blob: c5261bb1117f2e556162d5dc0cea1e79cae47656 [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
danielk197713adf8a2004-06-03 16:08:41 +0000453
drh107886a2008-11-21 22:21:50 +0000454/*
dan9359c7b2009-08-21 08:29:10 +0000455** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000456** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000457** vxworksFileId objects used by this file, all of which may be
458** shared by multiple threads.
459**
460** Function unixMutexHeld() is used to assert() that the global mutex
461** is held when required. This function is only used as part of assert()
462** statements. e.g.
463**
464** unixEnterMutex()
465** assert( unixMutexHeld() );
466** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000467*/
468static void unixEnterMutex(void){
469 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
470}
471static void unixLeaveMutex(void){
472 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
473}
dan9359c7b2009-08-21 08:29:10 +0000474#ifdef SQLITE_DEBUG
475static int unixMutexHeld(void) {
476 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
477}
478#endif
drh107886a2008-11-21 22:21:50 +0000479
drh734c9862008-11-28 15:37:20 +0000480
481#ifdef SQLITE_DEBUG
482/*
483** Helper function for printing out trace information from debugging
484** binaries. This returns the string represetation of the supplied
485** integer lock-type.
486*/
drh308c2a52010-05-14 11:30:18 +0000487static const char *azFileLock(int eFileLock){
488 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000489 case NO_LOCK: return "NONE";
490 case SHARED_LOCK: return "SHARED";
491 case RESERVED_LOCK: return "RESERVED";
492 case PENDING_LOCK: return "PENDING";
493 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000494 }
495 return "ERROR";
496}
497#endif
498
499#ifdef SQLITE_LOCK_TRACE
500/*
501** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000502**
drh734c9862008-11-28 15:37:20 +0000503** This routine is used for troubleshooting locks on multithreaded
504** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
505** command-line option on the compiler. This code is normally
506** turned off.
507*/
508static int lockTrace(int fd, int op, struct flock *p){
509 char *zOpName, *zType;
510 int s;
511 int savedErrno;
512 if( op==F_GETLK ){
513 zOpName = "GETLK";
514 }else if( op==F_SETLK ){
515 zOpName = "SETLK";
516 }else{
drh99ab3b12011-03-02 15:09:07 +0000517 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000518 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
519 return s;
520 }
521 if( p->l_type==F_RDLCK ){
522 zType = "RDLCK";
523 }else if( p->l_type==F_WRLCK ){
524 zType = "WRLCK";
525 }else if( p->l_type==F_UNLCK ){
526 zType = "UNLCK";
527 }else{
528 assert( 0 );
529 }
530 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000531 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000532 savedErrno = errno;
533 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
534 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
535 (int)p->l_pid, s);
536 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
537 struct flock l2;
538 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000539 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000540 if( l2.l_type==F_RDLCK ){
541 zType = "RDLCK";
542 }else if( l2.l_type==F_WRLCK ){
543 zType = "WRLCK";
544 }else if( l2.l_type==F_UNLCK ){
545 zType = "UNLCK";
546 }else{
547 assert( 0 );
548 }
549 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
550 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
551 }
552 errno = savedErrno;
553 return s;
554}
drh99ab3b12011-03-02 15:09:07 +0000555#undef osFcntl
556#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000557#endif /* SQLITE_LOCK_TRACE */
558
559
drhff812312011-02-23 13:33:46 +0000560/*
561** Retry ftruncate() calls that fail due to EINTR
562*/
563#ifdef EINTR
564static int robust_ftruncate(int h, sqlite3_int64 sz){
565 int rc;
drh99ab3b12011-03-02 15:09:07 +0000566 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000567 return rc;
568}
569#else
drh99ab3b12011-03-02 15:09:07 +0000570# define robust_ftruncate(a,b) osFtruncate(a,b)
drhff812312011-02-23 13:33:46 +0000571#endif
572
drh734c9862008-11-28 15:37:20 +0000573
574/*
575** This routine translates a standard POSIX errno code into something
576** useful to the clients of the sqlite3 functions. Specifically, it is
577** intended to translate a variety of "try again" errors into SQLITE_BUSY
578** and a variety of "please close the file descriptor NOW" errors into
579** SQLITE_IOERR
580**
581** Errors during initialization of locks, or file system support for locks,
582** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
583*/
584static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
585 switch (posixError) {
586 case 0:
587 return SQLITE_OK;
588
589 case EAGAIN:
590 case ETIMEDOUT:
591 case EBUSY:
592 case EINTR:
593 case ENOLCK:
594 /* random NFS retry error, unless during file system support
595 * introspection, in which it actually means what it says */
596 return SQLITE_BUSY;
597
598 case EACCES:
599 /* EACCES is like EAGAIN during locking operations, but not any other time*/
600 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
601 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
602 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
603 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
604 return SQLITE_BUSY;
605 }
606 /* else fall through */
607 case EPERM:
608 return SQLITE_PERM;
609
610 case EDEADLK:
611 return SQLITE_IOERR_BLOCKED;
612
613#if EOPNOTSUPP!=ENOTSUP
614 case EOPNOTSUPP:
615 /* something went terribly awry, unless during file system support
616 * introspection, in which it actually means what it says */
617#endif
618#ifdef ENOTSUP
619 case ENOTSUP:
620 /* invalid fd, unless during file system support introspection, in which
621 * it actually means what it says */
622#endif
623 case EIO:
624 case EBADF:
625 case EINVAL:
626 case ENOTCONN:
627 case ENODEV:
628 case ENXIO:
629 case ENOENT:
630 case ESTALE:
631 case ENOSYS:
632 /* these should force the client to close the file and reconnect */
633
634 default:
635 return sqliteIOErr;
636 }
637}
638
639
640
641/******************************************************************************
642****************** Begin Unique File ID Utility Used By VxWorks ***************
643**
644** On most versions of unix, we can get a unique ID for a file by concatenating
645** the device number and the inode number. But this does not work on VxWorks.
646** On VxWorks, a unique file id must be based on the canonical filename.
647**
648** A pointer to an instance of the following structure can be used as a
649** unique file ID in VxWorks. Each instance of this structure contains
650** a copy of the canonical filename. There is also a reference count.
651** The structure is reclaimed when the number of pointers to it drops to
652** zero.
653**
654** There are never very many files open at one time and lookups are not
655** a performance-critical path, so it is sufficient to put these
656** structures on a linked list.
657*/
658struct vxworksFileId {
659 struct vxworksFileId *pNext; /* Next in a list of them all */
660 int nRef; /* Number of references to this one */
661 int nName; /* Length of the zCanonicalName[] string */
662 char *zCanonicalName; /* Canonical filename */
663};
664
665#if OS_VXWORKS
666/*
drh9b35ea62008-11-29 02:20:26 +0000667** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000668** variable:
669*/
670static struct vxworksFileId *vxworksFileList = 0;
671
672/*
673** Simplify a filename into its canonical form
674** by making the following changes:
675**
676** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000677** * convert /./ into just /
678** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000679**
680** Changes are made in-place. Return the new name length.
681**
682** The original filename is in z[0..n-1]. Return the number of
683** characters in the simplified name.
684*/
685static int vxworksSimplifyName(char *z, int n){
686 int i, j;
687 while( n>1 && z[n-1]=='/' ){ n--; }
688 for(i=j=0; i<n; i++){
689 if( z[i]=='/' ){
690 if( z[i+1]=='/' ) continue;
691 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
692 i += 1;
693 continue;
694 }
695 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
696 while( j>0 && z[j-1]!='/' ){ j--; }
697 if( j>0 ){ j--; }
698 i += 2;
699 continue;
700 }
701 }
702 z[j++] = z[i];
703 }
704 z[j] = 0;
705 return j;
706}
707
708/*
709** Find a unique file ID for the given absolute pathname. Return
710** a pointer to the vxworksFileId object. This pointer is the unique
711** file ID.
712**
713** The nRef field of the vxworksFileId object is incremented before
714** the object is returned. A new vxworksFileId object is created
715** and added to the global list if necessary.
716**
717** If a memory allocation error occurs, return NULL.
718*/
719static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
720 struct vxworksFileId *pNew; /* search key and new file ID */
721 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
722 int n; /* Length of zAbsoluteName string */
723
724 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000725 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000726 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
727 if( pNew==0 ) return 0;
728 pNew->zCanonicalName = (char*)&pNew[1];
729 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
730 n = vxworksSimplifyName(pNew->zCanonicalName, n);
731
732 /* Search for an existing entry that matching the canonical name.
733 ** If found, increment the reference count and return a pointer to
734 ** the existing file ID.
735 */
736 unixEnterMutex();
737 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
738 if( pCandidate->nName==n
739 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
740 ){
741 sqlite3_free(pNew);
742 pCandidate->nRef++;
743 unixLeaveMutex();
744 return pCandidate;
745 }
746 }
747
748 /* No match was found. We will make a new file ID */
749 pNew->nRef = 1;
750 pNew->nName = n;
751 pNew->pNext = vxworksFileList;
752 vxworksFileList = pNew;
753 unixLeaveMutex();
754 return pNew;
755}
756
757/*
758** Decrement the reference count on a vxworksFileId object. Free
759** the object when the reference count reaches zero.
760*/
761static void vxworksReleaseFileId(struct vxworksFileId *pId){
762 unixEnterMutex();
763 assert( pId->nRef>0 );
764 pId->nRef--;
765 if( pId->nRef==0 ){
766 struct vxworksFileId **pp;
767 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
768 assert( *pp==pId );
769 *pp = pId->pNext;
770 sqlite3_free(pId);
771 }
772 unixLeaveMutex();
773}
774#endif /* OS_VXWORKS */
775/*************** End of Unique File ID Utility Used By VxWorks ****************
776******************************************************************************/
777
778
779/******************************************************************************
780*************************** Posix Advisory Locking ****************************
781**
drh9b35ea62008-11-29 02:20:26 +0000782** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000783** section 6.5.2.2 lines 483 through 490 specify that when a process
784** sets or clears a lock, that operation overrides any prior locks set
785** by the same process. It does not explicitly say so, but this implies
786** that it overrides locks set by the same process using a different
787** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000788**
789** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000790** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
791**
792** Suppose ./file1 and ./file2 are really the same file (because
793** one is a hard or symbolic link to the other) then if you set
794** an exclusive lock on fd1, then try to get an exclusive lock
795** on fd2, it works. I would have expected the second lock to
796** fail since there was already a lock on the file due to fd1.
797** But not so. Since both locks came from the same process, the
798** second overrides the first, even though they were on different
799** file descriptors opened on different file names.
800**
drh734c9862008-11-28 15:37:20 +0000801** This means that we cannot use POSIX locks to synchronize file access
802** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000803** to synchronize access for threads in separate processes, but not
804** threads within the same process.
805**
806** To work around the problem, SQLite has to manage file locks internally
807** on its own. Whenever a new database is opened, we have to find the
808** specific inode of the database file (the inode is determined by the
809** st_dev and st_ino fields of the stat structure that fstat() fills in)
810** and check for locks already existing on that inode. When locks are
811** created or removed, we have to look at our own internal record of the
812** locks to see if another thread has previously set a lock on that same
813** inode.
814**
drh9b35ea62008-11-29 02:20:26 +0000815** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
816** For VxWorks, we have to use the alternative unique ID system based on
817** canonical filename and implemented in the previous division.)
818**
danielk1977ad94b582007-08-20 06:44:22 +0000819** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000820** descriptor. It is now a structure that holds the integer file
821** descriptor and a pointer to a structure that describes the internal
822** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000823** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000824** point to the same locking structure. The locking structure keeps
825** a reference count (so we will know when to delete it) and a "cnt"
826** field that tells us its internal lock status. cnt==0 means the
827** file is unlocked. cnt==-1 means the file has an exclusive lock.
828** cnt>0 means there are cnt shared locks on the file.
829**
830** Any attempt to lock or unlock a file first checks the locking
831** structure. The fcntl() system call is only invoked to set a
832** POSIX lock if the internal lock structure transitions between
833** a locked and an unlocked state.
834**
drh734c9862008-11-28 15:37:20 +0000835** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000836**
837** If you close a file descriptor that points to a file that has locks,
838** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000839** released. To work around this problem, each unixInodeInfo object
840** maintains a count of the number of pending locks on tha inode.
841** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000842** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000843** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000844** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000845** be closed and that list is walked (and cleared) when the last lock
846** clears.
847**
drh9b35ea62008-11-29 02:20:26 +0000848** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000849**
drh9b35ea62008-11-29 02:20:26 +0000850** Many older versions of linux use the LinuxThreads library which is
851** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000852** A cannot be modified or overridden by a different thread B.
853** Only thread A can modify the lock. Locking behavior is correct
854** if the appliation uses the newer Native Posix Thread Library (NPTL)
855** on linux - with NPTL a lock created by thread A can override locks
856** in thread B. But there is no way to know at compile-time which
857** threading library is being used. So there is no way to know at
858** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000859** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000860** current process.
drh5fdae772004-06-29 03:29:00 +0000861**
drh8af6c222010-05-14 12:43:01 +0000862** SQLite used to support LinuxThreads. But support for LinuxThreads
863** was dropped beginning with version 3.7.0. SQLite will still work with
864** LinuxThreads provided that (1) there is no more than one connection
865** per database file in the same process and (2) database connections
866** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000867*/
868
869/*
870** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000871** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000872*/
873struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000874 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000875#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000876 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000877#else
drh107886a2008-11-21 22:21:50 +0000878 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000879#endif
880};
881
882/*
drhbbd42a62004-05-22 17:41:58 +0000883** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000884** inode. Or, on LinuxThreads, there is one of these structures for
885** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000886**
danielk1977ad94b582007-08-20 06:44:22 +0000887** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000888** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000889** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000890*/
drh8af6c222010-05-14 12:43:01 +0000891struct unixInodeInfo {
892 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000893 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000894 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000895 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000896 unixShmNode *pShmNode; /* Shared memory associated with this inode */
897 int nLock; /* Number of outstanding file locks */
898 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
899 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
900 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000901#if defined(SQLITE_ENABLE_LOCKING_STYLE)
902 unsigned long long sharedByte; /* for AFP simulated shared lock */
903#endif
drh6c7d5c52008-11-21 20:32:33 +0000904#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000905 sem_t *pSem; /* Named POSIX semaphore */
906 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000907#endif
drhbbd42a62004-05-22 17:41:58 +0000908};
909
drhda0e7682008-07-30 15:27:54 +0000910/*
drh8af6c222010-05-14 12:43:01 +0000911** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000912*/
drhd91c68f2010-05-14 14:52:25 +0000913static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000914
drh5fdae772004-06-29 03:29:00 +0000915/*
dane18d4952011-02-21 11:46:24 +0000916**
917** This function - unixLogError_x(), is only ever called via the macro
918** unixLogError().
919**
920** It is invoked after an error occurs in an OS function and errno has been
921** set. It logs a message using sqlite3_log() containing the current value of
922** errno and, if possible, the human-readable equivalent from strerror() or
923** strerror_r().
924**
925** The first argument passed to the macro should be the error code that
926** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
927** The two subsequent arguments should be the name of the OS function that
928** failed (e.g. "unlink", "open") and the the associated file-system path,
929** if any.
930*/
drh0e9365c2011-03-02 02:08:13 +0000931#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
932static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000933 int errcode, /* SQLite error code */
934 const char *zFunc, /* Name of OS function that failed */
935 const char *zPath, /* File path associated with error */
936 int iLine /* Source line number where error occurred */
937){
938 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000939 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000940
941 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
942 ** the strerror() function to obtain the human-readable error message
943 ** equivalent to errno. Otherwise, use strerror_r().
944 */
945#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
946 char aErr[80];
947 memset(aErr, 0, sizeof(aErr));
948 zErr = aErr;
949
950 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
951 ** assume that the system provides the the GNU version of strerror_r() that
952 ** returns a pointer to a buffer containing the error message. That pointer
953 ** may point to aErr[], or it may point to some static storage somewhere.
954 ** Otherwise, assume that the system provides the POSIX version of
955 ** strerror_r(), which always writes an error message into aErr[].
956 **
957 ** If the code incorrectly assumes that it is the POSIX version that is
958 ** available, the error message will often be an empty string. Not a
959 ** huge problem. Incorrectly concluding that the GNU version is available
960 ** could lead to a segfault though.
961 */
962#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
963 zErr =
964# endif
drh0e9365c2011-03-02 02:08:13 +0000965 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000966
967#elif SQLITE_THREADSAFE
968 /* This is a threadsafe build, but strerror_r() is not available. */
969 zErr = "";
970#else
971 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000972 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000973#endif
974
975 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000976 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000977 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000978 "os_unix.c:%d: (%d) %s(%s) - %s",
979 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000980 );
981
982 return errcode;
983}
984
drh0e9365c2011-03-02 02:08:13 +0000985/*
986** Close a file descriptor.
987**
988** We assume that close() almost always works, since it is only in a
989** very sick application or on a very sick platform that it might fail.
990** If it does fail, simply leak the file descriptor, but do log the
991** error.
992**
993** Note that it is not safe to retry close() after EINTR since the
994** file descriptor might have already been reused by another thread.
995** So we don't even try to recover from an EINTR. Just log the error
996** and move on.
997*/
998static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +0000999 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001000 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1001 pFile ? pFile->zPath : 0, lineno);
1002 }
1003}
dane18d4952011-02-21 11:46:24 +00001004
1005/*
danb0ac3e32010-06-16 10:55:42 +00001006** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001007*/
drh0e9365c2011-03-02 02:08:13 +00001008static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001009 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001010 UnixUnusedFd *p;
1011 UnixUnusedFd *pNext;
1012 for(p=pInode->pUnused; p; p=pNext){
1013 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001014 robust_close(pFile, p->fd, __LINE__);
1015 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001016 }
drh0e9365c2011-03-02 02:08:13 +00001017 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001018}
1019
1020/*
drh8af6c222010-05-14 12:43:01 +00001021** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001022**
1023** The mutex entered using the unixEnterMutex() function must be held
1024** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001025*/
danb0ac3e32010-06-16 10:55:42 +00001026static void releaseInodeInfo(unixFile *pFile){
1027 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001028 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001029 if( pInode ){
1030 pInode->nRef--;
1031 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001032 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001033 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001034 if( pInode->pPrev ){
1035 assert( pInode->pPrev->pNext==pInode );
1036 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001037 }else{
drh8af6c222010-05-14 12:43:01 +00001038 assert( inodeList==pInode );
1039 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001040 }
drh8af6c222010-05-14 12:43:01 +00001041 if( pInode->pNext ){
1042 assert( pInode->pNext->pPrev==pInode );
1043 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001044 }
drh8af6c222010-05-14 12:43:01 +00001045 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001046 }
drhbbd42a62004-05-22 17:41:58 +00001047 }
1048}
1049
1050/*
drh8af6c222010-05-14 12:43:01 +00001051** Given a file descriptor, locate the unixInodeInfo object that
1052** describes that file descriptor. Create a new one if necessary. The
1053** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001054**
dan9359c7b2009-08-21 08:29:10 +00001055** The mutex entered using the unixEnterMutex() function must be held
1056** when this function is called.
1057**
drh6c7d5c52008-11-21 20:32:33 +00001058** Return an appropriate error code.
1059*/
drh8af6c222010-05-14 12:43:01 +00001060static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001061 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001062 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001063){
1064 int rc; /* System call return code */
1065 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001066 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1067 struct stat statbuf; /* Low-level file information */
1068 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001069
dan9359c7b2009-08-21 08:29:10 +00001070 assert( unixMutexHeld() );
1071
drh6c7d5c52008-11-21 20:32:33 +00001072 /* Get low-level information about the file that we can used to
1073 ** create a unique name for the file.
1074 */
1075 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001076 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001077 if( rc!=0 ){
1078 pFile->lastErrno = errno;
1079#ifdef EOVERFLOW
1080 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1081#endif
1082 return SQLITE_IOERR;
1083 }
1084
drheb0d74f2009-02-03 15:27:02 +00001085#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001086 /* On OS X on an msdos filesystem, the inode number is reported
1087 ** incorrectly for zero-size files. See ticket #3260. To work
1088 ** around this problem (we consider it a bug in OS X, not SQLite)
1089 ** we always increase the file size to 1 by writing a single byte
1090 ** prior to accessing the inode number. The one byte written is
1091 ** an ASCII 'S' character which also happens to be the first byte
1092 ** in the header of every SQLite database. In this way, if there
1093 ** is a race condition such that another thread has already populated
1094 ** the first page of the database, no damage is done.
1095 */
drh7ed97b92010-01-20 13:07:21 +00001096 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001097 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001098 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001099 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001100 return SQLITE_IOERR;
1101 }
drh99ab3b12011-03-02 15:09:07 +00001102 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001103 if( rc!=0 ){
1104 pFile->lastErrno = errno;
1105 return SQLITE_IOERR;
1106 }
1107 }
drheb0d74f2009-02-03 15:27:02 +00001108#endif
drh6c7d5c52008-11-21 20:32:33 +00001109
drh8af6c222010-05-14 12:43:01 +00001110 memset(&fileId, 0, sizeof(fileId));
1111 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001112#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001113 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001114#else
drh8af6c222010-05-14 12:43:01 +00001115 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001116#endif
drh8af6c222010-05-14 12:43:01 +00001117 pInode = inodeList;
1118 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1119 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001120 }
drh8af6c222010-05-14 12:43:01 +00001121 if( pInode==0 ){
1122 pInode = sqlite3_malloc( sizeof(*pInode) );
1123 if( pInode==0 ){
1124 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001125 }
drh8af6c222010-05-14 12:43:01 +00001126 memset(pInode, 0, sizeof(*pInode));
1127 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1128 pInode->nRef = 1;
1129 pInode->pNext = inodeList;
1130 pInode->pPrev = 0;
1131 if( inodeList ) inodeList->pPrev = pInode;
1132 inodeList = pInode;
1133 }else{
1134 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001135 }
drh8af6c222010-05-14 12:43:01 +00001136 *ppInode = pInode;
1137 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001138}
drh6c7d5c52008-11-21 20:32:33 +00001139
aswift5b1a2562008-08-22 00:22:35 +00001140
1141/*
danielk197713adf8a2004-06-03 16:08:41 +00001142** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001143** file by this or any other process. If such a lock is held, set *pResOut
1144** to a non-zero value otherwise *pResOut is set to zero. The return value
1145** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001146*/
danielk1977861f7452008-06-05 11:39:11 +00001147static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001148 int rc = SQLITE_OK;
1149 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001150 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001151
danielk1977861f7452008-06-05 11:39:11 +00001152 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1153
drh054889e2005-11-30 03:20:31 +00001154 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001155 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001156
1157 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001158 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001159 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001160 }
1161
drh2ac3ee92004-06-07 16:27:46 +00001162 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001163 */
danielk197709480a92009-02-09 05:32:32 +00001164#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001165 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001166 struct flock lock;
1167 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001168 lock.l_start = RESERVED_BYTE;
1169 lock.l_len = 1;
1170 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001171 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001172 int tErrno = errno;
1173 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1174 pFile->lastErrno = tErrno;
1175 } else if( lock.l_type!=F_UNLCK ){
1176 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001177 }
1178 }
danielk197709480a92009-02-09 05:32:32 +00001179#endif
danielk197713adf8a2004-06-03 16:08:41 +00001180
drh6c7d5c52008-11-21 20:32:33 +00001181 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001182 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001183
aswift5b1a2562008-08-22 00:22:35 +00001184 *pResOut = reserved;
1185 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001186}
1187
1188/*
drh308c2a52010-05-14 11:30:18 +00001189** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001190** of the following:
1191**
drh2ac3ee92004-06-07 16:27:46 +00001192** (1) SHARED_LOCK
1193** (2) RESERVED_LOCK
1194** (3) PENDING_LOCK
1195** (4) EXCLUSIVE_LOCK
1196**
drhb3e04342004-06-08 00:47:47 +00001197** Sometimes when requesting one lock state, additional lock states
1198** are inserted in between. The locking might fail on one of the later
1199** transitions leaving the lock state different from what it started but
1200** still short of its goal. The following chart shows the allowed
1201** transitions and the inserted intermediate states:
1202**
1203** UNLOCKED -> SHARED
1204** SHARED -> RESERVED
1205** SHARED -> (PENDING) -> EXCLUSIVE
1206** RESERVED -> (PENDING) -> EXCLUSIVE
1207** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001208**
drha6abd042004-06-09 17:37:22 +00001209** This routine will only increase a lock. Use the sqlite3OsUnlock()
1210** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001211*/
drh308c2a52010-05-14 11:30:18 +00001212static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001213 /* The following describes the implementation of the various locks and
1214 ** lock transitions in terms of the POSIX advisory shared and exclusive
1215 ** lock primitives (called read-locks and write-locks below, to avoid
1216 ** confusion with SQLite lock names). The algorithms are complicated
1217 ** slightly in order to be compatible with windows systems simultaneously
1218 ** accessing the same database file, in case that is ever required.
1219 **
1220 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1221 ** byte', each single bytes at well known offsets, and the 'shared byte
1222 ** range', a range of 510 bytes at a well known offset.
1223 **
1224 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1225 ** byte'. If this is successful, a random byte from the 'shared byte
1226 ** range' is read-locked and the lock on the 'pending byte' released.
1227 **
danielk197790ba3bd2004-06-25 08:32:25 +00001228 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1229 ** A RESERVED lock is implemented by grabbing a write-lock on the
1230 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001231 **
1232 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001233 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1234 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1235 ** obtained, but existing SHARED locks are allowed to persist. A process
1236 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1237 ** This property is used by the algorithm for rolling back a journal file
1238 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001239 **
danielk197790ba3bd2004-06-25 08:32:25 +00001240 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1241 ** implemented by obtaining a write-lock on the entire 'shared byte
1242 ** range'. Since all other locks require a read-lock on one of the bytes
1243 ** within this range, this ensures that no other locks are held on the
1244 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001245 **
1246 ** The reason a single byte cannot be used instead of the 'shared byte
1247 ** range' is that some versions of windows do not support read-locks. By
1248 ** locking a random byte from a range, concurrent SHARED locks may exist
1249 ** even if the locking primitive used is always a write-lock.
1250 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001251 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001252 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001253 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001254 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001255 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001256 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001257
drh054889e2005-11-30 03:20:31 +00001258 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001259 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1260 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001261 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001262
1263 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001264 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001265 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001266 */
drh308c2a52010-05-14 11:30:18 +00001267 if( pFile->eFileLock>=eFileLock ){
1268 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1269 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001270 return SQLITE_OK;
1271 }
1272
drh0c2694b2009-09-03 16:23:44 +00001273 /* Make sure the locking sequence is correct.
1274 ** (1) We never move from unlocked to anything higher than shared lock.
1275 ** (2) SQLite never explicitly requests a pendig lock.
1276 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001277 */
drh308c2a52010-05-14 11:30:18 +00001278 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1279 assert( eFileLock!=PENDING_LOCK );
1280 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001281
drh8af6c222010-05-14 12:43:01 +00001282 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001283 */
drh6c7d5c52008-11-21 20:32:33 +00001284 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001285 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001286
danielk1977ad94b582007-08-20 06:44:22 +00001287 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001288 ** handle that precludes the requested lock, return BUSY.
1289 */
drh8af6c222010-05-14 12:43:01 +00001290 if( (pFile->eFileLock!=pInode->eFileLock &&
1291 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001292 ){
1293 rc = SQLITE_BUSY;
1294 goto end_lock;
1295 }
1296
1297 /* If a SHARED lock is requested, and some thread using this PID already
1298 ** has a SHARED or RESERVED lock, then increment reference counts and
1299 ** return SQLITE_OK.
1300 */
drh308c2a52010-05-14 11:30:18 +00001301 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001302 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001303 assert( eFileLock==SHARED_LOCK );
1304 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001305 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001306 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001307 pInode->nShared++;
1308 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001309 goto end_lock;
1310 }
1311
danielk19779a1d0ab2004-06-01 14:09:28 +00001312
drh3cde3bb2004-06-12 02:17:14 +00001313 /* A PENDING lock is needed before acquiring a SHARED lock and before
1314 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1315 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 */
drh0c2694b2009-09-03 16:23:44 +00001317 lock.l_len = 1L;
1318 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001319 if( eFileLock==SHARED_LOCK
1320 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001321 ){
drh308c2a52010-05-14 11:30:18 +00001322 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001323 lock.l_start = PENDING_BYTE;
drh99ab3b12011-03-02 15:09:07 +00001324 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001325 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001326 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001327 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1328 if( IS_LOCK_ERROR(rc) ){
1329 pFile->lastErrno = tErrno;
1330 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001331 goto end_lock;
1332 }
drh3cde3bb2004-06-12 02:17:14 +00001333 }
1334
1335
1336 /* If control gets to this point, then actually go ahead and make
1337 ** operating system calls for the specified lock.
1338 */
drh308c2a52010-05-14 11:30:18 +00001339 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001340 assert( pInode->nShared==0 );
1341 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001342
drh2ac3ee92004-06-07 16:27:46 +00001343 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001344 lock.l_start = SHARED_FIRST;
1345 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001346 if( (s = osFcntl(pFile->h, F_SETLK, &lock))==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001347 tErrno = errno;
1348 }
drh2ac3ee92004-06-07 16:27:46 +00001349 /* Drop the temporary PENDING lock */
1350 lock.l_start = PENDING_BYTE;
1351 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001352 lock.l_type = F_UNLCK;
drh99ab3b12011-03-02 15:09:07 +00001353 if( osFcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001354 if( s != -1 ){
1355 /* This could happen with a network mount */
1356 tErrno = errno;
1357 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1358 if( IS_LOCK_ERROR(rc) ){
1359 pFile->lastErrno = tErrno;
1360 }
1361 goto end_lock;
1362 }
drh2b4b5962005-06-15 17:47:55 +00001363 }
drhe2396a12007-03-29 20:19:58 +00001364 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001365 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1366 if( IS_LOCK_ERROR(rc) ){
1367 pFile->lastErrno = tErrno;
1368 }
drhbbd42a62004-05-22 17:41:58 +00001369 }else{
drh308c2a52010-05-14 11:30:18 +00001370 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001371 pInode->nLock++;
1372 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001373 }
drh8af6c222010-05-14 12:43:01 +00001374 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001375 /* We are trying for an exclusive lock but another thread in this
1376 ** same process is still holding a shared lock. */
1377 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001378 }else{
drh3cde3bb2004-06-12 02:17:14 +00001379 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001380 ** assumed that there is a SHARED or greater lock on the file
1381 ** already.
1382 */
drh308c2a52010-05-14 11:30:18 +00001383 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001384 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001385 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001386 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001387 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001389 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001390 lock.l_start = SHARED_FIRST;
1391 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001392 break;
1393 default:
1394 assert(0);
1395 }
drh99ab3b12011-03-02 15:09:07 +00001396 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001397 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001398 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001399 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1400 if( IS_LOCK_ERROR(rc) ){
1401 pFile->lastErrno = tErrno;
1402 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001403 }
drhbbd42a62004-05-22 17:41:58 +00001404 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001405
drh8f941bc2009-01-14 23:03:40 +00001406
1407#ifndef NDEBUG
1408 /* Set up the transaction-counter change checking flags when
1409 ** transitioning from a SHARED to a RESERVED lock. The change
1410 ** from SHARED to RESERVED marks the beginning of a normal
1411 ** write operation (not a hot journal rollback).
1412 */
1413 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001414 && pFile->eFileLock<=SHARED_LOCK
1415 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001416 ){
1417 pFile->transCntrChng = 0;
1418 pFile->dbUpdate = 0;
1419 pFile->inNormalWrite = 1;
1420 }
1421#endif
1422
1423
danielk1977ecb2a962004-06-02 06:30:16 +00001424 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001425 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001426 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001427 }else if( eFileLock==EXCLUSIVE_LOCK ){
1428 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001429 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001430 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001431
1432end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001433 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001434 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1435 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001436 return rc;
1437}
1438
1439/*
dan08da86a2009-08-21 17:18:03 +00001440** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001441** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001442*/
1443static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001444 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001445 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001446 p->pNext = pInode->pUnused;
1447 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001448 pFile->h = -1;
1449 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001450}
1451
1452/*
drh308c2a52010-05-14 11:30:18 +00001453** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001454** must be either NO_LOCK or SHARED_LOCK.
1455**
1456** If the locking level of the file descriptor is already at or below
1457** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001458**
1459** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1460** the byte range is divided into 2 parts and the first part is unlocked then
1461** set to a read lock, then the other part is simply unlocked. This works
1462** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1463** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001464*/
drh308c2a52010-05-14 11:30:18 +00001465static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001466 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001467 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001468 struct flock lock;
1469 int rc = SQLITE_OK;
1470 int h;
drh0c2694b2009-09-03 16:23:44 +00001471 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001472
drh054889e2005-11-30 03:20:31 +00001473 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001474 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001475 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001476 getpid()));
drha6abd042004-06-09 17:37:22 +00001477
drh308c2a52010-05-14 11:30:18 +00001478 assert( eFileLock<=SHARED_LOCK );
1479 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001480 return SQLITE_OK;
1481 }
drh6c7d5c52008-11-21 20:32:33 +00001482 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001483 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001484 pInode = pFile->pInode;
1485 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001486 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001487 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001488 SimulateIOErrorBenign(1);
1489 SimulateIOError( h=(-1) )
1490 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001491
1492#ifndef NDEBUG
1493 /* When reducing a lock such that other processes can start
1494 ** reading the database file again, make sure that the
1495 ** transaction counter was updated if any part of the database
1496 ** file changed. If the transaction counter is not updated,
1497 ** other connections to the same file might not realize that
1498 ** the file has changed and hence might not know to flush their
1499 ** cache. The use of a stale cache can lead to database corruption.
1500 */
dan7c246102010-04-12 19:00:29 +00001501#if 0
drh8f941bc2009-01-14 23:03:40 +00001502 assert( pFile->inNormalWrite==0
1503 || pFile->dbUpdate==0
1504 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001505#endif
drh8f941bc2009-01-14 23:03:40 +00001506 pFile->inNormalWrite = 0;
1507#endif
1508
drh7ed97b92010-01-20 13:07:21 +00001509 /* downgrading to a shared lock on NFS involves clearing the write lock
1510 ** before establishing the readlock - to avoid a race condition we downgrade
1511 ** the lock in 2 blocks, so that part of the range will be covered by a
1512 ** write lock until the rest is covered by a read lock:
1513 ** 1: [WWWWW]
1514 ** 2: [....W]
1515 ** 3: [RRRRW]
1516 ** 4: [RRRR.]
1517 */
drh308c2a52010-05-14 11:30:18 +00001518 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001519
1520#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1521 assert( handleNFSUnlock==0 );
1522#endif
1523#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001524 if( handleNFSUnlock ){
1525 off_t divSize = SHARED_SIZE - 1;
1526
1527 lock.l_type = F_UNLCK;
1528 lock.l_whence = SEEK_SET;
1529 lock.l_start = SHARED_FIRST;
1530 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001531 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001532 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001533 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1534 if( IS_LOCK_ERROR(rc) ){
1535 pFile->lastErrno = tErrno;
1536 }
1537 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001538 }
drh7ed97b92010-01-20 13:07:21 +00001539 lock.l_type = F_RDLCK;
1540 lock.l_whence = SEEK_SET;
1541 lock.l_start = SHARED_FIRST;
1542 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001543 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001544 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001545 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1546 if( IS_LOCK_ERROR(rc) ){
1547 pFile->lastErrno = tErrno;
1548 }
1549 goto end_unlock;
1550 }
1551 lock.l_type = F_UNLCK;
1552 lock.l_whence = SEEK_SET;
1553 lock.l_start = SHARED_FIRST+divSize;
1554 lock.l_len = SHARED_SIZE-divSize;
drh99ab3b12011-03-02 15:09:07 +00001555 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001556 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001557 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1558 if( IS_LOCK_ERROR(rc) ){
1559 pFile->lastErrno = tErrno;
1560 }
1561 goto end_unlock;
1562 }
drh30f776f2011-02-25 03:25:07 +00001563 }else
1564#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1565 {
drh7ed97b92010-01-20 13:07:21 +00001566 lock.l_type = F_RDLCK;
1567 lock.l_whence = SEEK_SET;
1568 lock.l_start = SHARED_FIRST;
1569 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001570 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001571 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001572 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1573 if( IS_LOCK_ERROR(rc) ){
1574 pFile->lastErrno = tErrno;
1575 }
1576 goto end_unlock;
1577 }
drh9c105bb2004-10-02 20:38:28 +00001578 }
1579 }
drhbbd42a62004-05-22 17:41:58 +00001580 lock.l_type = F_UNLCK;
1581 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001582 lock.l_start = PENDING_BYTE;
1583 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh99ab3b12011-03-02 15:09:07 +00001584 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001585 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001586 }else{
drh0c2694b2009-09-03 16:23:44 +00001587 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001588 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1589 if( IS_LOCK_ERROR(rc) ){
1590 pFile->lastErrno = tErrno;
1591 }
drhcd731cf2009-03-28 23:23:02 +00001592 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001593 }
drhbbd42a62004-05-22 17:41:58 +00001594 }
drh308c2a52010-05-14 11:30:18 +00001595 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001596 /* Decrement the shared lock counter. Release the lock using an
1597 ** OS call only when all threads in this same process have released
1598 ** the lock.
1599 */
drh8af6c222010-05-14 12:43:01 +00001600 pInode->nShared--;
1601 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001602 lock.l_type = F_UNLCK;
1603 lock.l_whence = SEEK_SET;
1604 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001605 SimulateIOErrorBenign(1);
1606 SimulateIOError( h=(-1) )
1607 SimulateIOErrorBenign(0);
drh99ab3b12011-03-02 15:09:07 +00001608 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001609 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001610 }else{
drh0c2694b2009-09-03 16:23:44 +00001611 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001612 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001613 if( IS_LOCK_ERROR(rc) ){
1614 pFile->lastErrno = tErrno;
1615 }
drh8af6c222010-05-14 12:43:01 +00001616 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001617 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001618 }
drha6abd042004-06-09 17:37:22 +00001619 }
1620
drhbbd42a62004-05-22 17:41:58 +00001621 /* Decrement the count of locks against this same file. When the
1622 ** count reaches zero, close any other file descriptors whose close
1623 ** was deferred because of outstanding locks.
1624 */
drh8af6c222010-05-14 12:43:01 +00001625 pInode->nLock--;
1626 assert( pInode->nLock>=0 );
1627 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001628 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001629 }
1630 }
aswift5b1a2562008-08-22 00:22:35 +00001631
1632end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001633 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001634 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001635 return rc;
drhbbd42a62004-05-22 17:41:58 +00001636}
1637
1638/*
drh308c2a52010-05-14 11:30:18 +00001639** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001640** must be either NO_LOCK or SHARED_LOCK.
1641**
1642** If the locking level of the file descriptor is already at or below
1643** the requested locking level, this routine is a no-op.
1644*/
drh308c2a52010-05-14 11:30:18 +00001645static int unixUnlock(sqlite3_file *id, int eFileLock){
1646 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001647}
1648
1649/*
danielk1977e339d652008-06-28 11:23:00 +00001650** This function performs the parts of the "close file" operation
1651** common to all locking schemes. It closes the directory and file
1652** handles, if they are valid, and sets all fields of the unixFile
1653** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001654**
1655** It is *not* necessary to hold the mutex when this routine is called,
1656** even on VxWorks. A mutex will be acquired on VxWorks by the
1657** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001658*/
1659static int closeUnixFile(sqlite3_file *id){
1660 unixFile *pFile = (unixFile*)id;
1661 if( pFile ){
1662 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001663 robust_close(pFile, pFile->dirfd, __LINE__);
1664 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001665 }
1666 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001667 robust_close(pFile, pFile->h, __LINE__);
1668 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001669 }
drh6c7d5c52008-11-21 20:32:33 +00001670#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001671 if( pFile->pId ){
1672 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001673 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001674 }
drh107886a2008-11-21 22:21:50 +00001675 vxworksReleaseFileId(pFile->pId);
1676 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001677 }
1678#endif
drhff59a112010-05-14 20:15:51 +00001679 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001680 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001681 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001682 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001683 }
1684 return SQLITE_OK;
1685}
1686
1687/*
danielk1977e3026632004-06-22 11:29:02 +00001688** Close a file.
1689*/
danielk197762079062007-08-15 17:08:46 +00001690static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001691 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001692 if( id ){
1693 unixFile *pFile = (unixFile *)id;
1694 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001695 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001696 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001697 /* If there are outstanding locks, do not actually close the file just
1698 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001699 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001700 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001701 */
dan08da86a2009-08-21 17:18:03 +00001702 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001703 }
danb0ac3e32010-06-16 10:55:42 +00001704 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001705 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001706 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001707 }
aswiftaebf4132008-11-21 00:10:35 +00001708 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001709}
1710
drh734c9862008-11-28 15:37:20 +00001711/************** End of the posix advisory lock implementation *****************
1712******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001713
drh734c9862008-11-28 15:37:20 +00001714/******************************************************************************
1715****************************** No-op Locking **********************************
1716**
1717** Of the various locking implementations available, this is by far the
1718** simplest: locking is ignored. No attempt is made to lock the database
1719** file for reading or writing.
1720**
1721** This locking mode is appropriate for use on read-only databases
1722** (ex: databases that are burned into CD-ROM, for example.) It can
1723** also be used if the application employs some external mechanism to
1724** prevent simultaneous access of the same database by two or more
1725** database connections. But there is a serious risk of database
1726** corruption if this locking mode is used in situations where multiple
1727** database connections are accessing the same database file at the same
1728** time and one or more of those connections are writing.
1729*/
drhbfe66312006-10-03 17:40:40 +00001730
drh734c9862008-11-28 15:37:20 +00001731static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1732 UNUSED_PARAMETER(NotUsed);
1733 *pResOut = 0;
1734 return SQLITE_OK;
1735}
drh734c9862008-11-28 15:37:20 +00001736static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1737 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1738 return SQLITE_OK;
1739}
drh734c9862008-11-28 15:37:20 +00001740static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1741 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1742 return SQLITE_OK;
1743}
1744
1745/*
drh9b35ea62008-11-29 02:20:26 +00001746** Close the file.
drh734c9862008-11-28 15:37:20 +00001747*/
1748static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001749 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001750}
1751
1752/******************* End of the no-op lock implementation *********************
1753******************************************************************************/
1754
1755/******************************************************************************
1756************************* Begin dot-file Locking ******************************
1757**
drh0c2694b2009-09-03 16:23:44 +00001758** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001759** files in order to control access to the database. This works on just
1760** about every filesystem imaginable. But there are serious downsides:
1761**
1762** (1) There is zero concurrency. A single reader blocks all other
1763** connections from reading or writing the database.
1764**
1765** (2) An application crash or power loss can leave stale lock files
1766** sitting around that need to be cleared manually.
1767**
1768** Nevertheless, a dotlock is an appropriate locking mode for use if no
1769** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001770**
1771** Dotfile locking works by creating a file in the same directory as the
1772** database and with the same name but with a ".lock" extension added.
1773** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1774** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001775*/
1776
1777/*
1778** The file suffix added to the data base filename in order to create the
1779** lock file.
1780*/
1781#define DOTLOCK_SUFFIX ".lock"
1782
drh7708e972008-11-29 00:56:52 +00001783/*
1784** This routine checks if there is a RESERVED lock held on the specified
1785** file by this or any other process. If such a lock is held, set *pResOut
1786** to a non-zero value otherwise *pResOut is set to zero. The return value
1787** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1788**
1789** In dotfile locking, either a lock exists or it does not. So in this
1790** variation of CheckReservedLock(), *pResOut is set to true if any lock
1791** is held on the file and false if the file is unlocked.
1792*/
drh734c9862008-11-28 15:37:20 +00001793static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1794 int rc = SQLITE_OK;
1795 int reserved = 0;
1796 unixFile *pFile = (unixFile*)id;
1797
1798 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1799
1800 assert( pFile );
1801
1802 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001803 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001804 /* Either this connection or some other connection in the same process
1805 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001806 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001807 }else{
1808 /* The lock is held if and only if the lockfile exists */
1809 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001810 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001811 }
drh308c2a52010-05-14 11:30:18 +00001812 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001813 *pResOut = reserved;
1814 return rc;
1815}
1816
drh7708e972008-11-29 00:56:52 +00001817/*
drh308c2a52010-05-14 11:30:18 +00001818** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001819** of the following:
1820**
1821** (1) SHARED_LOCK
1822** (2) RESERVED_LOCK
1823** (3) PENDING_LOCK
1824** (4) EXCLUSIVE_LOCK
1825**
1826** Sometimes when requesting one lock state, additional lock states
1827** are inserted in between. The locking might fail on one of the later
1828** transitions leaving the lock state different from what it started but
1829** still short of its goal. The following chart shows the allowed
1830** transitions and the inserted intermediate states:
1831**
1832** UNLOCKED -> SHARED
1833** SHARED -> RESERVED
1834** SHARED -> (PENDING) -> EXCLUSIVE
1835** RESERVED -> (PENDING) -> EXCLUSIVE
1836** PENDING -> EXCLUSIVE
1837**
1838** This routine will only increase a lock. Use the sqlite3OsUnlock()
1839** routine to lower a locking level.
1840**
1841** With dotfile locking, we really only support state (4): EXCLUSIVE.
1842** But we track the other locking levels internally.
1843*/
drh308c2a52010-05-14 11:30:18 +00001844static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001845 unixFile *pFile = (unixFile*)id;
1846 int fd;
1847 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001848 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001849
drh7708e972008-11-29 00:56:52 +00001850
1851 /* If we have any lock, then the lock file already exists. All we have
1852 ** to do is adjust our internal record of the lock level.
1853 */
drh308c2a52010-05-14 11:30:18 +00001854 if( pFile->eFileLock > NO_LOCK ){
1855 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001856#if !OS_VXWORKS
1857 /* Always update the timestamp on the old file */
1858 utimes(zLockFile, NULL);
1859#endif
drh7708e972008-11-29 00:56:52 +00001860 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001861 }
1862
1863 /* grab an exclusive lock */
drh99ab3b12011-03-02 15:09:07 +00001864 fd = osOpen(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001865 if( fd<0 ){
1866 /* failed to open/create the file, someone else may have stolen the lock */
1867 int tErrno = errno;
1868 if( EEXIST == tErrno ){
1869 rc = SQLITE_BUSY;
1870 } else {
1871 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1872 if( IS_LOCK_ERROR(rc) ){
1873 pFile->lastErrno = tErrno;
1874 }
1875 }
drh7708e972008-11-29 00:56:52 +00001876 return rc;
drh734c9862008-11-28 15:37:20 +00001877 }
drh0e9365c2011-03-02 02:08:13 +00001878 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001879
1880 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001881 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001882 return rc;
1883}
1884
drh7708e972008-11-29 00:56:52 +00001885/*
drh308c2a52010-05-14 11:30:18 +00001886** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001887** must be either NO_LOCK or SHARED_LOCK.
1888**
1889** If the locking level of the file descriptor is already at or below
1890** the requested locking level, this routine is a no-op.
1891**
1892** When the locking level reaches NO_LOCK, delete the lock file.
1893*/
drh308c2a52010-05-14 11:30:18 +00001894static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001895 unixFile *pFile = (unixFile*)id;
1896 char *zLockFile = (char *)pFile->lockingContext;
1897
1898 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001899 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1900 pFile->eFileLock, getpid()));
1901 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001902
1903 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001904 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001905 return SQLITE_OK;
1906 }
drh7708e972008-11-29 00:56:52 +00001907
1908 /* To downgrade to shared, simply update our internal notion of the
1909 ** lock state. No need to mess with the file on disk.
1910 */
drh308c2a52010-05-14 11:30:18 +00001911 if( eFileLock==SHARED_LOCK ){
1912 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001913 return SQLITE_OK;
1914 }
1915
drh7708e972008-11-29 00:56:52 +00001916 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001917 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001918 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001919 int rc = 0;
1920 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001921 if( ENOENT != tErrno ){
1922 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1923 }
1924 if( IS_LOCK_ERROR(rc) ){
1925 pFile->lastErrno = tErrno;
1926 }
1927 return rc;
1928 }
drh308c2a52010-05-14 11:30:18 +00001929 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001930 return SQLITE_OK;
1931}
1932
1933/*
drh9b35ea62008-11-29 02:20:26 +00001934** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001935*/
1936static int dotlockClose(sqlite3_file *id) {
1937 int rc;
1938 if( id ){
1939 unixFile *pFile = (unixFile*)id;
1940 dotlockUnlock(id, NO_LOCK);
1941 sqlite3_free(pFile->lockingContext);
1942 }
drh734c9862008-11-28 15:37:20 +00001943 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001944 return rc;
1945}
1946/****************** End of the dot-file lock implementation *******************
1947******************************************************************************/
1948
1949/******************************************************************************
1950************************** Begin flock Locking ********************************
1951**
1952** Use the flock() system call to do file locking.
1953**
drh6b9d6dd2008-12-03 19:34:47 +00001954** flock() locking is like dot-file locking in that the various
1955** fine-grain locking levels supported by SQLite are collapsed into
1956** a single exclusive lock. In other words, SHARED, RESERVED, and
1957** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1958** still works when you do this, but concurrency is reduced since
1959** only a single process can be reading the database at a time.
1960**
drh734c9862008-11-28 15:37:20 +00001961** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1962** compiling for VXWORKS.
1963*/
1964#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001965
drh6b9d6dd2008-12-03 19:34:47 +00001966/*
drhff812312011-02-23 13:33:46 +00001967** Retry flock() calls that fail with EINTR
1968*/
1969#ifdef EINTR
1970static int robust_flock(int fd, int op){
1971 int rc;
1972 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
1973 return rc;
1974}
1975#else
drh5c819272011-02-23 14:00:12 +00001976# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00001977#endif
1978
1979
1980/*
drh6b9d6dd2008-12-03 19:34:47 +00001981** This routine checks if there is a RESERVED lock held on the specified
1982** file by this or any other process. If such a lock is held, set *pResOut
1983** to a non-zero value otherwise *pResOut is set to zero. The return value
1984** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1985*/
drh734c9862008-11-28 15:37:20 +00001986static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1987 int rc = SQLITE_OK;
1988 int reserved = 0;
1989 unixFile *pFile = (unixFile*)id;
1990
1991 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1992
1993 assert( pFile );
1994
1995 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001996 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001997 reserved = 1;
1998 }
1999
2000 /* Otherwise see if some other process holds it. */
2001 if( !reserved ){
2002 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002003 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002004 if( !lrc ){
2005 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002006 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002007 if ( lrc ) {
2008 int tErrno = errno;
2009 /* unlock failed with an error */
2010 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2011 if( IS_LOCK_ERROR(lrc) ){
2012 pFile->lastErrno = tErrno;
2013 rc = lrc;
2014 }
2015 }
2016 } else {
2017 int tErrno = errno;
2018 reserved = 1;
2019 /* someone else might have it reserved */
2020 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2021 if( IS_LOCK_ERROR(lrc) ){
2022 pFile->lastErrno = tErrno;
2023 rc = lrc;
2024 }
2025 }
2026 }
drh308c2a52010-05-14 11:30:18 +00002027 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002028
2029#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2030 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2031 rc = SQLITE_OK;
2032 reserved=1;
2033 }
2034#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2035 *pResOut = reserved;
2036 return rc;
2037}
2038
drh6b9d6dd2008-12-03 19:34:47 +00002039/*
drh308c2a52010-05-14 11:30:18 +00002040** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002041** of the following:
2042**
2043** (1) SHARED_LOCK
2044** (2) RESERVED_LOCK
2045** (3) PENDING_LOCK
2046** (4) EXCLUSIVE_LOCK
2047**
2048** Sometimes when requesting one lock state, additional lock states
2049** are inserted in between. The locking might fail on one of the later
2050** transitions leaving the lock state different from what it started but
2051** still short of its goal. The following chart shows the allowed
2052** transitions and the inserted intermediate states:
2053**
2054** UNLOCKED -> SHARED
2055** SHARED -> RESERVED
2056** SHARED -> (PENDING) -> EXCLUSIVE
2057** RESERVED -> (PENDING) -> EXCLUSIVE
2058** PENDING -> EXCLUSIVE
2059**
2060** flock() only really support EXCLUSIVE locks. We track intermediate
2061** lock states in the sqlite3_file structure, but all locks SHARED or
2062** above are really EXCLUSIVE locks and exclude all other processes from
2063** access the file.
2064**
2065** This routine will only increase a lock. Use the sqlite3OsUnlock()
2066** routine to lower a locking level.
2067*/
drh308c2a52010-05-14 11:30:18 +00002068static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002069 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002070 unixFile *pFile = (unixFile*)id;
2071
2072 assert( pFile );
2073
2074 /* if we already have a lock, it is exclusive.
2075 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002076 if (pFile->eFileLock > NO_LOCK) {
2077 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002078 return SQLITE_OK;
2079 }
2080
2081 /* grab an exclusive lock */
2082
drhff812312011-02-23 13:33:46 +00002083 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002084 int tErrno = errno;
2085 /* didn't get, must be busy */
2086 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2087 if( IS_LOCK_ERROR(rc) ){
2088 pFile->lastErrno = tErrno;
2089 }
2090 } else {
2091 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002092 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002093 }
drh308c2a52010-05-14 11:30:18 +00002094 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2095 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002096#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2097 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2098 rc = SQLITE_BUSY;
2099 }
2100#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2101 return rc;
2102}
2103
drh6b9d6dd2008-12-03 19:34:47 +00002104
2105/*
drh308c2a52010-05-14 11:30:18 +00002106** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002107** must be either NO_LOCK or SHARED_LOCK.
2108**
2109** If the locking level of the file descriptor is already at or below
2110** the requested locking level, this routine is a no-op.
2111*/
drh308c2a52010-05-14 11:30:18 +00002112static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002113 unixFile *pFile = (unixFile*)id;
2114
2115 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002116 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2117 pFile->eFileLock, getpid()));
2118 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002119
2120 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002121 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002122 return SQLITE_OK;
2123 }
2124
2125 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002126 if (eFileLock==SHARED_LOCK) {
2127 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002128 return SQLITE_OK;
2129 }
2130
2131 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002132 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002133 if (rc) {
2134 int r, tErrno = errno;
2135 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2136 if( IS_LOCK_ERROR(r) ){
2137 pFile->lastErrno = tErrno;
2138 }
2139#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2140 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2141 r = SQLITE_BUSY;
2142 }
2143#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2144
2145 return r;
2146 } else {
drh308c2a52010-05-14 11:30:18 +00002147 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002148 return SQLITE_OK;
2149 }
2150}
2151
2152/*
2153** Close a file.
2154*/
2155static int flockClose(sqlite3_file *id) {
2156 if( id ){
2157 flockUnlock(id, NO_LOCK);
2158 }
2159 return closeUnixFile(id);
2160}
2161
2162#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2163
2164/******************* End of the flock lock implementation *********************
2165******************************************************************************/
2166
2167/******************************************************************************
2168************************ Begin Named Semaphore Locking ************************
2169**
2170** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002171**
2172** Semaphore locking is like dot-lock and flock in that it really only
2173** supports EXCLUSIVE locking. Only a single process can read or write
2174** the database file at a time. This reduces potential concurrency, but
2175** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002176*/
2177#if OS_VXWORKS
2178
drh6b9d6dd2008-12-03 19:34:47 +00002179/*
2180** This routine checks if there is a RESERVED lock held on the specified
2181** file by this or any other process. If such a lock is held, set *pResOut
2182** to a non-zero value otherwise *pResOut is set to zero. The return value
2183** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2184*/
drh734c9862008-11-28 15:37:20 +00002185static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2186 int rc = SQLITE_OK;
2187 int reserved = 0;
2188 unixFile *pFile = (unixFile*)id;
2189
2190 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2191
2192 assert( pFile );
2193
2194 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002195 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002196 reserved = 1;
2197 }
2198
2199 /* Otherwise see if some other process holds it. */
2200 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002201 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002202 struct stat statBuf;
2203
2204 if( sem_trywait(pSem)==-1 ){
2205 int tErrno = errno;
2206 if( EAGAIN != tErrno ){
2207 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2208 pFile->lastErrno = tErrno;
2209 } else {
2210 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002211 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002212 }
2213 }else{
2214 /* we could have it if we want it */
2215 sem_post(pSem);
2216 }
2217 }
drh308c2a52010-05-14 11:30:18 +00002218 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002219
2220 *pResOut = reserved;
2221 return rc;
2222}
2223
drh6b9d6dd2008-12-03 19:34:47 +00002224/*
drh308c2a52010-05-14 11:30:18 +00002225** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002226** of the following:
2227**
2228** (1) SHARED_LOCK
2229** (2) RESERVED_LOCK
2230** (3) PENDING_LOCK
2231** (4) EXCLUSIVE_LOCK
2232**
2233** Sometimes when requesting one lock state, additional lock states
2234** are inserted in between. The locking might fail on one of the later
2235** transitions leaving the lock state different from what it started but
2236** still short of its goal. The following chart shows the allowed
2237** transitions and the inserted intermediate states:
2238**
2239** UNLOCKED -> SHARED
2240** SHARED -> RESERVED
2241** SHARED -> (PENDING) -> EXCLUSIVE
2242** RESERVED -> (PENDING) -> EXCLUSIVE
2243** PENDING -> EXCLUSIVE
2244**
2245** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2246** lock states in the sqlite3_file structure, but all locks SHARED or
2247** above are really EXCLUSIVE locks and exclude all other processes from
2248** access the file.
2249**
2250** This routine will only increase a lock. Use the sqlite3OsUnlock()
2251** routine to lower a locking level.
2252*/
drh308c2a52010-05-14 11:30:18 +00002253static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002254 unixFile *pFile = (unixFile*)id;
2255 int fd;
drh8af6c222010-05-14 12:43:01 +00002256 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002257 int rc = SQLITE_OK;
2258
2259 /* if we already have a lock, it is exclusive.
2260 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002261 if (pFile->eFileLock > NO_LOCK) {
2262 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002263 rc = SQLITE_OK;
2264 goto sem_end_lock;
2265 }
2266
2267 /* lock semaphore now but bail out when already locked. */
2268 if( sem_trywait(pSem)==-1 ){
2269 rc = SQLITE_BUSY;
2270 goto sem_end_lock;
2271 }
2272
2273 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002274 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002275
2276 sem_end_lock:
2277 return rc;
2278}
2279
drh6b9d6dd2008-12-03 19:34:47 +00002280/*
drh308c2a52010-05-14 11:30:18 +00002281** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002282** must be either NO_LOCK or SHARED_LOCK.
2283**
2284** If the locking level of the file descriptor is already at or below
2285** the requested locking level, this routine is a no-op.
2286*/
drh308c2a52010-05-14 11:30:18 +00002287static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002288 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002289 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002290
2291 assert( pFile );
2292 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002293 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2294 pFile->eFileLock, getpid()));
2295 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002296
2297 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002298 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002299 return SQLITE_OK;
2300 }
2301
2302 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002303 if (eFileLock==SHARED_LOCK) {
2304 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002305 return SQLITE_OK;
2306 }
2307
2308 /* no, really unlock. */
2309 if ( sem_post(pSem)==-1 ) {
2310 int rc, tErrno = errno;
2311 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2312 if( IS_LOCK_ERROR(rc) ){
2313 pFile->lastErrno = tErrno;
2314 }
2315 return rc;
2316 }
drh308c2a52010-05-14 11:30:18 +00002317 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002318 return SQLITE_OK;
2319}
2320
2321/*
2322 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002323 */
drh734c9862008-11-28 15:37:20 +00002324static int semClose(sqlite3_file *id) {
2325 if( id ){
2326 unixFile *pFile = (unixFile*)id;
2327 semUnlock(id, NO_LOCK);
2328 assert( pFile );
2329 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002330 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002331 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002332 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002333 }
2334 return SQLITE_OK;
2335}
2336
2337#endif /* OS_VXWORKS */
2338/*
2339** Named semaphore locking is only available on VxWorks.
2340**
2341*************** End of the named semaphore lock implementation ****************
2342******************************************************************************/
2343
2344
2345/******************************************************************************
2346*************************** Begin AFP Locking *********************************
2347**
2348** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2349** on Apple Macintosh computers - both OS9 and OSX.
2350**
2351** Third-party implementations of AFP are available. But this code here
2352** only works on OSX.
2353*/
2354
drhd2cb50b2009-01-09 21:41:17 +00002355#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002356/*
2357** The afpLockingContext structure contains all afp lock specific state
2358*/
drhbfe66312006-10-03 17:40:40 +00002359typedef struct afpLockingContext afpLockingContext;
2360struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002361 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002362 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002363};
2364
2365struct ByteRangeLockPB2
2366{
2367 unsigned long long offset; /* offset to first byte to lock */
2368 unsigned long long length; /* nbr of bytes to lock */
2369 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2370 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2371 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2372 int fd; /* file desc to assoc this lock with */
2373};
2374
drhfd131da2007-08-07 17:13:03 +00002375#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002376
drh6b9d6dd2008-12-03 19:34:47 +00002377/*
2378** This is a utility for setting or clearing a bit-range lock on an
2379** AFP filesystem.
2380**
2381** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2382*/
2383static int afpSetLock(
2384 const char *path, /* Name of the file to be locked or unlocked */
2385 unixFile *pFile, /* Open file descriptor on path */
2386 unsigned long long offset, /* First byte to be locked */
2387 unsigned long long length, /* Number of bytes to lock */
2388 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002389){
drh6b9d6dd2008-12-03 19:34:47 +00002390 struct ByteRangeLockPB2 pb;
2391 int err;
drhbfe66312006-10-03 17:40:40 +00002392
2393 pb.unLockFlag = setLockFlag ? 0 : 1;
2394 pb.startEndFlag = 0;
2395 pb.offset = offset;
2396 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002397 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002398
drh308c2a52010-05-14 11:30:18 +00002399 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002400 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002401 offset, length));
drhbfe66312006-10-03 17:40:40 +00002402 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2403 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002404 int rc;
2405 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002406 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2407 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002408#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2409 rc = SQLITE_BUSY;
2410#else
drh734c9862008-11-28 15:37:20 +00002411 rc = sqliteErrorFromPosixError(tErrno,
2412 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002413#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002414 if( IS_LOCK_ERROR(rc) ){
2415 pFile->lastErrno = tErrno;
2416 }
2417 return rc;
drhbfe66312006-10-03 17:40:40 +00002418 } else {
aswift5b1a2562008-08-22 00:22:35 +00002419 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002420 }
2421}
2422
drh6b9d6dd2008-12-03 19:34:47 +00002423/*
2424** This routine checks if there is a RESERVED lock held on the specified
2425** file by this or any other process. If such a lock is held, set *pResOut
2426** to a non-zero value otherwise *pResOut is set to zero. The return value
2427** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2428*/
danielk1977e339d652008-06-28 11:23:00 +00002429static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002430 int rc = SQLITE_OK;
2431 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002432 unixFile *pFile = (unixFile*)id;
2433
aswift5b1a2562008-08-22 00:22:35 +00002434 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2435
2436 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002437 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002438 if( context->reserved ){
2439 *pResOut = 1;
2440 return SQLITE_OK;
2441 }
drh8af6c222010-05-14 12:43:01 +00002442 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002443
2444 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002445 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002446 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002447 }
2448
2449 /* Otherwise see if some other process holds it.
2450 */
aswift5b1a2562008-08-22 00:22:35 +00002451 if( !reserved ){
2452 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002453 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002454 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002455 /* if we succeeded in taking the reserved lock, unlock it to restore
2456 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002457 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002458 } else {
2459 /* if we failed to get the lock then someone else must have it */
2460 reserved = 1;
2461 }
2462 if( IS_LOCK_ERROR(lrc) ){
2463 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002464 }
2465 }
drhbfe66312006-10-03 17:40:40 +00002466
drh7ed97b92010-01-20 13:07:21 +00002467 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002468 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002469
2470 *pResOut = reserved;
2471 return rc;
drhbfe66312006-10-03 17:40:40 +00002472}
2473
drh6b9d6dd2008-12-03 19:34:47 +00002474/*
drh308c2a52010-05-14 11:30:18 +00002475** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002476** of the following:
2477**
2478** (1) SHARED_LOCK
2479** (2) RESERVED_LOCK
2480** (3) PENDING_LOCK
2481** (4) EXCLUSIVE_LOCK
2482**
2483** Sometimes when requesting one lock state, additional lock states
2484** are inserted in between. The locking might fail on one of the later
2485** transitions leaving the lock state different from what it started but
2486** still short of its goal. The following chart shows the allowed
2487** transitions and the inserted intermediate states:
2488**
2489** UNLOCKED -> SHARED
2490** SHARED -> RESERVED
2491** SHARED -> (PENDING) -> EXCLUSIVE
2492** RESERVED -> (PENDING) -> EXCLUSIVE
2493** PENDING -> EXCLUSIVE
2494**
2495** This routine will only increase a lock. Use the sqlite3OsUnlock()
2496** routine to lower a locking level.
2497*/
drh308c2a52010-05-14 11:30:18 +00002498static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002499 int rc = SQLITE_OK;
2500 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002501 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002502 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002503
2504 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002505 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2506 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002507 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002508
drhbfe66312006-10-03 17:40:40 +00002509 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002510 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002511 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002512 */
drh308c2a52010-05-14 11:30:18 +00002513 if( pFile->eFileLock>=eFileLock ){
2514 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2515 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002516 return SQLITE_OK;
2517 }
2518
2519 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002520 ** (1) We never move from unlocked to anything higher than shared lock.
2521 ** (2) SQLite never explicitly requests a pendig lock.
2522 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002523 */
drh308c2a52010-05-14 11:30:18 +00002524 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2525 assert( eFileLock!=PENDING_LOCK );
2526 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002527
drh8af6c222010-05-14 12:43:01 +00002528 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002529 */
drh6c7d5c52008-11-21 20:32:33 +00002530 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002531 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002532
2533 /* If some thread using this PID has a lock via a different unixFile*
2534 ** handle that precludes the requested lock, return BUSY.
2535 */
drh8af6c222010-05-14 12:43:01 +00002536 if( (pFile->eFileLock!=pInode->eFileLock &&
2537 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002538 ){
2539 rc = SQLITE_BUSY;
2540 goto afp_end_lock;
2541 }
2542
2543 /* If a SHARED lock is requested, and some thread using this PID already
2544 ** has a SHARED or RESERVED lock, then increment reference counts and
2545 ** return SQLITE_OK.
2546 */
drh308c2a52010-05-14 11:30:18 +00002547 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002548 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002549 assert( eFileLock==SHARED_LOCK );
2550 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002551 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002552 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002553 pInode->nShared++;
2554 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002555 goto afp_end_lock;
2556 }
drhbfe66312006-10-03 17:40:40 +00002557
2558 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002559 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2560 ** be released.
2561 */
drh308c2a52010-05-14 11:30:18 +00002562 if( eFileLock==SHARED_LOCK
2563 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002564 ){
2565 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002566 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002567 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002568 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002569 goto afp_end_lock;
2570 }
2571 }
2572
2573 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002574 ** operating system calls for the specified lock.
2575 */
drh308c2a52010-05-14 11:30:18 +00002576 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002577 int lrc1, lrc2, lrc1Errno;
2578 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002579
drh8af6c222010-05-14 12:43:01 +00002580 assert( pInode->nShared==0 );
2581 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002582
2583 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002584 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002585 /* note that the quality of the randomness doesn't matter that much */
2586 lk = random();
drh8af6c222010-05-14 12:43:01 +00002587 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002588 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002589 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002590 if( IS_LOCK_ERROR(lrc1) ){
2591 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002592 }
aswift5b1a2562008-08-22 00:22:35 +00002593 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002594 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002595
aswift5b1a2562008-08-22 00:22:35 +00002596 if( IS_LOCK_ERROR(lrc1) ) {
2597 pFile->lastErrno = lrc1Errno;
2598 rc = lrc1;
2599 goto afp_end_lock;
2600 } else if( IS_LOCK_ERROR(lrc2) ){
2601 rc = lrc2;
2602 goto afp_end_lock;
2603 } else if( lrc1 != SQLITE_OK ) {
2604 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002605 } else {
drh308c2a52010-05-14 11:30:18 +00002606 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002607 pInode->nLock++;
2608 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002609 }
drh8af6c222010-05-14 12:43:01 +00002610 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002611 /* We are trying for an exclusive lock but another thread in this
2612 ** same process is still holding a shared lock. */
2613 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002614 }else{
2615 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2616 ** assumed that there is a SHARED or greater lock on the file
2617 ** already.
2618 */
2619 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002620 assert( 0!=pFile->eFileLock );
2621 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002622 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002623 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002624 if( !failed ){
2625 context->reserved = 1;
2626 }
drhbfe66312006-10-03 17:40:40 +00002627 }
drh308c2a52010-05-14 11:30:18 +00002628 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002629 /* Acquire an EXCLUSIVE lock */
2630
2631 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002632 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002633 */
drh6b9d6dd2008-12-03 19:34:47 +00002634 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002635 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002636 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002637 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002638 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002639 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002640 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002641 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002642 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2643 ** a critical I/O error
2644 */
2645 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2646 SQLITE_IOERR_LOCK;
2647 goto afp_end_lock;
2648 }
2649 }else{
aswift5b1a2562008-08-22 00:22:35 +00002650 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002651 }
2652 }
aswift5b1a2562008-08-22 00:22:35 +00002653 if( failed ){
2654 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002655 }
2656 }
2657
2658 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002659 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002660 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002661 }else if( eFileLock==EXCLUSIVE_LOCK ){
2662 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002663 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002664 }
2665
2666afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002667 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002668 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2669 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002670 return rc;
2671}
2672
2673/*
drh308c2a52010-05-14 11:30:18 +00002674** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002675** must be either NO_LOCK or SHARED_LOCK.
2676**
2677** If the locking level of the file descriptor is already at or below
2678** the requested locking level, this routine is a no-op.
2679*/
drh308c2a52010-05-14 11:30:18 +00002680static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002681 int rc = SQLITE_OK;
2682 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002683 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002684 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2685 int skipShared = 0;
2686#ifdef SQLITE_TEST
2687 int h = pFile->h;
2688#endif
drhbfe66312006-10-03 17:40:40 +00002689
2690 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002691 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002692 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002693 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002694
drh308c2a52010-05-14 11:30:18 +00002695 assert( eFileLock<=SHARED_LOCK );
2696 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002697 return SQLITE_OK;
2698 }
drh6c7d5c52008-11-21 20:32:33 +00002699 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002700 pInode = pFile->pInode;
2701 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002702 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002703 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002704 SimulateIOErrorBenign(1);
2705 SimulateIOError( h=(-1) )
2706 SimulateIOErrorBenign(0);
2707
2708#ifndef NDEBUG
2709 /* When reducing a lock such that other processes can start
2710 ** reading the database file again, make sure that the
2711 ** transaction counter was updated if any part of the database
2712 ** file changed. If the transaction counter is not updated,
2713 ** other connections to the same file might not realize that
2714 ** the file has changed and hence might not know to flush their
2715 ** cache. The use of a stale cache can lead to database corruption.
2716 */
2717 assert( pFile->inNormalWrite==0
2718 || pFile->dbUpdate==0
2719 || pFile->transCntrChng==1 );
2720 pFile->inNormalWrite = 0;
2721#endif
aswiftaebf4132008-11-21 00:10:35 +00002722
drh308c2a52010-05-14 11:30:18 +00002723 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002724 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002725 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002726 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002727 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002728 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2729 } else {
2730 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002731 }
2732 }
drh308c2a52010-05-14 11:30:18 +00002733 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002734 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002735 }
drh308c2a52010-05-14 11:30:18 +00002736 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002737 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2738 if( !rc ){
2739 context->reserved = 0;
2740 }
aswiftaebf4132008-11-21 00:10:35 +00002741 }
drh8af6c222010-05-14 12:43:01 +00002742 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2743 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002744 }
aswiftaebf4132008-11-21 00:10:35 +00002745 }
drh308c2a52010-05-14 11:30:18 +00002746 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002747
drh7ed97b92010-01-20 13:07:21 +00002748 /* Decrement the shared lock counter. Release the lock using an
2749 ** OS call only when all threads in this same process have released
2750 ** the lock.
2751 */
drh8af6c222010-05-14 12:43:01 +00002752 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2753 pInode->nShared--;
2754 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002755 SimulateIOErrorBenign(1);
2756 SimulateIOError( h=(-1) )
2757 SimulateIOErrorBenign(0);
2758 if( !skipShared ){
2759 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2760 }
2761 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002762 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002763 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002764 }
2765 }
2766 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002767 pInode->nLock--;
2768 assert( pInode->nLock>=0 );
2769 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002770 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002771 }
2772 }
drhbfe66312006-10-03 17:40:40 +00002773 }
drh7ed97b92010-01-20 13:07:21 +00002774
drh6c7d5c52008-11-21 20:32:33 +00002775 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002776 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002777 return rc;
2778}
2779
2780/*
drh339eb0b2008-03-07 15:34:11 +00002781** Close a file & cleanup AFP specific locking context
2782*/
danielk1977e339d652008-06-28 11:23:00 +00002783static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002784 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002785 if( id ){
2786 unixFile *pFile = (unixFile*)id;
2787 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002788 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002789 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002790 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002791 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002792 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002793 ** the last lock is cleared.
2794 */
dan08da86a2009-08-21 17:18:03 +00002795 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002796 }
danb0ac3e32010-06-16 10:55:42 +00002797 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002798 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002799 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002800 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002801 }
drh7ed97b92010-01-20 13:07:21 +00002802 return rc;
drhbfe66312006-10-03 17:40:40 +00002803}
2804
drhd2cb50b2009-01-09 21:41:17 +00002805#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002806/*
2807** The code above is the AFP lock implementation. The code is specific
2808** to MacOSX and does not work on other unix platforms. No alternative
2809** is available. If you don't compile for a mac, then the "unix-afp"
2810** VFS is not available.
2811**
2812********************* End of the AFP lock implementation **********************
2813******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002814
drh7ed97b92010-01-20 13:07:21 +00002815/******************************************************************************
2816*************************** Begin NFS Locking ********************************/
2817
2818#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2819/*
drh308c2a52010-05-14 11:30:18 +00002820 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002821 ** must be either NO_LOCK or SHARED_LOCK.
2822 **
2823 ** If the locking level of the file descriptor is already at or below
2824 ** the requested locking level, this routine is a no-op.
2825 */
drh308c2a52010-05-14 11:30:18 +00002826static int nfsUnlock(sqlite3_file *id, int eFileLock){
2827 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002828}
2829
2830#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2831/*
2832** The code above is the NFS lock implementation. The code is specific
2833** to MacOSX and does not work on other unix platforms. No alternative
2834** is available.
2835**
2836********************* End of the NFS lock implementation **********************
2837******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002838
2839/******************************************************************************
2840**************** Non-locking sqlite3_file methods *****************************
2841**
2842** The next division contains implementations for all methods of the
2843** sqlite3_file object other than the locking methods. The locking
2844** methods were defined in divisions above (one locking method per
2845** division). Those methods that are common to all locking modes
2846** are gather together into this division.
2847*/
drhbfe66312006-10-03 17:40:40 +00002848
2849/*
drh734c9862008-11-28 15:37:20 +00002850** Seek to the offset passed as the second argument, then read cnt
2851** bytes into pBuf. Return the number of bytes actually read.
2852**
2853** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2854** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2855** one system to another. Since SQLite does not define USE_PREAD
2856** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2857** See tickets #2741 and #2681.
2858**
2859** To avoid stomping the errno value on a failed read the lastErrno value
2860** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002861*/
drh734c9862008-11-28 15:37:20 +00002862static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2863 int got;
drh7ed97b92010-01-20 13:07:21 +00002864#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002865 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002866#endif
drh734c9862008-11-28 15:37:20 +00002867 TIMER_START;
2868#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002869 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002870 SimulateIOError( got = -1 );
2871#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002872 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002873 SimulateIOError( got = -1 );
2874#else
2875 newOffset = lseek(id->h, offset, SEEK_SET);
2876 SimulateIOError( newOffset-- );
2877 if( newOffset!=offset ){
2878 if( newOffset == -1 ){
2879 ((unixFile*)id)->lastErrno = errno;
2880 }else{
2881 ((unixFile*)id)->lastErrno = 0;
2882 }
2883 return -1;
2884 }
drhe562be52011-03-02 18:01:10 +00002885 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002886#endif
2887 TIMER_END;
2888 if( got<0 ){
2889 ((unixFile*)id)->lastErrno = errno;
2890 }
drh308c2a52010-05-14 11:30:18 +00002891 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002892 return got;
drhbfe66312006-10-03 17:40:40 +00002893}
2894
2895/*
drh734c9862008-11-28 15:37:20 +00002896** Read data from a file into a buffer. Return SQLITE_OK if all
2897** bytes were read successfully and SQLITE_IOERR if anything goes
2898** wrong.
drh339eb0b2008-03-07 15:34:11 +00002899*/
drh734c9862008-11-28 15:37:20 +00002900static int unixRead(
2901 sqlite3_file *id,
2902 void *pBuf,
2903 int amt,
2904 sqlite3_int64 offset
2905){
dan08da86a2009-08-21 17:18:03 +00002906 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002907 int got;
2908 assert( id );
drh08c6d442009-02-09 17:34:07 +00002909
dan08da86a2009-08-21 17:18:03 +00002910 /* If this is a database file (not a journal, master-journal or temp
2911 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002912#if 0
dane946c392009-08-22 11:39:46 +00002913 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002914 || offset>=PENDING_BYTE+512
2915 || offset+amt<=PENDING_BYTE
2916 );
dan7c246102010-04-12 19:00:29 +00002917#endif
drh08c6d442009-02-09 17:34:07 +00002918
dan08da86a2009-08-21 17:18:03 +00002919 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002920 if( got==amt ){
2921 return SQLITE_OK;
2922 }else if( got<0 ){
2923 /* lastErrno set by seekAndRead */
2924 return SQLITE_IOERR_READ;
2925 }else{
dan08da86a2009-08-21 17:18:03 +00002926 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002927 /* Unread parts of the buffer must be zero-filled */
2928 memset(&((char*)pBuf)[got], 0, amt-got);
2929 return SQLITE_IOERR_SHORT_READ;
2930 }
2931}
2932
2933/*
2934** Seek to the offset in id->offset then read cnt bytes into pBuf.
2935** Return the number of bytes actually read. Update the offset.
2936**
2937** To avoid stomping the errno value on a failed write the lastErrno value
2938** is set before returning.
2939*/
2940static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2941 int got;
drh7ed97b92010-01-20 13:07:21 +00002942#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002943 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002944#endif
drh734c9862008-11-28 15:37:20 +00002945 TIMER_START;
2946#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002947 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002948#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002949 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002950#else
2951 newOffset = lseek(id->h, offset, SEEK_SET);
2952 if( newOffset!=offset ){
2953 if( newOffset == -1 ){
2954 ((unixFile*)id)->lastErrno = errno;
2955 }else{
2956 ((unixFile*)id)->lastErrno = 0;
2957 }
2958 return -1;
2959 }
drhe562be52011-03-02 18:01:10 +00002960 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002961#endif
2962 TIMER_END;
2963 if( got<0 ){
2964 ((unixFile*)id)->lastErrno = errno;
2965 }
2966
drh308c2a52010-05-14 11:30:18 +00002967 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002968 return got;
2969}
2970
2971
2972/*
2973** Write data from a buffer into a file. Return SQLITE_OK on success
2974** or some other error code on failure.
2975*/
2976static int unixWrite(
2977 sqlite3_file *id,
2978 const void *pBuf,
2979 int amt,
2980 sqlite3_int64 offset
2981){
dan08da86a2009-08-21 17:18:03 +00002982 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002983 int wrote = 0;
2984 assert( id );
2985 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002986
dan08da86a2009-08-21 17:18:03 +00002987 /* If this is a database file (not a journal, master-journal or temp
2988 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002989#if 0
dane946c392009-08-22 11:39:46 +00002990 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002991 || offset>=PENDING_BYTE+512
2992 || offset+amt<=PENDING_BYTE
2993 );
dan7c246102010-04-12 19:00:29 +00002994#endif
drh08c6d442009-02-09 17:34:07 +00002995
drh8f941bc2009-01-14 23:03:40 +00002996#ifndef NDEBUG
2997 /* If we are doing a normal write to a database file (as opposed to
2998 ** doing a hot-journal rollback or a write to some file other than a
2999 ** normal database file) then record the fact that the database
3000 ** has changed. If the transaction counter is modified, record that
3001 ** fact too.
3002 */
dan08da86a2009-08-21 17:18:03 +00003003 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003004 pFile->dbUpdate = 1; /* The database has been modified */
3005 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003006 int rc;
drh8f941bc2009-01-14 23:03:40 +00003007 char oldCntr[4];
3008 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003009 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003010 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003011 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003012 pFile->transCntrChng = 1; /* The transaction counter has changed */
3013 }
3014 }
3015 }
3016#endif
3017
dan08da86a2009-08-21 17:18:03 +00003018 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003019 amt -= wrote;
3020 offset += wrote;
3021 pBuf = &((char*)pBuf)[wrote];
3022 }
3023 SimulateIOError(( wrote=(-1), amt=1 ));
3024 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003025
drh734c9862008-11-28 15:37:20 +00003026 if( amt>0 ){
3027 if( wrote<0 ){
3028 /* lastErrno set by seekAndWrite */
3029 return SQLITE_IOERR_WRITE;
3030 }else{
dan08da86a2009-08-21 17:18:03 +00003031 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003032 return SQLITE_FULL;
3033 }
3034 }
dan6e09d692010-07-27 18:34:15 +00003035
drh734c9862008-11-28 15:37:20 +00003036 return SQLITE_OK;
3037}
3038
3039#ifdef SQLITE_TEST
3040/*
3041** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003042** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003043*/
3044int sqlite3_sync_count = 0;
3045int sqlite3_fullsync_count = 0;
3046#endif
3047
3048/*
drh89240432009-03-25 01:06:01 +00003049** We do not trust systems to provide a working fdatasync(). Some do.
3050** Others do no. To be safe, we will stick with the (slower) fsync().
3051** If you know that your system does support fdatasync() correctly,
3052** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003053*/
drh89240432009-03-25 01:06:01 +00003054#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003055# define fdatasync fsync
3056#endif
3057
3058/*
3059** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3060** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3061** only available on Mac OS X. But that could change.
3062*/
3063#ifdef F_FULLFSYNC
3064# define HAVE_FULLFSYNC 1
3065#else
3066# define HAVE_FULLFSYNC 0
3067#endif
3068
3069
3070/*
3071** The fsync() system call does not work as advertised on many
3072** unix systems. The following procedure is an attempt to make
3073** it work better.
3074**
3075** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3076** for testing when we want to run through the test suite quickly.
3077** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3078** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3079** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003080**
3081** SQLite sets the dataOnly flag if the size of the file is unchanged.
3082** The idea behind dataOnly is that it should only write the file content
3083** to disk, not the inode. We only set dataOnly if the file size is
3084** unchanged since the file size is part of the inode. However,
3085** Ted Ts'o tells us that fdatasync() will also write the inode if the
3086** file size has changed. The only real difference between fdatasync()
3087** and fsync(), Ted tells us, is that fdatasync() will not flush the
3088** inode if the mtime or owner or other inode attributes have changed.
3089** We only care about the file size, not the other file attributes, so
3090** as far as SQLite is concerned, an fdatasync() is always adequate.
3091** So, we always use fdatasync() if it is available, regardless of
3092** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003093*/
3094static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003095 int rc;
drh734c9862008-11-28 15:37:20 +00003096
3097 /* The following "ifdef/elif/else/" block has the same structure as
3098 ** the one below. It is replicated here solely to avoid cluttering
3099 ** up the real code with the UNUSED_PARAMETER() macros.
3100 */
3101#ifdef SQLITE_NO_SYNC
3102 UNUSED_PARAMETER(fd);
3103 UNUSED_PARAMETER(fullSync);
3104 UNUSED_PARAMETER(dataOnly);
3105#elif HAVE_FULLFSYNC
3106 UNUSED_PARAMETER(dataOnly);
3107#else
3108 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003109 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003110#endif
3111
3112 /* Record the number of times that we do a normal fsync() and
3113 ** FULLSYNC. This is used during testing to verify that this procedure
3114 ** gets called with the correct arguments.
3115 */
3116#ifdef SQLITE_TEST
3117 if( fullSync ) sqlite3_fullsync_count++;
3118 sqlite3_sync_count++;
3119#endif
3120
3121 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3122 ** no-op
3123 */
3124#ifdef SQLITE_NO_SYNC
3125 rc = SQLITE_OK;
3126#elif HAVE_FULLFSYNC
3127 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003128 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003129 }else{
3130 rc = 1;
3131 }
3132 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003133 ** It shouldn't be possible for fullfsync to fail on the local
3134 ** file system (on OSX), so failure indicates that FULLFSYNC
3135 ** isn't supported for this file system. So, attempt an fsync
3136 ** and (for now) ignore the overhead of a superfluous fcntl call.
3137 ** It'd be better to detect fullfsync support once and avoid
3138 ** the fcntl call every time sync is called.
3139 */
drh734c9862008-11-28 15:37:20 +00003140 if( rc ) rc = fsync(fd);
3141
drh7ed97b92010-01-20 13:07:21 +00003142#elif defined(__APPLE__)
3143 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3144 ** so currently we default to the macro that redefines fdatasync to fsync
3145 */
3146 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003147#else
drh0b647ff2009-03-21 14:41:04 +00003148 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003149#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003150 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003151 rc = fsync(fd);
3152 }
drh0b647ff2009-03-21 14:41:04 +00003153#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003154#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3155
3156 if( OS_VXWORKS && rc!= -1 ){
3157 rc = 0;
3158 }
chw97185482008-11-17 08:05:31 +00003159 return rc;
drhbfe66312006-10-03 17:40:40 +00003160}
3161
drh734c9862008-11-28 15:37:20 +00003162/*
3163** Make sure all writes to a particular file are committed to disk.
3164**
3165** If dataOnly==0 then both the file itself and its metadata (file
3166** size, access time, etc) are synced. If dataOnly!=0 then only the
3167** file data is synced.
3168**
3169** Under Unix, also make sure that the directory entry for the file
3170** has been created by fsync-ing the directory that contains the file.
3171** If we do not do this and we encounter a power failure, the directory
3172** entry for the journal might not exist after we reboot. The next
3173** SQLite to access the file will not know that the journal exists (because
3174** the directory entry for the journal was never created) and the transaction
3175** will not roll back - possibly leading to database corruption.
3176*/
3177static int unixSync(sqlite3_file *id, int flags){
3178 int rc;
3179 unixFile *pFile = (unixFile*)id;
3180
3181 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3182 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3183
3184 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3185 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3186 || (flags&0x0F)==SQLITE_SYNC_FULL
3187 );
3188
3189 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3190 ** line is to test that doing so does not cause any problems.
3191 */
3192 SimulateDiskfullError( return SQLITE_FULL );
3193
3194 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003195 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003196 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3197 SimulateIOError( rc=1 );
3198 if( rc ){
3199 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003200 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003201 }
3202 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003203 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3204 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003205#ifndef SQLITE_DISABLE_DIRSYNC
3206 /* The directory sync is only attempted if full_fsync is
3207 ** turned off or unavailable. If a full_fsync occurred above,
3208 ** then the directory sync is superfluous.
3209 */
3210 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3211 /*
3212 ** We have received multiple reports of fsync() returning
3213 ** errors when applied to directories on certain file systems.
3214 ** A failed directory sync is not a big deal. So it seems
3215 ** better to ignore the error. Ticket #1657
3216 */
3217 /* pFile->lastErrno = errno; */
3218 /* return SQLITE_IOERR; */
3219 }
3220#endif
drh0e9365c2011-03-02 02:08:13 +00003221 /* Only need to sync once, so close the directory when we are done */
3222 robust_close(pFile, pFile->dirfd, __LINE__);
3223 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003224 }
3225 return rc;
3226}
3227
3228/*
3229** Truncate an open file to a specified size
3230*/
3231static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003232 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003233 int rc;
dan6e09d692010-07-27 18:34:15 +00003234 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003235 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003236
3237 /* If the user has configured a chunk-size for this file, truncate the
3238 ** file so that it consists of an integer number of chunks (i.e. the
3239 ** actual file size after the operation may be larger than the requested
3240 ** size).
3241 */
3242 if( pFile->szChunk ){
3243 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3244 }
3245
drhff812312011-02-23 13:33:46 +00003246 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003247 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003248 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003249 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003250 }else{
drh3313b142009-11-06 04:13:18 +00003251#ifndef NDEBUG
3252 /* If we are doing a normal write to a database file (as opposed to
3253 ** doing a hot-journal rollback or a write to some file other than a
3254 ** normal database file) and we truncate the file to zero length,
3255 ** that effectively updates the change counter. This might happen
3256 ** when restoring a database using the backup API from a zero-length
3257 ** source.
3258 */
dan6e09d692010-07-27 18:34:15 +00003259 if( pFile->inNormalWrite && nByte==0 ){
3260 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003261 }
3262#endif
3263
drh734c9862008-11-28 15:37:20 +00003264 return SQLITE_OK;
3265 }
3266}
3267
3268/*
3269** Determine the current size of a file in bytes
3270*/
3271static int unixFileSize(sqlite3_file *id, i64 *pSize){
3272 int rc;
3273 struct stat buf;
3274 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003275 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003276 SimulateIOError( rc=1 );
3277 if( rc!=0 ){
3278 ((unixFile*)id)->lastErrno = errno;
3279 return SQLITE_IOERR_FSTAT;
3280 }
3281 *pSize = buf.st_size;
3282
drh8af6c222010-05-14 12:43:01 +00003283 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003284 ** writes a single byte into that file in order to work around a bug
3285 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3286 ** layers, we need to report this file size as zero even though it is
3287 ** really 1. Ticket #3260.
3288 */
3289 if( *pSize==1 ) *pSize = 0;
3290
3291
3292 return SQLITE_OK;
3293}
3294
drhd2cb50b2009-01-09 21:41:17 +00003295#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003296/*
3297** Handler for proxy-locking file-control verbs. Defined below in the
3298** proxying locking division.
3299*/
3300static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003301#endif
drh715ff302008-12-03 22:32:44 +00003302
dan502019c2010-07-28 14:26:17 +00003303/*
3304** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3305** file-control operation.
3306**
3307** If the user has configured a chunk-size for this file, it could be
3308** that the file needs to be extended at this point. Otherwise, the
3309** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3310*/
3311static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3312 if( pFile->szChunk ){
3313 i64 nSize; /* Required file size */
3314 struct stat buf; /* Used to hold return values of fstat() */
3315
drh99ab3b12011-03-02 15:09:07 +00003316 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003317
3318 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3319 if( nSize>(i64)buf.st_size ){
3320#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003321 int rc;
3322 do{
drhe562be52011-03-02 18:01:10 +00003323 rc = osFallocate(pFile->.h, buf.st_size, nSize-buf.st_size;
drhff812312011-02-23 13:33:46 +00003324 }while( rc<0 && errno=EINTR );
3325 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003326#else
3327 /* If the OS does not have posix_fallocate(), fake it. First use
3328 ** ftruncate() to set the file size, then write a single byte to
3329 ** the last byte in each block within the extended region. This
3330 ** is the same technique used by glibc to implement posix_fallocate()
3331 ** on systems that do not have a real fallocate() system call.
3332 */
3333 int nBlk = buf.st_blksize; /* File-system block size */
3334 i64 iWrite; /* Next offset to write to */
3335 int nWrite; /* Return value from seekAndWrite() */
3336
drhff812312011-02-23 13:33:46 +00003337 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003338 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003339 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003340 }
3341 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3342 do {
3343 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3344 iWrite += nBlk;
3345 } while( nWrite==1 && iWrite<nSize );
3346 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3347#endif
3348 }
3349 }
3350
3351 return SQLITE_OK;
3352}
danielk1977ad94b582007-08-20 06:44:22 +00003353
danielk1977e3026632004-06-22 11:29:02 +00003354/*
drh9e33c2c2007-08-31 18:34:59 +00003355** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003356*/
drhcc6bb3e2007-08-31 16:11:35 +00003357static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003358 switch( op ){
3359 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003360 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003361 return SQLITE_OK;
3362 }
drh7708e972008-11-29 00:56:52 +00003363 case SQLITE_LAST_ERRNO: {
3364 *(int*)pArg = ((unixFile*)id)->lastErrno;
3365 return SQLITE_OK;
3366 }
dan6e09d692010-07-27 18:34:15 +00003367 case SQLITE_FCNTL_CHUNK_SIZE: {
3368 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003369 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003370 }
drh9ff27ec2010-05-19 19:26:05 +00003371 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003372 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003373 }
drh8f941bc2009-01-14 23:03:40 +00003374#ifndef NDEBUG
3375 /* The pager calls this method to signal that it has done
3376 ** a rollback and that the database is therefore unchanged and
3377 ** it hence it is OK for the transaction change counter to be
3378 ** unchanged.
3379 */
3380 case SQLITE_FCNTL_DB_UNCHANGED: {
3381 ((unixFile*)id)->dbUpdate = 0;
3382 return SQLITE_OK;
3383 }
3384#endif
drhd2cb50b2009-01-09 21:41:17 +00003385#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003386 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003387 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003388 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003389 }
drhd2cb50b2009-01-09 21:41:17 +00003390#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003391 case SQLITE_FCNTL_SYNC_OMITTED: {
3392 return SQLITE_OK; /* A no-op */
3393 }
drh9e33c2c2007-08-31 18:34:59 +00003394 }
drh0b52b7d2011-01-26 19:46:22 +00003395 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003396}
3397
3398/*
danielk1977a3d4c882007-03-23 10:08:38 +00003399** Return the sector size in bytes of the underlying block device for
3400** the specified file. This is almost always 512 bytes, but may be
3401** larger for some devices.
3402**
3403** SQLite code assumes this function cannot fail. It also assumes that
3404** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003405** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003406** same for both.
3407*/
danielk1977397d65f2008-11-19 11:35:39 +00003408static int unixSectorSize(sqlite3_file *NotUsed){
3409 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003410 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003411}
3412
danielk197790949c22007-08-17 16:50:38 +00003413/*
danielk1977397d65f2008-11-19 11:35:39 +00003414** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003415*/
danielk1977397d65f2008-11-19 11:35:39 +00003416static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3417 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003418 return 0;
3419}
3420
drhd9e5c4f2010-05-12 18:01:39 +00003421#ifndef SQLITE_OMIT_WAL
3422
3423
3424/*
drhd91c68f2010-05-14 14:52:25 +00003425** Object used to represent an shared memory buffer.
3426**
3427** When multiple threads all reference the same wal-index, each thread
3428** has its own unixShm object, but they all point to a single instance
3429** of this unixShmNode object. In other words, each wal-index is opened
3430** only once per process.
3431**
3432** Each unixShmNode object is connected to a single unixInodeInfo object.
3433** We could coalesce this object into unixInodeInfo, but that would mean
3434** every open file that does not use shared memory (in other words, most
3435** open files) would have to carry around this extra information. So
3436** the unixInodeInfo object contains a pointer to this unixShmNode object
3437** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003438**
3439** unixMutexHeld() must be true when creating or destroying
3440** this object or while reading or writing the following fields:
3441**
3442** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003443**
3444** The following fields are read-only after the object is created:
3445**
3446** fid
3447** zFilename
3448**
drhd91c68f2010-05-14 14:52:25 +00003449** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003450** unixMutexHeld() is true when reading or writing any other field
3451** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003452*/
drhd91c68f2010-05-14 14:52:25 +00003453struct unixShmNode {
3454 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003455 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003456 char *zFilename; /* Name of the mmapped file */
3457 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003458 int szRegion; /* Size of shared-memory regions */
3459 int nRegion; /* Size of array apRegion */
3460 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003461 int nRef; /* Number of unixShm objects pointing to this */
3462 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003463#ifdef SQLITE_DEBUG
3464 u8 exclMask; /* Mask of exclusive locks held */
3465 u8 sharedMask; /* Mask of shared locks held */
3466 u8 nextShmId; /* Next available unixShm.id value */
3467#endif
3468};
3469
3470/*
drhd9e5c4f2010-05-12 18:01:39 +00003471** Structure used internally by this VFS to record the state of an
3472** open shared memory connection.
3473**
drhd91c68f2010-05-14 14:52:25 +00003474** The following fields are initialized when this object is created and
3475** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003476**
drhd91c68f2010-05-14 14:52:25 +00003477** unixShm.pFile
3478** unixShm.id
3479**
3480** All other fields are read/write. The unixShm.pFile->mutex must be held
3481** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003482*/
3483struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003484 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3485 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003486 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003487 u16 sharedMask; /* Mask of shared locks held */
3488 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003489#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003490 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003491#endif
3492};
3493
3494/*
drhd9e5c4f2010-05-12 18:01:39 +00003495** Constants used for locking
3496*/
drhbd9676c2010-06-23 17:58:38 +00003497#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003498#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003499
drhd9e5c4f2010-05-12 18:01:39 +00003500/*
drh73b64e42010-05-30 19:55:15 +00003501** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003502**
3503** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3504** otherwise.
3505*/
3506static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003507 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3508 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003509 int ofst, /* First byte of the locking range */
3510 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003511){
3512 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003513 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003514
drhd91c68f2010-05-14 14:52:25 +00003515 /* Access to the unixShmNode object is serialized by the caller */
3516 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003517
drh73b64e42010-05-30 19:55:15 +00003518 /* Shared locks never span more than one byte */
3519 assert( n==1 || lockType!=F_RDLCK );
3520
3521 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003522 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003523
drhd9e5c4f2010-05-12 18:01:39 +00003524 /* Initialize the locking parameters */
3525 memset(&f, 0, sizeof(f));
3526 f.l_type = lockType;
3527 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003528 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003529 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003530
drh99ab3b12011-03-02 15:09:07 +00003531 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003532 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3533
3534 /* Update the global lock state and do debug tracing */
3535#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003536 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003537 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003538 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003539 if( rc==SQLITE_OK ){
3540 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003541 OSTRACE(("unlock %d ok", ofst));
3542 pShmNode->exclMask &= ~mask;
3543 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003544 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003545 OSTRACE(("read-lock %d ok", ofst));
3546 pShmNode->exclMask &= ~mask;
3547 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003548 }else{
3549 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003550 OSTRACE(("write-lock %d ok", ofst));
3551 pShmNode->exclMask |= mask;
3552 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003553 }
3554 }else{
3555 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003556 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003557 }else if( lockType==F_RDLCK ){
3558 OSTRACE(("read-lock failed"));
3559 }else{
3560 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003561 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003562 }
3563 }
drh20e1f082010-05-31 16:10:12 +00003564 OSTRACE((" - afterwards %03x,%03x\n",
3565 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003566 }
drhd9e5c4f2010-05-12 18:01:39 +00003567#endif
3568
3569 return rc;
3570}
3571
drhd9e5c4f2010-05-12 18:01:39 +00003572
3573/*
drhd91c68f2010-05-14 14:52:25 +00003574** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003575**
3576** This is not a VFS shared-memory method; it is a utility function called
3577** by VFS shared-memory methods.
3578*/
drhd91c68f2010-05-14 14:52:25 +00003579static void unixShmPurge(unixFile *pFd){
3580 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003581 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003582 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003583 int i;
drhd91c68f2010-05-14 14:52:25 +00003584 assert( p->pInode==pFd->pInode );
3585 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003586 for(i=0; i<p->nRegion; i++){
3587 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003588 }
dan18801912010-06-14 14:07:50 +00003589 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003590 if( p->h>=0 ){
3591 robust_close(pFd, p->h, __LINE__);
3592 p->h = -1;
3593 }
drhd91c68f2010-05-14 14:52:25 +00003594 p->pInode->pShmNode = 0;
3595 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003596 }
3597}
3598
3599/*
danda9fe0c2010-07-13 18:44:03 +00003600** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003601** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003602**
drh7234c6d2010-06-19 15:10:09 +00003603** The file used to implement shared-memory is in the same directory
3604** as the open database file and has the same name as the open database
3605** file with the "-shm" suffix added. For example, if the database file
3606** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003607** for shared memory will be called "/home/user1/config.db-shm".
3608**
3609** Another approach to is to use files in /dev/shm or /dev/tmp or an
3610** some other tmpfs mount. But if a file in a different directory
3611** from the database file is used, then differing access permissions
3612** or a chroot() might cause two different processes on the same
3613** database to end up using different files for shared memory -
3614** meaning that their memory would not really be shared - resulting
3615** in database corruption. Nevertheless, this tmpfs file usage
3616** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3617** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3618** option results in an incompatible build of SQLite; builds of SQLite
3619** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3620** same database file at the same time, database corruption will likely
3621** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3622** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003623**
3624** When opening a new shared-memory file, if no other instances of that
3625** file are currently open, in this process or in other processes, then
3626** the file must be truncated to zero length or have its header cleared.
3627*/
danda9fe0c2010-07-13 18:44:03 +00003628static int unixOpenSharedMemory(unixFile *pDbFd){
3629 struct unixShm *p = 0; /* The connection to be opened */
3630 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3631 int rc; /* Result code */
3632 unixInodeInfo *pInode; /* The inode of fd */
3633 char *zShmFilename; /* Name of the file used for SHM */
3634 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003635
danda9fe0c2010-07-13 18:44:03 +00003636 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003637 p = sqlite3_malloc( sizeof(*p) );
3638 if( p==0 ) return SQLITE_NOMEM;
3639 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003640 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003641
danda9fe0c2010-07-13 18:44:03 +00003642 /* Check to see if a unixShmNode object already exists. Reuse an existing
3643 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003644 */
3645 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003646 pInode = pDbFd->pInode;
3647 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003648 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003649 struct stat sStat; /* fstat() info for database file */
3650
3651 /* Call fstat() to figure out the permissions on the database file. If
3652 ** a new *-shm file is created, an attempt will be made to create it
3653 ** with the same permissions. The actual permissions the file is created
3654 ** with are subject to the current umask setting.
3655 */
drh99ab3b12011-03-02 15:09:07 +00003656 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00003657 rc = SQLITE_IOERR_FSTAT;
3658 goto shm_open_err;
3659 }
3660
drha4ced192010-07-15 18:32:40 +00003661#ifdef SQLITE_SHM_DIRECTORY
3662 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3663#else
drh7234c6d2010-06-19 15:10:09 +00003664 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003665#endif
drh7234c6d2010-06-19 15:10:09 +00003666 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003667 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003668 rc = SQLITE_NOMEM;
3669 goto shm_open_err;
3670 }
drhd91c68f2010-05-14 14:52:25 +00003671 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003672 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003673#ifdef SQLITE_SHM_DIRECTORY
3674 sqlite3_snprintf(nShmFilename, zShmFilename,
3675 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3676 (u32)sStat.st_ino, (u32)sStat.st_dev);
3677#else
drh7234c6d2010-06-19 15:10:09 +00003678 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003679#endif
drhd91c68f2010-05-14 14:52:25 +00003680 pShmNode->h = -1;
3681 pDbFd->pInode->pShmNode = pShmNode;
3682 pShmNode->pInode = pDbFd->pInode;
3683 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3684 if( pShmNode->mutex==0 ){
3685 rc = SQLITE_NOMEM;
3686 goto shm_open_err;
3687 }
drhd9e5c4f2010-05-12 18:01:39 +00003688
drh99ab3b12011-03-02 15:09:07 +00003689 pShmNode->h = osOpen(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003690 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003691 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003692 goto shm_open_err;
3693 }
3694
drhd9e5c4f2010-05-12 18:01:39 +00003695 /* Check to see if another process is holding the dead-man switch.
3696 ** If not, truncate the file to zero length.
3697 */
drhd91c68f2010-05-14 14:52:25 +00003698 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003699 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhff812312011-02-23 13:33:46 +00003700 if( robust_ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003701 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003702 }
3703 }
3704 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003705 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003706 }
3707 if( rc ) goto shm_open_err;
3708 }
3709
drhd91c68f2010-05-14 14:52:25 +00003710 /* Make the new connection a child of the unixShmNode */
3711 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003712#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003713 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003714#endif
drhd91c68f2010-05-14 14:52:25 +00003715 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003716 pDbFd->pShm = p;
3717 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003718
3719 /* The reference count on pShmNode has already been incremented under
3720 ** the cover of the unixEnterMutex() mutex and the pointer from the
3721 ** new (struct unixShm) object to the pShmNode has been set. All that is
3722 ** left to do is to link the new object into the linked list starting
3723 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3724 ** mutex.
3725 */
3726 sqlite3_mutex_enter(pShmNode->mutex);
3727 p->pNext = pShmNode->pFirst;
3728 pShmNode->pFirst = p;
3729 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003730 return SQLITE_OK;
3731
3732 /* Jump here on any error */
3733shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003734 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003735 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003736 unixLeaveMutex();
3737 return rc;
3738}
3739
3740/*
danda9fe0c2010-07-13 18:44:03 +00003741** This function is called to obtain a pointer to region iRegion of the
3742** shared-memory associated with the database file fd. Shared-memory regions
3743** are numbered starting from zero. Each shared-memory region is szRegion
3744** bytes in size.
3745**
3746** If an error occurs, an error code is returned and *pp is set to NULL.
3747**
3748** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3749** region has not been allocated (by any client, including one running in a
3750** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3751** bExtend is non-zero and the requested shared-memory region has not yet
3752** been allocated, it is allocated by this function.
3753**
3754** If the shared-memory region has already been allocated or is allocated by
3755** this call as described above, then it is mapped into this processes
3756** address space (if it is not already), *pp is set to point to the mapped
3757** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003758*/
danda9fe0c2010-07-13 18:44:03 +00003759static int unixShmMap(
3760 sqlite3_file *fd, /* Handle open on database file */
3761 int iRegion, /* Region to retrieve */
3762 int szRegion, /* Size of regions */
3763 int bExtend, /* True to extend file if necessary */
3764 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003765){
danda9fe0c2010-07-13 18:44:03 +00003766 unixFile *pDbFd = (unixFile*)fd;
3767 unixShm *p;
3768 unixShmNode *pShmNode;
3769 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003770
danda9fe0c2010-07-13 18:44:03 +00003771 /* If the shared-memory file has not yet been opened, open it now. */
3772 if( pDbFd->pShm==0 ){
3773 rc = unixOpenSharedMemory(pDbFd);
3774 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003775 }
drhd9e5c4f2010-05-12 18:01:39 +00003776
danda9fe0c2010-07-13 18:44:03 +00003777 p = pDbFd->pShm;
3778 pShmNode = p->pShmNode;
3779 sqlite3_mutex_enter(pShmNode->mutex);
3780 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3781
3782 if( pShmNode->nRegion<=iRegion ){
3783 char **apNew; /* New apRegion[] array */
3784 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3785 struct stat sStat; /* Used by fstat() */
3786
3787 pShmNode->szRegion = szRegion;
3788
3789 /* The requested region is not mapped into this processes address space.
3790 ** Check to see if it has been allocated (i.e. if the wal-index file is
3791 ** large enough to contain the requested region).
3792 */
drh99ab3b12011-03-02 15:09:07 +00003793 if( osFstat(pShmNode->h, &sStat) ){
danda9fe0c2010-07-13 18:44:03 +00003794 rc = SQLITE_IOERR_SHMSIZE;
3795 goto shmpage_out;
3796 }
3797
3798 if( sStat.st_size<nByte ){
3799 /* The requested memory region does not exist. If bExtend is set to
3800 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3801 **
3802 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3803 ** the requested memory region.
3804 */
3805 if( !bExtend ) goto shmpage_out;
drhff812312011-02-23 13:33:46 +00003806 if( robust_ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003807 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003808 goto shmpage_out;
3809 }
3810 }
3811
3812 /* Map the requested memory region into this processes address space. */
3813 apNew = (char **)sqlite3_realloc(
3814 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3815 );
3816 if( !apNew ){
3817 rc = SQLITE_IOERR_NOMEM;
3818 goto shmpage_out;
3819 }
3820 pShmNode->apRegion = apNew;
3821 while(pShmNode->nRegion<=iRegion){
3822 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003823 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003824 );
3825 if( pMem==MAP_FAILED ){
3826 rc = SQLITE_IOERR;
3827 goto shmpage_out;
3828 }
3829 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3830 pShmNode->nRegion++;
3831 }
3832 }
3833
3834shmpage_out:
3835 if( pShmNode->nRegion>iRegion ){
3836 *pp = pShmNode->apRegion[iRegion];
3837 }else{
3838 *pp = 0;
3839 }
3840 sqlite3_mutex_leave(pShmNode->mutex);
3841 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003842}
3843
3844/*
drhd9e5c4f2010-05-12 18:01:39 +00003845** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003846**
3847** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3848** different here than in posix. In xShmLock(), one can go from unlocked
3849** to shared and back or from unlocked to exclusive and back. But one may
3850** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003851*/
3852static int unixShmLock(
3853 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003854 int ofst, /* First lock to acquire or release */
3855 int n, /* Number of locks to acquire or release */
3856 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003857){
drh73b64e42010-05-30 19:55:15 +00003858 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3859 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3860 unixShm *pX; /* For looping over all siblings */
3861 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3862 int rc = SQLITE_OK; /* Result code */
3863 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003864
drhd91c68f2010-05-14 14:52:25 +00003865 assert( pShmNode==pDbFd->pInode->pShmNode );
3866 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003867 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003868 assert( n>=1 );
3869 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3870 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3871 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3872 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3873 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003874
drhc99597c2010-05-31 01:41:15 +00003875 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003876 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003877 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003878 if( flags & SQLITE_SHM_UNLOCK ){
3879 u16 allMask = 0; /* Mask of locks held by siblings */
3880
3881 /* See if any siblings hold this same lock */
3882 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3883 if( pX==p ) continue;
3884 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3885 allMask |= pX->sharedMask;
3886 }
3887
3888 /* Unlock the system-level locks */
3889 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003890 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003891 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003892 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003893 }
drh73b64e42010-05-30 19:55:15 +00003894
3895 /* Undo the local locks */
3896 if( rc==SQLITE_OK ){
3897 p->exclMask &= ~mask;
3898 p->sharedMask &= ~mask;
3899 }
3900 }else if( flags & SQLITE_SHM_SHARED ){
3901 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3902
3903 /* Find out which shared locks are already held by sibling connections.
3904 ** If any sibling already holds an exclusive lock, go ahead and return
3905 ** SQLITE_BUSY.
3906 */
3907 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003908 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003909 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003910 break;
3911 }
3912 allShared |= pX->sharedMask;
3913 }
3914
3915 /* Get shared locks at the system level, if necessary */
3916 if( rc==SQLITE_OK ){
3917 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003918 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003919 }else{
drh73b64e42010-05-30 19:55:15 +00003920 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003921 }
drhd9e5c4f2010-05-12 18:01:39 +00003922 }
drh73b64e42010-05-30 19:55:15 +00003923
3924 /* Get the local shared locks */
3925 if( rc==SQLITE_OK ){
3926 p->sharedMask |= mask;
3927 }
3928 }else{
3929 /* Make sure no sibling connections hold locks that will block this
3930 ** lock. If any do, return SQLITE_BUSY right away.
3931 */
3932 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003933 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3934 rc = SQLITE_BUSY;
3935 break;
3936 }
3937 }
3938
3939 /* Get the exclusive locks at the system level. Then if successful
3940 ** also mark the local connection as being locked.
3941 */
3942 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003943 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003944 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003945 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003946 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003947 }
drhd9e5c4f2010-05-12 18:01:39 +00003948 }
3949 }
drhd91c68f2010-05-14 14:52:25 +00003950 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003951 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3952 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003953 return rc;
3954}
3955
drh286a2882010-05-20 23:51:06 +00003956/*
3957** Implement a memory barrier or memory fence on shared memory.
3958**
3959** All loads and stores begun before the barrier must complete before
3960** any load or store begun after the barrier.
3961*/
3962static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003963 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003964){
drhff828942010-06-26 21:34:06 +00003965 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003966 unixEnterMutex();
3967 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003968}
3969
dan18801912010-06-14 14:07:50 +00003970/*
danda9fe0c2010-07-13 18:44:03 +00003971** Close a connection to shared-memory. Delete the underlying
3972** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003973**
3974** If there is no shared memory associated with the connection then this
3975** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003976*/
danda9fe0c2010-07-13 18:44:03 +00003977static int unixShmUnmap(
3978 sqlite3_file *fd, /* The underlying database file */
3979 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003980){
danda9fe0c2010-07-13 18:44:03 +00003981 unixShm *p; /* The connection to be closed */
3982 unixShmNode *pShmNode; /* The underlying shared-memory file */
3983 unixShm **pp; /* For looping over sibling connections */
3984 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003985
danda9fe0c2010-07-13 18:44:03 +00003986 pDbFd = (unixFile*)fd;
3987 p = pDbFd->pShm;
3988 if( p==0 ) return SQLITE_OK;
3989 pShmNode = p->pShmNode;
3990
3991 assert( pShmNode==pDbFd->pInode->pShmNode );
3992 assert( pShmNode->pInode==pDbFd->pInode );
3993
3994 /* Remove connection p from the set of connections associated
3995 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003996 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003997 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3998 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003999
danda9fe0c2010-07-13 18:44:03 +00004000 /* Free the connection p */
4001 sqlite3_free(p);
4002 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004003 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004004
4005 /* If pShmNode->nRef has reached 0, then close the underlying
4006 ** shared-memory file, too */
4007 unixEnterMutex();
4008 assert( pShmNode->nRef>0 );
4009 pShmNode->nRef--;
4010 if( pShmNode->nRef==0 ){
4011 if( deleteFlag ) unlink(pShmNode->zFilename);
4012 unixShmPurge(pDbFd);
4013 }
4014 unixLeaveMutex();
4015
4016 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004017}
drh286a2882010-05-20 23:51:06 +00004018
danda9fe0c2010-07-13 18:44:03 +00004019
drhd9e5c4f2010-05-12 18:01:39 +00004020#else
drh6b017cc2010-06-14 18:01:46 +00004021# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004022# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004023# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004024# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004025#endif /* #ifndef SQLITE_OMIT_WAL */
4026
drh734c9862008-11-28 15:37:20 +00004027/*
4028** Here ends the implementation of all sqlite3_file methods.
4029**
4030********************** End sqlite3_file Methods *******************************
4031******************************************************************************/
4032
4033/*
drh6b9d6dd2008-12-03 19:34:47 +00004034** This division contains definitions of sqlite3_io_methods objects that
4035** implement various file locking strategies. It also contains definitions
4036** of "finder" functions. A finder-function is used to locate the appropriate
4037** sqlite3_io_methods object for a particular database file. The pAppData
4038** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4039** the correct finder-function for that VFS.
4040**
4041** Most finder functions return a pointer to a fixed sqlite3_io_methods
4042** object. The only interesting finder-function is autolockIoFinder, which
4043** looks at the filesystem type and tries to guess the best locking
4044** strategy from that.
4045**
drh1875f7a2008-12-08 18:19:17 +00004046** For finder-funtion F, two objects are created:
4047**
4048** (1) The real finder-function named "FImpt()".
4049**
dane946c392009-08-22 11:39:46 +00004050** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004051**
4052**
4053** A pointer to the F pointer is used as the pAppData value for VFS
4054** objects. We have to do this instead of letting pAppData point
4055** directly at the finder-function since C90 rules prevent a void*
4056** from be cast into a function pointer.
4057**
drh6b9d6dd2008-12-03 19:34:47 +00004058**
drh7708e972008-11-29 00:56:52 +00004059** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004060**
drh7708e972008-11-29 00:56:52 +00004061** * A constant sqlite3_io_methods object call METHOD that has locking
4062** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4063**
4064** * An I/O method finder function called FINDER that returns a pointer
4065** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004066*/
drhd9e5c4f2010-05-12 18:01:39 +00004067#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004068static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004069 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004070 CLOSE, /* xClose */ \
4071 unixRead, /* xRead */ \
4072 unixWrite, /* xWrite */ \
4073 unixTruncate, /* xTruncate */ \
4074 unixSync, /* xSync */ \
4075 unixFileSize, /* xFileSize */ \
4076 LOCK, /* xLock */ \
4077 UNLOCK, /* xUnlock */ \
4078 CKLOCK, /* xCheckReservedLock */ \
4079 unixFileControl, /* xFileControl */ \
4080 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004081 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004082 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004083 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004084 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004085 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004086}; \
drh0c2694b2009-09-03 16:23:44 +00004087static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4088 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004089 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004090} \
drh0c2694b2009-09-03 16:23:44 +00004091static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004092 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004093
4094/*
4095** Here are all of the sqlite3_io_methods objects for each of the
4096** locking strategies. Functions that return pointers to these methods
4097** are also created.
4098*/
4099IOMETHODS(
4100 posixIoFinder, /* Finder function name */
4101 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004102 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004103 unixClose, /* xClose method */
4104 unixLock, /* xLock method */
4105 unixUnlock, /* xUnlock method */
4106 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004107)
drh7708e972008-11-29 00:56:52 +00004108IOMETHODS(
4109 nolockIoFinder, /* Finder function name */
4110 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004111 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004112 nolockClose, /* xClose method */
4113 nolockLock, /* xLock method */
4114 nolockUnlock, /* xUnlock method */
4115 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004116)
drh7708e972008-11-29 00:56:52 +00004117IOMETHODS(
4118 dotlockIoFinder, /* Finder function name */
4119 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004120 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004121 dotlockClose, /* xClose method */
4122 dotlockLock, /* xLock method */
4123 dotlockUnlock, /* xUnlock method */
4124 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004125)
drh7708e972008-11-29 00:56:52 +00004126
chw78a13182009-04-07 05:35:03 +00004127#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004128IOMETHODS(
4129 flockIoFinder, /* Finder function name */
4130 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004131 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004132 flockClose, /* xClose method */
4133 flockLock, /* xLock method */
4134 flockUnlock, /* xUnlock method */
4135 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004136)
drh7708e972008-11-29 00:56:52 +00004137#endif
4138
drh6c7d5c52008-11-21 20:32:33 +00004139#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004140IOMETHODS(
4141 semIoFinder, /* Finder function name */
4142 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004143 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004144 semClose, /* xClose method */
4145 semLock, /* xLock method */
4146 semUnlock, /* xUnlock method */
4147 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004148)
aswiftaebf4132008-11-21 00:10:35 +00004149#endif
drh7708e972008-11-29 00:56:52 +00004150
drhd2cb50b2009-01-09 21:41:17 +00004151#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004152IOMETHODS(
4153 afpIoFinder, /* Finder function name */
4154 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004155 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004156 afpClose, /* xClose method */
4157 afpLock, /* xLock method */
4158 afpUnlock, /* xUnlock method */
4159 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004160)
drh715ff302008-12-03 22:32:44 +00004161#endif
4162
4163/*
4164** The proxy locking method is a "super-method" in the sense that it
4165** opens secondary file descriptors for the conch and lock files and
4166** it uses proxy, dot-file, AFP, and flock() locking methods on those
4167** secondary files. For this reason, the division that implements
4168** proxy locking is located much further down in the file. But we need
4169** to go ahead and define the sqlite3_io_methods and finder function
4170** for proxy locking here. So we forward declare the I/O methods.
4171*/
drhd2cb50b2009-01-09 21:41:17 +00004172#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004173static int proxyClose(sqlite3_file*);
4174static int proxyLock(sqlite3_file*, int);
4175static int proxyUnlock(sqlite3_file*, int);
4176static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004177IOMETHODS(
4178 proxyIoFinder, /* Finder function name */
4179 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004180 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004181 proxyClose, /* xClose method */
4182 proxyLock, /* xLock method */
4183 proxyUnlock, /* xUnlock method */
4184 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004185)
aswiftaebf4132008-11-21 00:10:35 +00004186#endif
drh7708e972008-11-29 00:56:52 +00004187
drh7ed97b92010-01-20 13:07:21 +00004188/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4189#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4190IOMETHODS(
4191 nfsIoFinder, /* Finder function name */
4192 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004193 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004194 unixClose, /* xClose method */
4195 unixLock, /* xLock method */
4196 nfsUnlock, /* xUnlock method */
4197 unixCheckReservedLock /* xCheckReservedLock method */
4198)
4199#endif
drh7708e972008-11-29 00:56:52 +00004200
drhd2cb50b2009-01-09 21:41:17 +00004201#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004202/*
drh6b9d6dd2008-12-03 19:34:47 +00004203** This "finder" function attempts to determine the best locking strategy
4204** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004205** object that implements that strategy.
4206**
4207** This is for MacOSX only.
4208*/
drh1875f7a2008-12-08 18:19:17 +00004209static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004210 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004211 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004212){
4213 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004214 const char *zFilesystem; /* Filesystem type name */
4215 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004216 } aMap[] = {
4217 { "hfs", &posixIoMethods },
4218 { "ufs", &posixIoMethods },
4219 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004220 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004221 { "webdav", &nolockIoMethods },
4222 { 0, 0 }
4223 };
4224 int i;
4225 struct statfs fsInfo;
4226 struct flock lockInfo;
4227
4228 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004229 /* If filePath==NULL that means we are dealing with a transient file
4230 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004231 return &nolockIoMethods;
4232 }
4233 if( statfs(filePath, &fsInfo) != -1 ){
4234 if( fsInfo.f_flags & MNT_RDONLY ){
4235 return &nolockIoMethods;
4236 }
4237 for(i=0; aMap[i].zFilesystem; i++){
4238 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4239 return aMap[i].pMethods;
4240 }
4241 }
4242 }
4243
4244 /* Default case. Handles, amongst others, "nfs".
4245 ** Test byte-range lock using fcntl(). If the call succeeds,
4246 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004247 */
drh7708e972008-11-29 00:56:52 +00004248 lockInfo.l_len = 1;
4249 lockInfo.l_start = 0;
4250 lockInfo.l_whence = SEEK_SET;
4251 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004252 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004253 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4254 return &nfsIoMethods;
4255 } else {
4256 return &posixIoMethods;
4257 }
drh7708e972008-11-29 00:56:52 +00004258 }else{
4259 return &dotlockIoMethods;
4260 }
4261}
drh0c2694b2009-09-03 16:23:44 +00004262static const sqlite3_io_methods
4263 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004264
drhd2cb50b2009-01-09 21:41:17 +00004265#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004266
chw78a13182009-04-07 05:35:03 +00004267#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4268/*
4269** This "finder" function attempts to determine the best locking strategy
4270** for the database file "filePath". It then returns the sqlite3_io_methods
4271** object that implements that strategy.
4272**
4273** This is for VXWorks only.
4274*/
4275static const sqlite3_io_methods *autolockIoFinderImpl(
4276 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004277 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004278){
4279 struct flock lockInfo;
4280
4281 if( !filePath ){
4282 /* If filePath==NULL that means we are dealing with a transient file
4283 ** that does not need to be locked. */
4284 return &nolockIoMethods;
4285 }
4286
4287 /* Test if fcntl() is supported and use POSIX style locks.
4288 ** Otherwise fall back to the named semaphore method.
4289 */
4290 lockInfo.l_len = 1;
4291 lockInfo.l_start = 0;
4292 lockInfo.l_whence = SEEK_SET;
4293 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004294 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004295 return &posixIoMethods;
4296 }else{
4297 return &semIoMethods;
4298 }
4299}
drh0c2694b2009-09-03 16:23:44 +00004300static const sqlite3_io_methods
4301 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004302
4303#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4304
drh7708e972008-11-29 00:56:52 +00004305/*
4306** An abstract type for a pointer to a IO method finder function:
4307*/
drh0c2694b2009-09-03 16:23:44 +00004308typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004309
aswiftaebf4132008-11-21 00:10:35 +00004310
drh734c9862008-11-28 15:37:20 +00004311/****************************************************************************
4312**************************** sqlite3_vfs methods ****************************
4313**
4314** This division contains the implementation of methods on the
4315** sqlite3_vfs object.
4316*/
4317
danielk1977a3d4c882007-03-23 10:08:38 +00004318/*
danielk1977e339d652008-06-28 11:23:00 +00004319** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004320*/
4321static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004322 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004323 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004324 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004325 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004326 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004327 int noLock, /* Omit locking if true */
4328 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004329){
drh7708e972008-11-29 00:56:52 +00004330 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004331 unixFile *pNew = (unixFile *)pId;
4332 int rc = SQLITE_OK;
4333
drh8af6c222010-05-14 12:43:01 +00004334 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004335
dane946c392009-08-22 11:39:46 +00004336 /* Parameter isDelete is only used on vxworks. Express this explicitly
4337 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004338 */
drh7708e972008-11-29 00:56:52 +00004339 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004340
dan00157392010-10-05 11:33:15 +00004341 /* Usually the path zFilename should not be a relative pathname. The
4342 ** exception is when opening the proxy "conch" file in builds that
4343 ** include the special Apple locking styles.
4344 */
dan00157392010-10-05 11:33:15 +00004345#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004346 assert( zFilename==0 || zFilename[0]=='/'
4347 || pVfs->pAppData==(void*)&autolockIoFinder );
4348#else
4349 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004350#endif
dan00157392010-10-05 11:33:15 +00004351
drh308c2a52010-05-14 11:30:18 +00004352 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004353 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004354 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004355 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004356 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004357
drh6c7d5c52008-11-21 20:32:33 +00004358#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004359 pNew->pId = vxworksFindFileId(zFilename);
4360 if( pNew->pId==0 ){
4361 noLock = 1;
4362 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004363 }
4364#endif
4365
drhda0e7682008-07-30 15:27:54 +00004366 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004367 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004368 }else{
drh0c2694b2009-09-03 16:23:44 +00004369 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004370#if SQLITE_ENABLE_LOCKING_STYLE
4371 /* Cache zFilename in the locking context (AFP and dotlock override) for
4372 ** proxyLock activation is possible (remote proxy is based on db name)
4373 ** zFilename remains valid until file is closed, to support */
4374 pNew->lockingContext = (void*)zFilename;
4375#endif
drhda0e7682008-07-30 15:27:54 +00004376 }
danielk1977e339d652008-06-28 11:23:00 +00004377
drh7ed97b92010-01-20 13:07:21 +00004378 if( pLockingStyle == &posixIoMethods
4379#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4380 || pLockingStyle == &nfsIoMethods
4381#endif
4382 ){
drh7708e972008-11-29 00:56:52 +00004383 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004384 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004385 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004386 /* If an error occured in findInodeInfo(), close the file descriptor
4387 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004388 ** in two scenarios:
4389 **
4390 ** (a) A call to fstat() failed.
4391 ** (b) A malloc failed.
4392 **
4393 ** Scenario (b) may only occur if the process is holding no other
4394 ** file descriptors open on the same file. If there were other file
4395 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004396 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004397 ** handle h - as it is guaranteed that no posix locks will be released
4398 ** by doing so.
4399 **
4400 ** If scenario (a) caused the error then things are not so safe. The
4401 ** implicit assumption here is that if fstat() fails, things are in
4402 ** such bad shape that dropping a lock or two doesn't matter much.
4403 */
drh0e9365c2011-03-02 02:08:13 +00004404 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004405 h = -1;
4406 }
drh7708e972008-11-29 00:56:52 +00004407 unixLeaveMutex();
4408 }
danielk1977e339d652008-06-28 11:23:00 +00004409
drhd2cb50b2009-01-09 21:41:17 +00004410#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004411 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004412 /* AFP locking uses the file path so it needs to be included in
4413 ** the afpLockingContext.
4414 */
4415 afpLockingContext *pCtx;
4416 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4417 if( pCtx==0 ){
4418 rc = SQLITE_NOMEM;
4419 }else{
4420 /* NB: zFilename exists and remains valid until the file is closed
4421 ** according to requirement F11141. So we do not need to make a
4422 ** copy of the filename. */
4423 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004424 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004425 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004426 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004427 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004428 if( rc!=SQLITE_OK ){
4429 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004430 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004431 h = -1;
4432 }
drh7708e972008-11-29 00:56:52 +00004433 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004434 }
drh7708e972008-11-29 00:56:52 +00004435 }
4436#endif
danielk1977e339d652008-06-28 11:23:00 +00004437
drh7708e972008-11-29 00:56:52 +00004438 else if( pLockingStyle == &dotlockIoMethods ){
4439 /* Dotfile locking uses the file path so it needs to be included in
4440 ** the dotlockLockingContext
4441 */
4442 char *zLockFile;
4443 int nFilename;
drhea678832008-12-10 19:26:22 +00004444 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004445 zLockFile = (char *)sqlite3_malloc(nFilename);
4446 if( zLockFile==0 ){
4447 rc = SQLITE_NOMEM;
4448 }else{
4449 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004450 }
drh7708e972008-11-29 00:56:52 +00004451 pNew->lockingContext = zLockFile;
4452 }
danielk1977e339d652008-06-28 11:23:00 +00004453
drh6c7d5c52008-11-21 20:32:33 +00004454#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004455 else if( pLockingStyle == &semIoMethods ){
4456 /* Named semaphore locking uses the file path so it needs to be
4457 ** included in the semLockingContext
4458 */
4459 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004460 rc = findInodeInfo(pNew, &pNew->pInode);
4461 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4462 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004463 int n;
drh2238dcc2009-08-27 17:56:20 +00004464 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004465 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004466 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004467 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004468 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4469 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004470 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004471 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004472 }
chw97185482008-11-17 08:05:31 +00004473 }
drh7708e972008-11-29 00:56:52 +00004474 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004475 }
drh7708e972008-11-29 00:56:52 +00004476#endif
aswift5b1a2562008-08-22 00:22:35 +00004477
4478 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004479#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004480 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004481 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004482 h = -1;
chw97185482008-11-17 08:05:31 +00004483 unlink(zFilename);
4484 isDelete = 0;
4485 }
4486 pNew->isDelete = isDelete;
4487#endif
danielk1977e339d652008-06-28 11:23:00 +00004488 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004489 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4490 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004491 }else{
drh7708e972008-11-29 00:56:52 +00004492 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004493 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004494 }
danielk1977e339d652008-06-28 11:23:00 +00004495 return rc;
drh054889e2005-11-30 03:20:31 +00004496}
drh9c06c952005-11-26 00:25:00 +00004497
danielk1977ad94b582007-08-20 06:44:22 +00004498/*
4499** Open a file descriptor to the directory containing file zFilename.
4500** If successful, *pFd is set to the opened file descriptor and
4501** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4502** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4503** value.
4504**
4505** If SQLITE_OK is returned, the caller is responsible for closing
4506** the file descriptor *pFd using close().
4507*/
danielk1977fee2d252007-08-18 10:59:19 +00004508static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004509 int ii;
drh777b17a2007-09-20 10:02:54 +00004510 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004511 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004512
drh153c62c2007-08-24 03:51:33 +00004513 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004514 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004515 if( ii>0 ){
4516 zDirname[ii] = '\0';
drh99ab3b12011-03-02 15:09:07 +00004517 fd = osOpen(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004518 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004519#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004520 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004521#endif
drh308c2a52010-05-14 11:30:18 +00004522 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004523 }
4524 }
danielk1977fee2d252007-08-18 10:59:19 +00004525 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004526 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004527}
4528
danielk1977b4b47412007-08-17 15:53:36 +00004529/*
drh8b3cf822010-06-01 21:02:51 +00004530** Return the name of a directory in which to put temporary files.
4531** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004532*/
drh7234c6d2010-06-19 15:10:09 +00004533static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004534 static const char *azDirs[] = {
4535 0,
aswiftaebf4132008-11-21 00:10:35 +00004536 0,
danielk197717b90b52008-06-06 11:11:25 +00004537 "/var/tmp",
4538 "/usr/tmp",
4539 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004540 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004541 };
drh8b3cf822010-06-01 21:02:51 +00004542 unsigned int i;
4543 struct stat buf;
4544 const char *zDir = 0;
4545
4546 azDirs[0] = sqlite3_temp_directory;
4547 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004548 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004549 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004550 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004551 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004552 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004553 break;
4554 }
4555 return zDir;
4556}
4557
4558/*
4559** Create a temporary file name in zBuf. zBuf must be allocated
4560** by the calling process and must be big enough to hold at least
4561** pVfs->mxPathname bytes.
4562*/
4563static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004564 static const unsigned char zChars[] =
4565 "abcdefghijklmnopqrstuvwxyz"
4566 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4567 "0123456789";
drh41022642008-11-21 00:24:42 +00004568 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004569 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004570
4571 /* It's odd to simulate an io-error here, but really this is just
4572 ** using the io-error infrastructure to test that SQLite handles this
4573 ** function failing.
4574 */
4575 SimulateIOError( return SQLITE_IOERR );
4576
drh7234c6d2010-06-19 15:10:09 +00004577 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004578 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004579
4580 /* Check that the output buffer is large enough for the temporary file
4581 ** name. If it is not, return SQLITE_ERROR.
4582 */
danielk197700e13612008-11-17 19:18:54 +00004583 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004584 return SQLITE_ERROR;
4585 }
4586
4587 do{
4588 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004589 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004590 sqlite3_randomness(15, &zBuf[j]);
4591 for(i=0; i<15; i++, j++){
4592 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4593 }
4594 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004595 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004596 return SQLITE_OK;
4597}
4598
drhd2cb50b2009-01-09 21:41:17 +00004599#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004600/*
4601** Routine to transform a unixFile into a proxy-locking unixFile.
4602** Implementation in the proxy-lock division, but used by unixOpen()
4603** if SQLITE_PREFER_PROXY_LOCKING is defined.
4604*/
4605static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004606#endif
drhc66d5b62008-12-03 22:48:32 +00004607
dan08da86a2009-08-21 17:18:03 +00004608/*
4609** Search for an unused file descriptor that was opened on the database
4610** file (not a journal or master-journal file) identified by pathname
4611** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4612** argument to this function.
4613**
4614** Such a file descriptor may exist if a database connection was closed
4615** but the associated file descriptor could not be closed because some
4616** other file descriptor open on the same file is holding a file-lock.
4617** Refer to comments in the unixClose() function and the lengthy comment
4618** describing "Posix Advisory Locking" at the start of this file for
4619** further details. Also, ticket #4018.
4620**
4621** If a suitable file descriptor is found, then it is returned. If no
4622** such file descriptor is located, -1 is returned.
4623*/
dane946c392009-08-22 11:39:46 +00004624static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4625 UnixUnusedFd *pUnused = 0;
4626
4627 /* Do not search for an unused file descriptor on vxworks. Not because
4628 ** vxworks would not benefit from the change (it might, we're not sure),
4629 ** but because no way to test it is currently available. It is better
4630 ** not to risk breaking vxworks support for the sake of such an obscure
4631 ** feature. */
4632#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004633 struct stat sStat; /* Results of stat() call */
4634
4635 /* A stat() call may fail for various reasons. If this happens, it is
4636 ** almost certain that an open() call on the same path will also fail.
4637 ** For this reason, if an error occurs in the stat() call here, it is
4638 ** ignored and -1 is returned. The caller will try to open a new file
4639 ** descriptor on the same path, fail, and return an error to SQLite.
4640 **
4641 ** Even if a subsequent open() call does succeed, the consequences of
4642 ** not searching for a resusable file descriptor are not dire. */
4643 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004644 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004645
4646 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004647 pInode = inodeList;
4648 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4649 || pInode->fileId.ino!=sStat.st_ino) ){
4650 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004651 }
drh8af6c222010-05-14 12:43:01 +00004652 if( pInode ){
dane946c392009-08-22 11:39:46 +00004653 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004654 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004655 pUnused = *pp;
4656 if( pUnused ){
4657 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004658 }
4659 }
4660 unixLeaveMutex();
4661 }
dane946c392009-08-22 11:39:46 +00004662#endif /* if !OS_VXWORKS */
4663 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004664}
danielk197717b90b52008-06-06 11:11:25 +00004665
4666/*
danddb0ac42010-07-14 14:48:58 +00004667** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004668** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004669** and a value suitable for passing as the third argument to open(2) is
4670** written to *pMode. If an IO error occurs, an SQLite error code is
4671** returned and the value of *pMode is not modified.
4672**
4673** If the file being opened is a temporary file, it is always created with
4674** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004675** is a database or master journal file, it is created with the permissions
4676** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004677**
drh8ab58662010-07-15 18:38:39 +00004678** Finally, if the file being opened is a WAL or regular journal file, then
4679** this function queries the file-system for the permissions on the
4680** corresponding database file and sets *pMode to this value. Whenever
4681** possible, WAL and journal files are created using the same permissions
4682** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004683*/
4684static int findCreateFileMode(
4685 const char *zPath, /* Path of file (possibly) being created */
4686 int flags, /* Flags passed as 4th argument to xOpen() */
4687 mode_t *pMode /* OUT: Permissions to open file with */
4688){
4689 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004690 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004691 char zDb[MAX_PATHNAME+1]; /* Database file path */
4692 int nDb; /* Number of valid bytes in zDb */
4693 struct stat sStat; /* Output of stat() on database file */
4694
dana0c989d2010-11-05 18:07:37 +00004695 /* zPath is a path to a WAL or journal file. The following block derives
4696 ** the path to the associated database file from zPath. This block handles
4697 ** the following naming conventions:
4698 **
4699 ** "<path to db>-journal"
4700 ** "<path to db>-wal"
4701 ** "<path to db>-journal-NNNN"
4702 ** "<path to db>-wal-NNNN"
4703 **
4704 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4705 ** used by the test_multiplex.c module.
4706 */
4707 nDb = sqlite3Strlen30(zPath) - 1;
4708 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4709 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004710 memcpy(zDb, zPath, nDb);
4711 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004712
danddb0ac42010-07-14 14:48:58 +00004713 if( 0==stat(zDb, &sStat) ){
4714 *pMode = sStat.st_mode & 0777;
4715 }else{
4716 rc = SQLITE_IOERR_FSTAT;
4717 }
4718 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4719 *pMode = 0600;
4720 }else{
4721 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4722 }
4723 return rc;
4724}
4725
4726/*
danielk1977ad94b582007-08-20 06:44:22 +00004727** Open the file zPath.
4728**
danielk1977b4b47412007-08-17 15:53:36 +00004729** Previously, the SQLite OS layer used three functions in place of this
4730** one:
4731**
4732** sqlite3OsOpenReadWrite();
4733** sqlite3OsOpenReadOnly();
4734** sqlite3OsOpenExclusive();
4735**
4736** These calls correspond to the following combinations of flags:
4737**
4738** ReadWrite() -> (READWRITE | CREATE)
4739** ReadOnly() -> (READONLY)
4740** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4741**
4742** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4743** true, the file was configured to be automatically deleted when the
4744** file handle closed. To achieve the same effect using this new
4745** interface, add the DELETEONCLOSE flag to those specified above for
4746** OpenExclusive().
4747*/
4748static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004749 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4750 const char *zPath, /* Pathname of file to be opened */
4751 sqlite3_file *pFile, /* The file descriptor to be filled in */
4752 int flags, /* Input flags to control the opening */
4753 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004754){
dan08da86a2009-08-21 17:18:03 +00004755 unixFile *p = (unixFile *)pFile;
4756 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004757 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004758 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004759 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004760 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004761 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004762
4763 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4764 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4765 int isCreate = (flags & SQLITE_OPEN_CREATE);
4766 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4767 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004768#if SQLITE_ENABLE_LOCKING_STYLE
4769 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4770#endif
danielk1977b4b47412007-08-17 15:53:36 +00004771
danielk1977fee2d252007-08-18 10:59:19 +00004772 /* If creating a master or main-file journal, this function will open
4773 ** a file-descriptor on the directory too. The first time unixSync()
4774 ** is called the directory file descriptor will be fsync()ed and close()d.
4775 */
danddb0ac42010-07-14 14:48:58 +00004776 int isOpenDirectory = (isCreate && (
4777 eType==SQLITE_OPEN_MASTER_JOURNAL
4778 || eType==SQLITE_OPEN_MAIN_JOURNAL
4779 || eType==SQLITE_OPEN_WAL
4780 ));
danielk1977fee2d252007-08-18 10:59:19 +00004781
danielk197717b90b52008-06-06 11:11:25 +00004782 /* If argument zPath is a NULL pointer, this function is required to open
4783 ** a temporary file. Use this buffer to store the file name in.
4784 */
4785 char zTmpname[MAX_PATHNAME+1];
4786 const char *zName = zPath;
4787
danielk1977fee2d252007-08-18 10:59:19 +00004788 /* Check the following statements are true:
4789 **
4790 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4791 ** (b) if CREATE is set, then READWRITE must also be set, and
4792 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004793 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004794 */
danielk1977b4b47412007-08-17 15:53:36 +00004795 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004796 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004797 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004798 assert(isDelete==0 || isCreate);
4799
danddb0ac42010-07-14 14:48:58 +00004800 /* The main DB, main journal, WAL file and master journal are never
4801 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004802 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4803 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4804 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004805 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004806
danielk1977fee2d252007-08-18 10:59:19 +00004807 /* Assert that the upper layer has set one of the "file-type" flags. */
4808 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4809 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4810 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004811 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004812 );
4813
dan08da86a2009-08-21 17:18:03 +00004814 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004815
dan08da86a2009-08-21 17:18:03 +00004816 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004817 UnixUnusedFd *pUnused;
4818 pUnused = findReusableFd(zName, flags);
4819 if( pUnused ){
4820 fd = pUnused->fd;
4821 }else{
dan6aa657f2009-08-24 18:57:58 +00004822 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004823 if( !pUnused ){
4824 return SQLITE_NOMEM;
4825 }
4826 }
4827 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004828 }else if( !zName ){
4829 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004830 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004831 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004832 if( rc!=SQLITE_OK ){
4833 return rc;
4834 }
4835 zName = zTmpname;
4836 }
4837
dan08da86a2009-08-21 17:18:03 +00004838 /* Determine the value of the flags parameter passed to POSIX function
4839 ** open(). These must be calculated even if open() is not called, as
4840 ** they may be stored as part of the file handle and used by the
4841 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004842 if( isReadonly ) openFlags |= O_RDONLY;
4843 if( isReadWrite ) openFlags |= O_RDWR;
4844 if( isCreate ) openFlags |= O_CREAT;
4845 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4846 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004847
danielk1977b4b47412007-08-17 15:53:36 +00004848 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004849 mode_t openMode; /* Permissions to create file with */
4850 rc = findCreateFileMode(zName, flags, &openMode);
4851 if( rc!=SQLITE_OK ){
4852 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004853 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004854 return rc;
4855 }
drh99ab3b12011-03-02 15:09:07 +00004856 fd = osOpen(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004857 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004858 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4859 /* Failed to open the file for read/write access. Try read-only. */
4860 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004861 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004862 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004863 openFlags |= O_RDONLY;
drh99ab3b12011-03-02 15:09:07 +00004864 fd = osOpen(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004865 }
4866 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004867 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004868 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004869 }
danielk1977b4b47412007-08-17 15:53:36 +00004870 }
dan08da86a2009-08-21 17:18:03 +00004871 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004872 if( pOutFlags ){
4873 *pOutFlags = flags;
4874 }
4875
dane946c392009-08-22 11:39:46 +00004876 if( p->pUnused ){
4877 p->pUnused->fd = fd;
4878 p->pUnused->flags = flags;
4879 }
4880
danielk1977b4b47412007-08-17 15:53:36 +00004881 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004882#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004883 zPath = zName;
4884#else
danielk197717b90b52008-06-06 11:11:25 +00004885 unlink(zName);
chw97185482008-11-17 08:05:31 +00004886#endif
danielk1977b4b47412007-08-17 15:53:36 +00004887 }
drh41022642008-11-21 00:24:42 +00004888#if SQLITE_ENABLE_LOCKING_STYLE
4889 else{
dan08da86a2009-08-21 17:18:03 +00004890 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004891 }
4892#endif
4893
danielk1977fee2d252007-08-18 10:59:19 +00004894 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004895 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004896 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004897 /* It is safe to close fd at this point, because it is guaranteed not
4898 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004899 ** it would not be safe to close as this would release any locks held
4900 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004901 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00004902 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004903 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004904 }
4905 }
danielk1977e339d652008-06-28 11:23:00 +00004906
4907#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004908 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00004909#endif
4910
drhda0e7682008-07-30 15:27:54 +00004911 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004912
drh7ed97b92010-01-20 13:07:21 +00004913
4914#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4915 struct statfs fsInfo;
4916 if( fstatfs(fd, &fsInfo) == -1 ){
4917 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00004918 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
4919 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004920 return SQLITE_IOERR_ACCESS;
4921 }
4922 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4923 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4924 }
4925#endif
4926
4927#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004928#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004929 isAutoProxy = 1;
4930#endif
4931 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004932 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4933 int useProxy = 0;
4934
dan08da86a2009-08-21 17:18:03 +00004935 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4936 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004937 if( envforce!=NULL ){
4938 useProxy = atoi(envforce)>0;
4939 }else{
4940 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004941 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004942 /* In theory, the close(fd) call is sub-optimal. If the file opened
4943 ** with fd is a database file, and there are other connections open
4944 ** on that file that are currently holding advisory locks on it,
4945 ** then the call to close() will cancel those locks. In practice,
4946 ** we're assuming that statfs() doesn't fail very often. At least
4947 ** not while other file descriptors opened by the same process on
4948 ** the same file are working. */
4949 p->lastErrno = errno;
4950 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00004951 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00004952 }
drh0e9365c2011-03-02 02:08:13 +00004953 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004954 rc = SQLITE_IOERR_ACCESS;
4955 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004956 }
4957 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4958 }
4959 if( useProxy ){
4960 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4961 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004962 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004963 if( rc!=SQLITE_OK ){
4964 /* Use unixClose to clean up the resources added in fillInUnixFile
4965 ** and clear all the structure's references. Specifically,
4966 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4967 */
4968 unixClose(pFile);
4969 return rc;
4970 }
aswiftaebf4132008-11-21 00:10:35 +00004971 }
dane946c392009-08-22 11:39:46 +00004972 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004973 }
4974 }
4975#endif
4976
dane946c392009-08-22 11:39:46 +00004977 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4978open_finished:
4979 if( rc!=SQLITE_OK ){
4980 sqlite3_free(p->pUnused);
4981 }
4982 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004983}
4984
dane946c392009-08-22 11:39:46 +00004985
danielk1977b4b47412007-08-17 15:53:36 +00004986/*
danielk1977fee2d252007-08-18 10:59:19 +00004987** Delete the file at zPath. If the dirSync argument is true, fsync()
4988** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004989*/
drh6b9d6dd2008-12-03 19:34:47 +00004990static int unixDelete(
4991 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4992 const char *zPath, /* Name of file to be deleted */
4993 int dirSync /* If true, fsync() directory after deleting file */
4994){
danielk1977fee2d252007-08-18 10:59:19 +00004995 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004996 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004997 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004998 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00004999 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005000 }
danielk1977d39fa702008-10-16 13:27:40 +00005001#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005002 if( dirSync ){
5003 int fd;
5004 rc = openDirectory(zPath, &fd);
5005 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005006#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005007 if( fsync(fd)==-1 )
5008#else
5009 if( fsync(fd) )
5010#endif
5011 {
dane18d4952011-02-21 11:46:24 +00005012 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005013 }
drh0e9365c2011-03-02 02:08:13 +00005014 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005015 }
5016 }
danielk1977d138dd82008-10-15 16:02:48 +00005017#endif
danielk1977fee2d252007-08-18 10:59:19 +00005018 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005019}
5020
danielk197790949c22007-08-17 16:50:38 +00005021/*
5022** Test the existance of or access permissions of file zPath. The
5023** test performed depends on the value of flags:
5024**
5025** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5026** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5027** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5028**
5029** Otherwise return 0.
5030*/
danielk1977861f7452008-06-05 11:39:11 +00005031static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005032 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5033 const char *zPath, /* Path of the file to examine */
5034 int flags, /* What do we want to learn about the zPath file? */
5035 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005036){
rse25c0d1a2007-09-20 08:38:14 +00005037 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005038 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005039 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005040 switch( flags ){
5041 case SQLITE_ACCESS_EXISTS:
5042 amode = F_OK;
5043 break;
5044 case SQLITE_ACCESS_READWRITE:
5045 amode = W_OK|R_OK;
5046 break;
drh50d3f902007-08-27 21:10:36 +00005047 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005048 amode = R_OK;
5049 break;
5050
5051 default:
5052 assert(!"Invalid flags argument");
5053 }
drh99ab3b12011-03-02 15:09:07 +00005054 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005055 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5056 struct stat buf;
5057 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5058 *pResOut = 0;
5059 }
5060 }
danielk1977861f7452008-06-05 11:39:11 +00005061 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005062}
5063
danielk1977b4b47412007-08-17 15:53:36 +00005064
5065/*
5066** Turn a relative pathname into a full pathname. The relative path
5067** is stored as a nul-terminated string in the buffer pointed to by
5068** zPath.
5069**
5070** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5071** (in this case, MAX_PATHNAME bytes). The full-path is written to
5072** this buffer before returning.
5073*/
danielk1977adfb9b02007-09-17 07:02:56 +00005074static int unixFullPathname(
5075 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5076 const char *zPath, /* Possibly relative input path */
5077 int nOut, /* Size of output buffer in bytes */
5078 char *zOut /* Output buffer */
5079){
danielk1977843e65f2007-09-01 16:16:15 +00005080
5081 /* It's odd to simulate an io-error here, but really this is just
5082 ** using the io-error infrastructure to test that SQLite handles this
5083 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005084 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005085 */
5086 SimulateIOError( return SQLITE_ERROR );
5087
drh153c62c2007-08-24 03:51:33 +00005088 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005089 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005090
drh3c7f2dc2007-12-06 13:26:20 +00005091 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005092 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005093 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005094 }else{
5095 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005096 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005097 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005098 }
drhea678832008-12-10 19:26:22 +00005099 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005100 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005101 }
5102 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005103}
5104
drh0ccebe72005-06-07 22:22:50 +00005105
drh761df872006-12-21 01:29:22 +00005106#ifndef SQLITE_OMIT_LOAD_EXTENSION
5107/*
5108** Interfaces for opening a shared library, finding entry points
5109** within the shared library, and closing the shared library.
5110*/
5111#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005112static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5113 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005114 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5115}
danielk197795c8a542007-09-01 06:51:27 +00005116
5117/*
5118** SQLite calls this function immediately after a call to unixDlSym() or
5119** unixDlOpen() fails (returns a null pointer). If a more detailed error
5120** message is available, it is written to zBufOut. If no error message
5121** is available, zBufOut is left unmodified and SQLite uses a default
5122** error message.
5123*/
danielk1977397d65f2008-11-19 11:35:39 +00005124static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005125 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005126 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005127 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005128 zErr = dlerror();
5129 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005130 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005131 }
drh6c7d5c52008-11-21 20:32:33 +00005132 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005133}
drh1875f7a2008-12-08 18:19:17 +00005134static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5135 /*
5136 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5137 ** cast into a pointer to a function. And yet the library dlsym() routine
5138 ** returns a void* which is really a pointer to a function. So how do we
5139 ** use dlsym() with -pedantic-errors?
5140 **
5141 ** Variable x below is defined to be a pointer to a function taking
5142 ** parameters void* and const char* and returning a pointer to a function.
5143 ** We initialize x by assigning it a pointer to the dlsym() function.
5144 ** (That assignment requires a cast.) Then we call the function that
5145 ** x points to.
5146 **
5147 ** This work-around is unlikely to work correctly on any system where
5148 ** you really cannot cast a function pointer into void*. But then, on the
5149 ** other hand, dlsym() will not work on such a system either, so we have
5150 ** not really lost anything.
5151 */
5152 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005153 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005154 x = (void(*(*)(void*,const char*))(void))dlsym;
5155 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005156}
danielk1977397d65f2008-11-19 11:35:39 +00005157static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5158 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005159 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005160}
danielk1977b4b47412007-08-17 15:53:36 +00005161#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5162 #define unixDlOpen 0
5163 #define unixDlError 0
5164 #define unixDlSym 0
5165 #define unixDlClose 0
5166#endif
5167
5168/*
danielk197790949c22007-08-17 16:50:38 +00005169** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005170*/
danielk1977397d65f2008-11-19 11:35:39 +00005171static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5172 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005173 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005174
drhbbd42a62004-05-22 17:41:58 +00005175 /* We have to initialize zBuf to prevent valgrind from reporting
5176 ** errors. The reports issued by valgrind are incorrect - we would
5177 ** prefer that the randomness be increased by making use of the
5178 ** uninitialized space in zBuf - but valgrind errors tend to worry
5179 ** some users. Rather than argue, it seems easier just to initialize
5180 ** the whole array and silence valgrind, even if that means less randomness
5181 ** in the random seed.
5182 **
5183 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005184 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005185 ** tests repeatable.
5186 */
danielk1977b4b47412007-08-17 15:53:36 +00005187 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005188#if !defined(SQLITE_TEST)
5189 {
drh842b8642005-01-21 17:53:17 +00005190 int pid, fd;
drh99ab3b12011-03-02 15:09:07 +00005191 fd = osOpen("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005192 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005193 time_t t;
5194 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005195 memcpy(zBuf, &t, sizeof(t));
5196 pid = getpid();
5197 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005198 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005199 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005200 }else{
drhe562be52011-03-02 18:01:10 +00005201 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005202 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005203 }
drhbbd42a62004-05-22 17:41:58 +00005204 }
5205#endif
drh72cbd072008-10-14 17:58:38 +00005206 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005207}
5208
danielk1977b4b47412007-08-17 15:53:36 +00005209
drhbbd42a62004-05-22 17:41:58 +00005210/*
5211** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005212** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005213** The return value is the number of microseconds of sleep actually
5214** requested from the underlying operating system, a number which
5215** might be greater than or equal to the argument, but not less
5216** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005217*/
danielk1977397d65f2008-11-19 11:35:39 +00005218static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005219#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005220 struct timespec sp;
5221
5222 sp.tv_sec = microseconds / 1000000;
5223 sp.tv_nsec = (microseconds % 1000000) * 1000;
5224 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005225 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005226 return microseconds;
5227#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005228 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005229 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005230 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005231#else
danielk1977b4b47412007-08-17 15:53:36 +00005232 int seconds = (microseconds+999999)/1000000;
5233 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005234 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005235 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005236#endif
drh88f474a2006-01-02 20:00:12 +00005237}
5238
5239/*
drh6b9d6dd2008-12-03 19:34:47 +00005240** The following variable, if set to a non-zero value, is interpreted as
5241** the number of seconds since 1970 and is used to set the result of
5242** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005243*/
5244#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005245int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005246#endif
5247
5248/*
drhb7e8ea22010-05-03 14:32:30 +00005249** Find the current time (in Universal Coordinated Time). Write into *piNow
5250** the current time and date as a Julian Day number times 86_400_000. In
5251** other words, write into *piNow the number of milliseconds since the Julian
5252** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5253** proleptic Gregorian calendar.
5254**
5255** On success, return 0. Return 1 if the time and date cannot be found.
5256*/
5257static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5258 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5259#if defined(NO_GETTOD)
5260 time_t t;
5261 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005262 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005263#elif OS_VXWORKS
5264 struct timespec sNow;
5265 clock_gettime(CLOCK_REALTIME, &sNow);
5266 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5267#else
5268 struct timeval sNow;
5269 gettimeofday(&sNow, 0);
5270 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5271#endif
5272
5273#ifdef SQLITE_TEST
5274 if( sqlite3_current_time ){
5275 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5276 }
5277#endif
5278 UNUSED_PARAMETER(NotUsed);
5279 return 0;
5280}
5281
5282/*
drhbbd42a62004-05-22 17:41:58 +00005283** Find the current time (in Universal Coordinated Time). Write the
5284** current time and date as a Julian Day number into *prNow and
5285** return 0. Return 1 if the time and date cannot be found.
5286*/
danielk1977397d65f2008-11-19 11:35:39 +00005287static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005288 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005289 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005290 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005291 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005292 return 0;
5293}
danielk1977b4b47412007-08-17 15:53:36 +00005294
drh6b9d6dd2008-12-03 19:34:47 +00005295/*
5296** We added the xGetLastError() method with the intention of providing
5297** better low-level error messages when operating-system problems come up
5298** during SQLite operation. But so far, none of that has been implemented
5299** in the core. So this routine is never called. For now, it is merely
5300** a place-holder.
5301*/
danielk1977397d65f2008-11-19 11:35:39 +00005302static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5303 UNUSED_PARAMETER(NotUsed);
5304 UNUSED_PARAMETER(NotUsed2);
5305 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005306 return 0;
5307}
5308
drhf2424c52010-04-26 00:04:55 +00005309
5310/*
drh734c9862008-11-28 15:37:20 +00005311************************ End of sqlite3_vfs methods ***************************
5312******************************************************************************/
5313
drh715ff302008-12-03 22:32:44 +00005314/******************************************************************************
5315************************** Begin Proxy Locking ********************************
5316**
5317** Proxy locking is a "uber-locking-method" in this sense: It uses the
5318** other locking methods on secondary lock files. Proxy locking is a
5319** meta-layer over top of the primitive locking implemented above. For
5320** this reason, the division that implements of proxy locking is deferred
5321** until late in the file (here) after all of the other I/O methods have
5322** been defined - so that the primitive locking methods are available
5323** as services to help with the implementation of proxy locking.
5324**
5325****
5326**
5327** The default locking schemes in SQLite use byte-range locks on the
5328** database file to coordinate safe, concurrent access by multiple readers
5329** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5330** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5331** as POSIX read & write locks over fixed set of locations (via fsctl),
5332** on AFP and SMB only exclusive byte-range locks are available via fsctl
5333** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5334** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5335** address in the shared range is taken for a SHARED lock, the entire
5336** shared range is taken for an EXCLUSIVE lock):
5337**
5338** PENDING_BYTE 0x40000000
5339** RESERVED_BYTE 0x40000001
5340** SHARED_RANGE 0x40000002 -> 0x40000200
5341**
5342** This works well on the local file system, but shows a nearly 100x
5343** slowdown in read performance on AFP because the AFP client disables
5344** the read cache when byte-range locks are present. Enabling the read
5345** cache exposes a cache coherency problem that is present on all OS X
5346** supported network file systems. NFS and AFP both observe the
5347** close-to-open semantics for ensuring cache coherency
5348** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5349** address the requirements for concurrent database access by multiple
5350** readers and writers
5351** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5352**
5353** To address the performance and cache coherency issues, proxy file locking
5354** changes the way database access is controlled by limiting access to a
5355** single host at a time and moving file locks off of the database file
5356** and onto a proxy file on the local file system.
5357**
5358**
5359** Using proxy locks
5360** -----------------
5361**
5362** C APIs
5363**
5364** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5365** <proxy_path> | ":auto:");
5366** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5367**
5368**
5369** SQL pragmas
5370**
5371** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5372** PRAGMA [database.]lock_proxy_file
5373**
5374** Specifying ":auto:" means that if there is a conch file with a matching
5375** host ID in it, the proxy path in the conch file will be used, otherwise
5376** a proxy path based on the user's temp dir
5377** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5378** actual proxy file name is generated from the name and path of the
5379** database file. For example:
5380**
5381** For database path "/Users/me/foo.db"
5382** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5383**
5384** Once a lock proxy is configured for a database connection, it can not
5385** be removed, however it may be switched to a different proxy path via
5386** the above APIs (assuming the conch file is not being held by another
5387** connection or process).
5388**
5389**
5390** How proxy locking works
5391** -----------------------
5392**
5393** Proxy file locking relies primarily on two new supporting files:
5394**
5395** * conch file to limit access to the database file to a single host
5396** at a time
5397**
5398** * proxy file to act as a proxy for the advisory locks normally
5399** taken on the database
5400**
5401** The conch file - to use a proxy file, sqlite must first "hold the conch"
5402** by taking an sqlite-style shared lock on the conch file, reading the
5403** contents and comparing the host's unique host ID (see below) and lock
5404** proxy path against the values stored in the conch. The conch file is
5405** stored in the same directory as the database file and the file name
5406** is patterned after the database file name as ".<databasename>-conch".
5407** If the conch file does not exist, or it's contents do not match the
5408** host ID and/or proxy path, then the lock is escalated to an exclusive
5409** lock and the conch file contents is updated with the host ID and proxy
5410** path and the lock is downgraded to a shared lock again. If the conch
5411** is held by another process (with a shared lock), the exclusive lock
5412** will fail and SQLITE_BUSY is returned.
5413**
5414** The proxy file - a single-byte file used for all advisory file locks
5415** normally taken on the database file. This allows for safe sharing
5416** of the database file for multiple readers and writers on the same
5417** host (the conch ensures that they all use the same local lock file).
5418**
drh715ff302008-12-03 22:32:44 +00005419** Requesting the lock proxy does not immediately take the conch, it is
5420** only taken when the first request to lock database file is made.
5421** This matches the semantics of the traditional locking behavior, where
5422** opening a connection to a database file does not take a lock on it.
5423** The shared lock and an open file descriptor are maintained until
5424** the connection to the database is closed.
5425**
5426** The proxy file and the lock file are never deleted so they only need
5427** to be created the first time they are used.
5428**
5429** Configuration options
5430** ---------------------
5431**
5432** SQLITE_PREFER_PROXY_LOCKING
5433**
5434** Database files accessed on non-local file systems are
5435** automatically configured for proxy locking, lock files are
5436** named automatically using the same logic as
5437** PRAGMA lock_proxy_file=":auto:"
5438**
5439** SQLITE_PROXY_DEBUG
5440**
5441** Enables the logging of error messages during host id file
5442** retrieval and creation
5443**
drh715ff302008-12-03 22:32:44 +00005444** LOCKPROXYDIR
5445**
5446** Overrides the default directory used for lock proxy files that
5447** are named automatically via the ":auto:" setting
5448**
5449** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5450**
5451** Permissions to use when creating a directory for storing the
5452** lock proxy files, only used when LOCKPROXYDIR is not set.
5453**
5454**
5455** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5456** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5457** force proxy locking to be used for every database file opened, and 0
5458** will force automatic proxy locking to be disabled for all database
5459** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5460** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5461*/
5462
5463/*
5464** Proxy locking is only available on MacOSX
5465*/
drhd2cb50b2009-01-09 21:41:17 +00005466#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005467
drh715ff302008-12-03 22:32:44 +00005468/*
5469** The proxyLockingContext has the path and file structures for the remote
5470** and local proxy files in it
5471*/
5472typedef struct proxyLockingContext proxyLockingContext;
5473struct proxyLockingContext {
5474 unixFile *conchFile; /* Open conch file */
5475 char *conchFilePath; /* Name of the conch file */
5476 unixFile *lockProxy; /* Open proxy lock file */
5477 char *lockProxyPath; /* Name of the proxy lock file */
5478 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005479 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005480 void *oldLockingContext; /* Original lockingcontext to restore on close */
5481 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5482};
5483
drh7ed97b92010-01-20 13:07:21 +00005484/*
5485** The proxy lock file path for the database at dbPath is written into lPath,
5486** which must point to valid, writable memory large enough for a maxLen length
5487** file path.
drh715ff302008-12-03 22:32:44 +00005488*/
drh715ff302008-12-03 22:32:44 +00005489static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5490 int len;
5491 int dbLen;
5492 int i;
5493
5494#ifdef LOCKPROXYDIR
5495 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5496#else
5497# ifdef _CS_DARWIN_USER_TEMP_DIR
5498 {
drh7ed97b92010-01-20 13:07:21 +00005499 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005500 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5501 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005502 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005503 }
drh7ed97b92010-01-20 13:07:21 +00005504 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005505 }
5506# else
5507 len = strlcpy(lPath, "/tmp/", maxLen);
5508# endif
5509#endif
5510
5511 if( lPath[len-1]!='/' ){
5512 len = strlcat(lPath, "/", maxLen);
5513 }
5514
5515 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005516 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005517 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005518 char c = dbPath[i];
5519 lPath[i+len] = (c=='/')?'_':c;
5520 }
5521 lPath[i+len]='\0';
5522 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005523 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005524 return SQLITE_OK;
5525}
5526
drh7ed97b92010-01-20 13:07:21 +00005527/*
5528 ** Creates the lock file and any missing directories in lockPath
5529 */
5530static int proxyCreateLockPath(const char *lockPath){
5531 int i, len;
5532 char buf[MAXPATHLEN];
5533 int start = 0;
5534
5535 assert(lockPath!=NULL);
5536 /* try to create all the intermediate directories */
5537 len = (int)strlen(lockPath);
5538 buf[0] = lockPath[0];
5539 for( i=1; i<len; i++ ){
5540 if( lockPath[i] == '/' && (i - start > 0) ){
5541 /* only mkdir if leaf dir != "." or "/" or ".." */
5542 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5543 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5544 buf[i]='\0';
5545 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5546 int err=errno;
5547 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005548 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005549 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005550 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005551 return err;
5552 }
5553 }
5554 }
5555 start=i+1;
5556 }
5557 buf[i] = lockPath[i];
5558 }
drh308c2a52010-05-14 11:30:18 +00005559 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005560 return 0;
5561}
5562
drh715ff302008-12-03 22:32:44 +00005563/*
5564** Create a new VFS file descriptor (stored in memory obtained from
5565** sqlite3_malloc) and open the file named "path" in the file descriptor.
5566**
5567** The caller is responsible not only for closing the file descriptor
5568** but also for freeing the memory associated with the file descriptor.
5569*/
drh7ed97b92010-01-20 13:07:21 +00005570static int proxyCreateUnixFile(
5571 const char *path, /* path for the new unixFile */
5572 unixFile **ppFile, /* unixFile created and returned by ref */
5573 int islockfile /* if non zero missing dirs will be created */
5574) {
5575 int fd = -1;
5576 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005577 unixFile *pNew;
5578 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005579 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005580 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005581 int terrno = 0;
5582 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005583
drh7ed97b92010-01-20 13:07:21 +00005584 /* 1. first try to open/create the file
5585 ** 2. if that fails, and this is a lock file (not-conch), try creating
5586 ** the parent directories and then try again.
5587 ** 3. if that fails, try to open the file read-only
5588 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5589 */
5590 pUnused = findReusableFd(path, openFlags);
5591 if( pUnused ){
5592 fd = pUnused->fd;
5593 }else{
5594 pUnused = sqlite3_malloc(sizeof(*pUnused));
5595 if( !pUnused ){
5596 return SQLITE_NOMEM;
5597 }
5598 }
5599 if( fd<0 ){
drh99ab3b12011-03-02 15:09:07 +00005600 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005601 terrno = errno;
5602 if( fd<0 && errno==ENOENT && islockfile ){
5603 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh99ab3b12011-03-02 15:09:07 +00005604 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005605 }
5606 }
5607 }
5608 if( fd<0 ){
5609 openFlags = O_RDONLY;
drh99ab3b12011-03-02 15:09:07 +00005610 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005611 terrno = errno;
5612 }
5613 if( fd<0 ){
5614 if( islockfile ){
5615 return SQLITE_BUSY;
5616 }
5617 switch (terrno) {
5618 case EACCES:
5619 return SQLITE_PERM;
5620 case EIO:
5621 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5622 default:
drh9978c972010-02-23 17:36:32 +00005623 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005624 }
5625 }
5626
5627 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5628 if( pNew==NULL ){
5629 rc = SQLITE_NOMEM;
5630 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005631 }
5632 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005633 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005634 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005635 pUnused->fd = fd;
5636 pUnused->flags = openFlags;
5637 pNew->pUnused = pUnused;
5638
5639 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5640 if( rc==SQLITE_OK ){
5641 *ppFile = pNew;
5642 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005643 }
drh7ed97b92010-01-20 13:07:21 +00005644end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005645 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005646 sqlite3_free(pNew);
5647 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005648 return rc;
5649}
5650
drh7ed97b92010-01-20 13:07:21 +00005651#ifdef SQLITE_TEST
5652/* simulate multiple hosts by creating unique hostid file paths */
5653int sqlite3_hostid_num = 0;
5654#endif
5655
5656#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5657
drh0ab216a2010-07-02 17:10:40 +00005658/* Not always defined in the headers as it ought to be */
5659extern int gethostuuid(uuid_t id, const struct timespec *wait);
5660
drh7ed97b92010-01-20 13:07:21 +00005661/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5662** bytes of writable memory.
5663*/
5664static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005665 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5666 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005667#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5668 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005669 {
5670 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5671 if( gethostuuid(pHostID, &timeout) ){
5672 int err = errno;
5673 if( pError ){
5674 *pError = err;
5675 }
5676 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005677 }
drh7ed97b92010-01-20 13:07:21 +00005678 }
drhe8b0c9b2010-09-25 14:13:17 +00005679#endif
drh7ed97b92010-01-20 13:07:21 +00005680#ifdef SQLITE_TEST
5681 /* simulate multiple hosts by creating unique hostid file paths */
5682 if( sqlite3_hostid_num != 0){
5683 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5684 }
5685#endif
5686
5687 return SQLITE_OK;
5688}
5689
5690/* The conch file contains the header, host id and lock file path
5691 */
5692#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5693#define PROXY_HEADERLEN 1 /* conch file header length */
5694#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5695#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5696
5697/*
5698** Takes an open conch file, copies the contents to a new path and then moves
5699** it back. The newly created file's file descriptor is assigned to the
5700** conch file structure and finally the original conch file descriptor is
5701** closed. Returns zero if successful.
5702*/
5703static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5704 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5705 unixFile *conchFile = pCtx->conchFile;
5706 char tPath[MAXPATHLEN];
5707 char buf[PROXY_MAXCONCHLEN];
5708 char *cPath = pCtx->conchFilePath;
5709 size_t readLen = 0;
5710 size_t pathLen = 0;
5711 char errmsg[64] = "";
5712 int fd = -1;
5713 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005714 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005715
5716 /* create a new path by replace the trailing '-conch' with '-break' */
5717 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5718 if( pathLen>MAXPATHLEN || pathLen<6 ||
5719 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005720 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005721 goto end_breaklock;
5722 }
5723 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005724 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005725 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005726 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005727 goto end_breaklock;
5728 }
5729 /* write it out to the temporary break file */
drh99ab3b12011-03-02 15:09:07 +00005730 fd = osOpen(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005731 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005732 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005733 goto end_breaklock;
5734 }
drhe562be52011-03-02 18:01:10 +00005735 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005736 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005737 goto end_breaklock;
5738 }
5739 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005740 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005741 goto end_breaklock;
5742 }
5743 rc = 0;
5744 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005745 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005746 conchFile->h = fd;
5747 conchFile->openFlags = O_RDWR | O_CREAT;
5748
5749end_breaklock:
5750 if( rc ){
5751 if( fd>=0 ){
5752 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005753 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005754 }
5755 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5756 }
5757 return rc;
5758}
5759
5760/* Take the requested lock on the conch file and break a stale lock if the
5761** host id matches.
5762*/
5763static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5764 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5765 unixFile *conchFile = pCtx->conchFile;
5766 int rc = SQLITE_OK;
5767 int nTries = 0;
5768 struct timespec conchModTime;
5769
5770 do {
5771 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5772 nTries ++;
5773 if( rc==SQLITE_BUSY ){
5774 /* If the lock failed (busy):
5775 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5776 * 2nd try: fail if the mod time changed or host id is different, wait
5777 * 10 sec and try again
5778 * 3rd try: break the lock unless the mod time has changed.
5779 */
5780 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005781 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005782 pFile->lastErrno = errno;
5783 return SQLITE_IOERR_LOCK;
5784 }
5785
5786 if( nTries==1 ){
5787 conchModTime = buf.st_mtimespec;
5788 usleep(500000); /* wait 0.5 sec and try the lock again*/
5789 continue;
5790 }
5791
5792 assert( nTries>1 );
5793 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5794 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5795 return SQLITE_BUSY;
5796 }
5797
5798 if( nTries==2 ){
5799 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005800 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005801 if( len<0 ){
5802 pFile->lastErrno = errno;
5803 return SQLITE_IOERR_LOCK;
5804 }
5805 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5806 /* don't break the lock if the host id doesn't match */
5807 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5808 return SQLITE_BUSY;
5809 }
5810 }else{
5811 /* don't break the lock on short read or a version mismatch */
5812 return SQLITE_BUSY;
5813 }
5814 usleep(10000000); /* wait 10 sec and try the lock again */
5815 continue;
5816 }
5817
5818 assert( nTries==3 );
5819 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5820 rc = SQLITE_OK;
5821 if( lockType==EXCLUSIVE_LOCK ){
5822 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5823 }
5824 if( !rc ){
5825 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5826 }
5827 }
5828 }
5829 } while( rc==SQLITE_BUSY && nTries<3 );
5830
5831 return rc;
5832}
5833
5834/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005835** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5836** lockPath means that the lockPath in the conch file will be used if the
5837** host IDs match, or a new lock path will be generated automatically
5838** and written to the conch file.
5839*/
5840static int proxyTakeConch(unixFile *pFile){
5841 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5842
drh7ed97b92010-01-20 13:07:21 +00005843 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005844 return SQLITE_OK;
5845 }else{
5846 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005847 uuid_t myHostID;
5848 int pError = 0;
5849 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005850 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005851 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005852 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005853 int createConch = 0;
5854 int hostIdMatch = 0;
5855 int readLen = 0;
5856 int tryOldLockPath = 0;
5857 int forceNewLockPath = 0;
5858
drh308c2a52010-05-14 11:30:18 +00005859 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5860 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005861
drh7ed97b92010-01-20 13:07:21 +00005862 rc = proxyGetHostID(myHostID, &pError);
5863 if( (rc&0xff)==SQLITE_IOERR ){
5864 pFile->lastErrno = pError;
5865 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005866 }
drh7ed97b92010-01-20 13:07:21 +00005867 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005868 if( rc!=SQLITE_OK ){
5869 goto end_takeconch;
5870 }
drh7ed97b92010-01-20 13:07:21 +00005871 /* read the existing conch file */
5872 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5873 if( readLen<0 ){
5874 /* I/O error: lastErrno set by seekAndRead */
5875 pFile->lastErrno = conchFile->lastErrno;
5876 rc = SQLITE_IOERR_READ;
5877 goto end_takeconch;
5878 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5879 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5880 /* a short read or version format mismatch means we need to create a new
5881 ** conch file.
5882 */
5883 createConch = 1;
5884 }
5885 /* if the host id matches and the lock path already exists in the conch
5886 ** we'll try to use the path there, if we can't open that path, we'll
5887 ** retry with a new auto-generated path
5888 */
5889 do { /* in case we need to try again for an :auto: named lock file */
5890
5891 if( !createConch && !forceNewLockPath ){
5892 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5893 PROXY_HOSTIDLEN);
5894 /* if the conch has data compare the contents */
5895 if( !pCtx->lockProxyPath ){
5896 /* for auto-named local lock file, just check the host ID and we'll
5897 ** use the local lock file path that's already in there
5898 */
5899 if( hostIdMatch ){
5900 size_t pathLen = (readLen - PROXY_PATHINDEX);
5901
5902 if( pathLen>=MAXPATHLEN ){
5903 pathLen=MAXPATHLEN-1;
5904 }
5905 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5906 lockPath[pathLen] = 0;
5907 tempLockPath = lockPath;
5908 tryOldLockPath = 1;
5909 /* create a copy of the lock path if the conch is taken */
5910 goto end_takeconch;
5911 }
5912 }else if( hostIdMatch
5913 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5914 readLen-PROXY_PATHINDEX)
5915 ){
5916 /* conch host and lock path match */
5917 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005918 }
drh7ed97b92010-01-20 13:07:21 +00005919 }
5920
5921 /* if the conch isn't writable and doesn't match, we can't take it */
5922 if( (conchFile->openFlags&O_RDWR) == 0 ){
5923 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005924 goto end_takeconch;
5925 }
drh7ed97b92010-01-20 13:07:21 +00005926
5927 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005928 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005929 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5930 tempLockPath = lockPath;
5931 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005932 }
drh7ed97b92010-01-20 13:07:21 +00005933
5934 /* update conch with host and path (this will fail if other process
5935 ** has a shared lock already), if the host id matches, use the big
5936 ** stick.
drh715ff302008-12-03 22:32:44 +00005937 */
drh7ed97b92010-01-20 13:07:21 +00005938 futimes(conchFile->h, NULL);
5939 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005940 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005941 /* We are trying for an exclusive lock but another thread in this
5942 ** same process is still holding a shared lock. */
5943 rc = SQLITE_BUSY;
5944 } else {
5945 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005946 }
drh715ff302008-12-03 22:32:44 +00005947 }else{
drh7ed97b92010-01-20 13:07:21 +00005948 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005949 }
drh7ed97b92010-01-20 13:07:21 +00005950 if( rc==SQLITE_OK ){
5951 char writeBuffer[PROXY_MAXCONCHLEN];
5952 int writeSize = 0;
5953
5954 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5955 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5956 if( pCtx->lockProxyPath!=NULL ){
5957 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5958 }else{
5959 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5960 }
5961 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00005962 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00005963 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5964 fsync(conchFile->h);
5965 /* If we created a new conch file (not just updated the contents of a
5966 ** valid conch file), try to match the permissions of the database
5967 */
5968 if( rc==SQLITE_OK && createConch ){
5969 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005970 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00005971 if( err==0 ){
5972 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5973 S_IROTH|S_IWOTH);
5974 /* try to match the database file R/W permissions, ignore failure */
5975#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00005976 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00005977#else
drhff812312011-02-23 13:33:46 +00005978 do{
drhe562be52011-03-02 18:01:10 +00005979 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00005980 }while( rc==(-1) && errno==EINTR );
5981 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00005982 int code = errno;
5983 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5984 cmode, code, strerror(code));
5985 } else {
5986 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5987 }
5988 }else{
5989 int code = errno;
5990 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5991 err, code, strerror(code));
5992#endif
5993 }
drh715ff302008-12-03 22:32:44 +00005994 }
5995 }
drh7ed97b92010-01-20 13:07:21 +00005996 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5997
5998 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005999 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006000 if( rc==SQLITE_OK && pFile->openFlags ){
6001 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006002 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006003 }
6004 pFile->h = -1;
drh99ab3b12011-03-02 15:09:07 +00006005 int fd = osOpen(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006006 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006007 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006008 if( fd>=0 ){
6009 pFile->h = fd;
6010 }else{
drh9978c972010-02-23 17:36:32 +00006011 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006012 during locking */
6013 }
6014 }
6015 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6016 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6017 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6018 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6019 /* we couldn't create the proxy lock file with the old lock file path
6020 ** so try again via auto-naming
6021 */
6022 forceNewLockPath = 1;
6023 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006024 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006025 }
6026 }
6027 if( rc==SQLITE_OK ){
6028 /* Need to make a copy of path if we extracted the value
6029 ** from the conch file or the path was allocated on the stack
6030 */
6031 if( tempLockPath ){
6032 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6033 if( !pCtx->lockProxyPath ){
6034 rc = SQLITE_NOMEM;
6035 }
6036 }
6037 }
6038 if( rc==SQLITE_OK ){
6039 pCtx->conchHeld = 1;
6040
6041 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6042 afpLockingContext *afpCtx;
6043 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6044 afpCtx->dbPath = pCtx->lockProxyPath;
6045 }
6046 } else {
6047 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6048 }
drh308c2a52010-05-14 11:30:18 +00006049 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6050 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006051 return rc;
drh308c2a52010-05-14 11:30:18 +00006052 } while (1); /* in case we need to retry the :auto: lock file -
6053 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006054 }
6055}
6056
6057/*
6058** If pFile holds a lock on a conch file, then release that lock.
6059*/
6060static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006061 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006062 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6063 unixFile *conchFile; /* Name of the conch file */
6064
6065 pCtx = (proxyLockingContext *)pFile->lockingContext;
6066 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006067 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006068 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006069 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006070 if( pCtx->conchHeld>0 ){
6071 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6072 }
drh715ff302008-12-03 22:32:44 +00006073 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006074 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6075 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006076 return rc;
6077}
6078
6079/*
6080** Given the name of a database file, compute the name of its conch file.
6081** Store the conch filename in memory obtained from sqlite3_malloc().
6082** Make *pConchPath point to the new name. Return SQLITE_OK on success
6083** or SQLITE_NOMEM if unable to obtain memory.
6084**
6085** The caller is responsible for ensuring that the allocated memory
6086** space is eventually freed.
6087**
6088** *pConchPath is set to NULL if a memory allocation error occurs.
6089*/
6090static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6091 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006092 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006093 char *conchPath; /* buffer in which to construct conch name */
6094
6095 /* Allocate space for the conch filename and initialize the name to
6096 ** the name of the original database file. */
6097 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6098 if( conchPath==0 ){
6099 return SQLITE_NOMEM;
6100 }
6101 memcpy(conchPath, dbPath, len+1);
6102
6103 /* now insert a "." before the last / character */
6104 for( i=(len-1); i>=0; i-- ){
6105 if( conchPath[i]=='/' ){
6106 i++;
6107 break;
6108 }
6109 }
6110 conchPath[i]='.';
6111 while ( i<len ){
6112 conchPath[i+1]=dbPath[i];
6113 i++;
6114 }
6115
6116 /* append the "-conch" suffix to the file */
6117 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006118 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006119
6120 return SQLITE_OK;
6121}
6122
6123
6124/* Takes a fully configured proxy locking-style unix file and switches
6125** the local lock file path
6126*/
6127static int switchLockProxyPath(unixFile *pFile, const char *path) {
6128 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6129 char *oldPath = pCtx->lockProxyPath;
6130 int rc = SQLITE_OK;
6131
drh308c2a52010-05-14 11:30:18 +00006132 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006133 return SQLITE_BUSY;
6134 }
6135
6136 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6137 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6138 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6139 return SQLITE_OK;
6140 }else{
6141 unixFile *lockProxy = pCtx->lockProxy;
6142 pCtx->lockProxy=NULL;
6143 pCtx->conchHeld = 0;
6144 if( lockProxy!=NULL ){
6145 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6146 if( rc ) return rc;
6147 sqlite3_free(lockProxy);
6148 }
6149 sqlite3_free(oldPath);
6150 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6151 }
6152
6153 return rc;
6154}
6155
6156/*
6157** pFile is a file that has been opened by a prior xOpen call. dbPath
6158** is a string buffer at least MAXPATHLEN+1 characters in size.
6159**
6160** This routine find the filename associated with pFile and writes it
6161** int dbPath.
6162*/
6163static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006164#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006165 if( pFile->pMethod == &afpIoMethods ){
6166 /* afp style keeps a reference to the db path in the filePath field
6167 ** of the struct */
drhea678832008-12-10 19:26:22 +00006168 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006169 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6170 } else
drh715ff302008-12-03 22:32:44 +00006171#endif
6172 if( pFile->pMethod == &dotlockIoMethods ){
6173 /* dot lock style uses the locking context to store the dot lock
6174 ** file path */
6175 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6176 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6177 }else{
6178 /* all other styles use the locking context to store the db file path */
6179 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006180 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006181 }
6182 return SQLITE_OK;
6183}
6184
6185/*
6186** Takes an already filled in unix file and alters it so all file locking
6187** will be performed on the local proxy lock file. The following fields
6188** are preserved in the locking context so that they can be restored and
6189** the unix structure properly cleaned up at close time:
6190** ->lockingContext
6191** ->pMethod
6192*/
6193static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6194 proxyLockingContext *pCtx;
6195 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6196 char *lockPath=NULL;
6197 int rc = SQLITE_OK;
6198
drh308c2a52010-05-14 11:30:18 +00006199 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006200 return SQLITE_BUSY;
6201 }
6202 proxyGetDbPathForUnixFile(pFile, dbPath);
6203 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6204 lockPath=NULL;
6205 }else{
6206 lockPath=(char *)path;
6207 }
6208
drh308c2a52010-05-14 11:30:18 +00006209 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6210 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006211
6212 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6213 if( pCtx==0 ){
6214 return SQLITE_NOMEM;
6215 }
6216 memset(pCtx, 0, sizeof(*pCtx));
6217
6218 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6219 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006220 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6221 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6222 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6223 ** (c) the file system is read-only, then enable no-locking access.
6224 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6225 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6226 */
6227 struct statfs fsInfo;
6228 struct stat conchInfo;
6229 int goLockless = 0;
6230
drh99ab3b12011-03-02 15:09:07 +00006231 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006232 int err = errno;
6233 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6234 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6235 }
6236 }
6237 if( goLockless ){
6238 pCtx->conchHeld = -1; /* read only FS/ lockless */
6239 rc = SQLITE_OK;
6240 }
6241 }
drh715ff302008-12-03 22:32:44 +00006242 }
6243 if( rc==SQLITE_OK && lockPath ){
6244 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6245 }
6246
6247 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006248 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6249 if( pCtx->dbPath==NULL ){
6250 rc = SQLITE_NOMEM;
6251 }
6252 }
6253 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006254 /* all memory is allocated, proxys are created and assigned,
6255 ** switch the locking context and pMethod then return.
6256 */
drh715ff302008-12-03 22:32:44 +00006257 pCtx->oldLockingContext = pFile->lockingContext;
6258 pFile->lockingContext = pCtx;
6259 pCtx->pOldMethod = pFile->pMethod;
6260 pFile->pMethod = &proxyIoMethods;
6261 }else{
6262 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006263 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006264 sqlite3_free(pCtx->conchFile);
6265 }
drhd56b1212010-08-11 06:14:15 +00006266 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006267 sqlite3_free(pCtx->conchFilePath);
6268 sqlite3_free(pCtx);
6269 }
drh308c2a52010-05-14 11:30:18 +00006270 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6271 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006272 return rc;
6273}
6274
6275
6276/*
6277** This routine handles sqlite3_file_control() calls that are specific
6278** to proxy locking.
6279*/
6280static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6281 switch( op ){
6282 case SQLITE_GET_LOCKPROXYFILE: {
6283 unixFile *pFile = (unixFile*)id;
6284 if( pFile->pMethod == &proxyIoMethods ){
6285 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6286 proxyTakeConch(pFile);
6287 if( pCtx->lockProxyPath ){
6288 *(const char **)pArg = pCtx->lockProxyPath;
6289 }else{
6290 *(const char **)pArg = ":auto: (not held)";
6291 }
6292 } else {
6293 *(const char **)pArg = NULL;
6294 }
6295 return SQLITE_OK;
6296 }
6297 case SQLITE_SET_LOCKPROXYFILE: {
6298 unixFile *pFile = (unixFile*)id;
6299 int rc = SQLITE_OK;
6300 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6301 if( pArg==NULL || (const char *)pArg==0 ){
6302 if( isProxyStyle ){
6303 /* turn off proxy locking - not supported */
6304 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6305 }else{
6306 /* turn off proxy locking - already off - NOOP */
6307 rc = SQLITE_OK;
6308 }
6309 }else{
6310 const char *proxyPath = (const char *)pArg;
6311 if( isProxyStyle ){
6312 proxyLockingContext *pCtx =
6313 (proxyLockingContext*)pFile->lockingContext;
6314 if( !strcmp(pArg, ":auto:")
6315 || (pCtx->lockProxyPath &&
6316 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6317 ){
6318 rc = SQLITE_OK;
6319 }else{
6320 rc = switchLockProxyPath(pFile, proxyPath);
6321 }
6322 }else{
6323 /* turn on proxy file locking */
6324 rc = proxyTransformUnixFile(pFile, proxyPath);
6325 }
6326 }
6327 return rc;
6328 }
6329 default: {
6330 assert( 0 ); /* The call assures that only valid opcodes are sent */
6331 }
6332 }
6333 /*NOTREACHED*/
6334 return SQLITE_ERROR;
6335}
6336
6337/*
6338** Within this division (the proxying locking implementation) the procedures
6339** above this point are all utilities. The lock-related methods of the
6340** proxy-locking sqlite3_io_method object follow.
6341*/
6342
6343
6344/*
6345** This routine checks if there is a RESERVED lock held on the specified
6346** file by this or any other process. If such a lock is held, set *pResOut
6347** to a non-zero value otherwise *pResOut is set to zero. The return value
6348** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6349*/
6350static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6351 unixFile *pFile = (unixFile*)id;
6352 int rc = proxyTakeConch(pFile);
6353 if( rc==SQLITE_OK ){
6354 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006355 if( pCtx->conchHeld>0 ){
6356 unixFile *proxy = pCtx->lockProxy;
6357 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6358 }else{ /* conchHeld < 0 is lockless */
6359 pResOut=0;
6360 }
drh715ff302008-12-03 22:32:44 +00006361 }
6362 return rc;
6363}
6364
6365/*
drh308c2a52010-05-14 11:30:18 +00006366** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006367** of the following:
6368**
6369** (1) SHARED_LOCK
6370** (2) RESERVED_LOCK
6371** (3) PENDING_LOCK
6372** (4) EXCLUSIVE_LOCK
6373**
6374** Sometimes when requesting one lock state, additional lock states
6375** are inserted in between. The locking might fail on one of the later
6376** transitions leaving the lock state different from what it started but
6377** still short of its goal. The following chart shows the allowed
6378** transitions and the inserted intermediate states:
6379**
6380** UNLOCKED -> SHARED
6381** SHARED -> RESERVED
6382** SHARED -> (PENDING) -> EXCLUSIVE
6383** RESERVED -> (PENDING) -> EXCLUSIVE
6384** PENDING -> EXCLUSIVE
6385**
6386** This routine will only increase a lock. Use the sqlite3OsUnlock()
6387** routine to lower a locking level.
6388*/
drh308c2a52010-05-14 11:30:18 +00006389static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006390 unixFile *pFile = (unixFile*)id;
6391 int rc = proxyTakeConch(pFile);
6392 if( rc==SQLITE_OK ){
6393 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006394 if( pCtx->conchHeld>0 ){
6395 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006396 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6397 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006398 }else{
6399 /* conchHeld < 0 is lockless */
6400 }
drh715ff302008-12-03 22:32:44 +00006401 }
6402 return rc;
6403}
6404
6405
6406/*
drh308c2a52010-05-14 11:30:18 +00006407** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006408** must be either NO_LOCK or SHARED_LOCK.
6409**
6410** If the locking level of the file descriptor is already at or below
6411** the requested locking level, this routine is a no-op.
6412*/
drh308c2a52010-05-14 11:30:18 +00006413static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006414 unixFile *pFile = (unixFile*)id;
6415 int rc = proxyTakeConch(pFile);
6416 if( rc==SQLITE_OK ){
6417 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006418 if( pCtx->conchHeld>0 ){
6419 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006420 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6421 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006422 }else{
6423 /* conchHeld < 0 is lockless */
6424 }
drh715ff302008-12-03 22:32:44 +00006425 }
6426 return rc;
6427}
6428
6429/*
6430** Close a file that uses proxy locks.
6431*/
6432static int proxyClose(sqlite3_file *id) {
6433 if( id ){
6434 unixFile *pFile = (unixFile*)id;
6435 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6436 unixFile *lockProxy = pCtx->lockProxy;
6437 unixFile *conchFile = pCtx->conchFile;
6438 int rc = SQLITE_OK;
6439
6440 if( lockProxy ){
6441 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6442 if( rc ) return rc;
6443 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6444 if( rc ) return rc;
6445 sqlite3_free(lockProxy);
6446 pCtx->lockProxy = 0;
6447 }
6448 if( conchFile ){
6449 if( pCtx->conchHeld ){
6450 rc = proxyReleaseConch(pFile);
6451 if( rc ) return rc;
6452 }
6453 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6454 if( rc ) return rc;
6455 sqlite3_free(conchFile);
6456 }
drhd56b1212010-08-11 06:14:15 +00006457 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006458 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006459 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006460 /* restore the original locking context and pMethod then close it */
6461 pFile->lockingContext = pCtx->oldLockingContext;
6462 pFile->pMethod = pCtx->pOldMethod;
6463 sqlite3_free(pCtx);
6464 return pFile->pMethod->xClose(id);
6465 }
6466 return SQLITE_OK;
6467}
6468
6469
6470
drhd2cb50b2009-01-09 21:41:17 +00006471#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006472/*
6473** The proxy locking style is intended for use with AFP filesystems.
6474** And since AFP is only supported on MacOSX, the proxy locking is also
6475** restricted to MacOSX.
6476**
6477**
6478******************* End of the proxy lock implementation **********************
6479******************************************************************************/
6480
drh734c9862008-11-28 15:37:20 +00006481/*
danielk1977e339d652008-06-28 11:23:00 +00006482** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006483**
6484** This routine registers all VFS implementations for unix-like operating
6485** systems. This routine, and the sqlite3_os_end() routine that follows,
6486** should be the only routines in this file that are visible from other
6487** files.
drh6b9d6dd2008-12-03 19:34:47 +00006488**
6489** This routine is called once during SQLite initialization and by a
6490** single thread. The memory allocation and mutex subsystems have not
6491** necessarily been initialized when this routine is called, and so they
6492** should not be used.
drh153c62c2007-08-24 03:51:33 +00006493*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006494int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006495 /*
6496 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006497 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6498 ** to the "finder" function. (pAppData is a pointer to a pointer because
6499 ** silly C90 rules prohibit a void* from being cast to a function pointer
6500 ** and so we have to go through the intermediate pointer to avoid problems
6501 ** when compiling with -pedantic-errors on GCC.)
6502 **
6503 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006504 ** finder-function. The finder-function returns a pointer to the
6505 ** sqlite_io_methods object that implements the desired locking
6506 ** behaviors. See the division above that contains the IOMETHODS
6507 ** macro for addition information on finder-functions.
6508 **
6509 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6510 ** object. But the "autolockIoFinder" available on MacOSX does a little
6511 ** more than that; it looks at the filesystem type that hosts the
6512 ** database file and tries to choose an locking method appropriate for
6513 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006514 */
drh7708e972008-11-29 00:56:52 +00006515 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006516 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006517 sizeof(unixFile), /* szOsFile */ \
6518 MAX_PATHNAME, /* mxPathname */ \
6519 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006520 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006521 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006522 unixOpen, /* xOpen */ \
6523 unixDelete, /* xDelete */ \
6524 unixAccess, /* xAccess */ \
6525 unixFullPathname, /* xFullPathname */ \
6526 unixDlOpen, /* xDlOpen */ \
6527 unixDlError, /* xDlError */ \
6528 unixDlSym, /* xDlSym */ \
6529 unixDlClose, /* xDlClose */ \
6530 unixRandomness, /* xRandomness */ \
6531 unixSleep, /* xSleep */ \
6532 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006533 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006534 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006535 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006536 unixGetSystemCall, /* xGetSystemCall */ \
6537 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006538 }
6539
drh6b9d6dd2008-12-03 19:34:47 +00006540 /*
6541 ** All default VFSes for unix are contained in the following array.
6542 **
6543 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6544 ** by the SQLite core when the VFS is registered. So the following
6545 ** array cannot be const.
6546 */
danielk1977e339d652008-06-28 11:23:00 +00006547 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006548#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006549 UNIXVFS("unix", autolockIoFinder ),
6550#else
6551 UNIXVFS("unix", posixIoFinder ),
6552#endif
6553 UNIXVFS("unix-none", nolockIoFinder ),
6554 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006555#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006556 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006557#endif
6558#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006559 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006560#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006561 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006562#endif
chw78a13182009-04-07 05:35:03 +00006563#endif
drhd2cb50b2009-01-09 21:41:17 +00006564#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006565 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006566 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006567 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006568#endif
drh153c62c2007-08-24 03:51:33 +00006569 };
drh6b9d6dd2008-12-03 19:34:47 +00006570 unsigned int i; /* Loop counter */
6571
6572 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006573 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006574 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006575 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006576 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006577}
danielk1977e339d652008-06-28 11:23:00 +00006578
6579/*
drh6b9d6dd2008-12-03 19:34:47 +00006580** Shutdown the operating system interface.
6581**
6582** Some operating systems might need to do some cleanup in this routine,
6583** to release dynamically allocated objects. But not on unix.
6584** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006585*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006586int sqlite3_os_end(void){
6587 return SQLITE_OK;
6588}
drhdce8bdb2007-08-16 13:01:44 +00006589
danielk197729bafea2008-06-26 10:41:19 +00006590#endif /* SQLITE_OS_UNIX */