blob: 246a2d57769319c4a709a8603dd1e48f4adc9e84 [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 */
drha7e61d82011-03-12 17:02:57 +0000209 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000210 int lastErrno; /* The unix errno from last I/O error */
211 void *lockingContext; /* Locking style specific state */
212 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000213 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/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
250
251/*
drh198bf392006-01-06 21:52:49 +0000252** Include code that is common to all os_*.c files
253*/
254#include "os_common.h"
255
256/*
drh0ccebe72005-06-07 22:22:50 +0000257** Define various macros that are missing from some systems.
258*/
drhbbd42a62004-05-22 17:41:58 +0000259#ifndef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifdef SQLITE_DISABLE_LFS
263# undef O_LARGEFILE
264# define O_LARGEFILE 0
265#endif
266#ifndef O_NOFOLLOW
267# define O_NOFOLLOW 0
268#endif
269#ifndef O_BINARY
270# define O_BINARY 0
271#endif
272
273/*
drh2b4b5962005-06-15 17:47:55 +0000274** The threadid macro resolves to the thread-id or to 0. Used for
275** testing and debugging only.
276*/
drhd677b3d2007-08-20 22:48:41 +0000277#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000278#define threadid pthread_self()
279#else
280#define threadid 0
281#endif
282
drh99ab3b12011-03-02 15:09:07 +0000283/*
284** Many system calls are accessed through pointer-to-functions so that
285** they may be overridden at runtime to facilitate fault injection during
286** testing and sandboxing. The following array holds the names and pointers
287** to all overrideable system calls.
288*/
289static struct unix_syscall {
290 const char *zName; /* Name of the sytem call */
291 void *pCurrent; /* Current value of the system call */
292 void *pDefault; /* Default value */
293} aSyscall[] = {
294 { "open", (void*)open, 0 },
295#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
296
297 { "close", (void*)close, 0 },
298#define osClose ((int(*)(int))aSyscall[1].pCurrent)
299
300 { "access", (void*)access, 0 },
301#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
302
303 { "getcwd", (void*)getcwd, 0 },
304#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
305
306 { "stat", (void*)stat, 0 },
307#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
308
309/*
310** The DJGPP compiler environment looks mostly like Unix, but it
311** lacks the fcntl() system call. So redefine fcntl() to be something
312** that always succeeds. This means that locking does not occur under
313** DJGPP. But it is DOS - what did you expect?
314*/
315#ifdef __DJGPP__
316 { "fstat", 0, 0 },
317#define osFstat(a,b,c) 0
318#else
319 { "fstat", (void*)fstat, 0 },
320#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
321#endif
322
323 { "ftruncate", (void*)ftruncate, 0 },
324#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
325
drhe562be52011-03-02 18:01:10 +0000326 { "fcntl", (void*)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000327#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000328
329 { "read", (void*)read, 0 },
330#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
331
332#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
333 { "pread", (void*)pread, 0 },
334#else
335 { "pread", (void*)0, 0 },
336#endif
337#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
338
339#if defined(USE_PREAD64)
340 { "pread64", (void*)pread64, 0 },
341#else
342 { "pread64", (void*)0, 0 },
343#endif
344#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
345
346 { "write", (void*)write, 0 },
347#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
348
349#if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
350 { "pwrite", (void*)pwrite, 0 },
351#else
352 { "pwrite", (void*)0, 0 },
353#endif
354#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
355 aSyscall[12].pCurrent)
356
357#if defined(USE_PREAD64)
358 { "pwrite64", (void*)pwrite64, 0 },
359#else
360 { "pwrite64", (void*)0, 0 },
361#endif
362#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
363 aSyscall[13].pCurrent)
364
365 { "fchmod", (void*)fchmod, 0 },
366#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
367
368#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
369 { "fallocate", (void*)posix_fallocate, 0 },
370#else
371 { "fallocate", (void*)0, 0 },
372#endif
373#define osFallocate ((int(*)(int,off_t,off_t)aSyscall[15].pCurrent)
374
375}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000376
377/*
378** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000379** "unix" VFSes. Return SQLITE_OK opon successfully updating the
380** system call pointer, or SQLITE_NOTFOUND if there is no configurable
381** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000382*/
383static int unixSetSystemCall(
384 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
385 const char *zName, /* Name of system call to override */
386 void *pNewFunc /* Pointer to new system call value */
387){
388 int i;
drh1df30962011-03-02 19:06:42 +0000389 int rc = SQLITE_NOTFOUND;
drh99ab3b12011-03-02 15:09:07 +0000390 if( zName==0 ){
391 /* If no zName is given, restore all system calls to their default
392 ** settings and return NULL
393 */
394 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
395 if( aSyscall[i].pDefault ){
396 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh1df30962011-03-02 19:06:42 +0000397 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000398 }
399 }
400 }else{
401 /* If zName is specified, operate on only the one system call
402 ** specified.
403 */
404 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
405 if( strcmp(zName, aSyscall[i].zName)==0 ){
406 if( aSyscall[i].pDefault==0 ){
407 aSyscall[i].pDefault = aSyscall[i].pCurrent;
408 }
drh1df30962011-03-02 19:06:42 +0000409 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000410 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
411 aSyscall[i].pCurrent = pNewFunc;
412 break;
413 }
414 }
415 }
416 return rc;
417}
418
drh1df30962011-03-02 19:06:42 +0000419/*
420** Return the value of a system call. Return NULL if zName is not a
421** recognized system call name. NULL is also returned if the system call
422** is currently undefined.
423*/
424static void *unixGetSystemCall(sqlite3_vfs *pNotUsed, const char *zName){
425 int i;
426 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
427 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
428 }
429 return 0;
430}
431
432/*
433** Return the name of the first system call after zName. If zName==NULL
434** then return the name of the first system call. Return NULL if zName
435** is the last system call or if zName is not the name of a valid
436** system call.
437*/
438static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
439 int i;
440 if( zName==0 ){
441 i = -1;
442 }else{
443 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0])-1; i++){
444 if( strcmp(zName, aSyscall[0].zName)==0 ) break;
445 }
446 }
447 for(i++; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
448 if( aSyscall[0].pCurrent!=0 ) return aSyscall[0].zName;
449 }
450 return 0;
451}
452
drhad4f1e52011-03-04 15:43:57 +0000453/*
454** Retry open() calls that fail due to EINTR
455*/
456static int robust_open(const char *z, int f, int m){
457 int rc;
458 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
459 return rc;
460}
danielk197713adf8a2004-06-03 16:08:41 +0000461
drh107886a2008-11-21 22:21:50 +0000462/*
dan9359c7b2009-08-21 08:29:10 +0000463** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000464** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000465** vxworksFileId objects used by this file, all of which may be
466** shared by multiple threads.
467**
468** Function unixMutexHeld() is used to assert() that the global mutex
469** is held when required. This function is only used as part of assert()
470** statements. e.g.
471**
472** unixEnterMutex()
473** assert( unixMutexHeld() );
474** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000475*/
476static void unixEnterMutex(void){
477 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
478}
479static void unixLeaveMutex(void){
480 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
481}
dan9359c7b2009-08-21 08:29:10 +0000482#ifdef SQLITE_DEBUG
483static int unixMutexHeld(void) {
484 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
485}
486#endif
drh107886a2008-11-21 22:21:50 +0000487
drh734c9862008-11-28 15:37:20 +0000488
489#ifdef SQLITE_DEBUG
490/*
491** Helper function for printing out trace information from debugging
492** binaries. This returns the string represetation of the supplied
493** integer lock-type.
494*/
drh308c2a52010-05-14 11:30:18 +0000495static const char *azFileLock(int eFileLock){
496 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000497 case NO_LOCK: return "NONE";
498 case SHARED_LOCK: return "SHARED";
499 case RESERVED_LOCK: return "RESERVED";
500 case PENDING_LOCK: return "PENDING";
501 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000502 }
503 return "ERROR";
504}
505#endif
506
507#ifdef SQLITE_LOCK_TRACE
508/*
509** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000510**
drh734c9862008-11-28 15:37:20 +0000511** This routine is used for troubleshooting locks on multithreaded
512** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
513** command-line option on the compiler. This code is normally
514** turned off.
515*/
516static int lockTrace(int fd, int op, struct flock *p){
517 char *zOpName, *zType;
518 int s;
519 int savedErrno;
520 if( op==F_GETLK ){
521 zOpName = "GETLK";
522 }else if( op==F_SETLK ){
523 zOpName = "SETLK";
524 }else{
drh99ab3b12011-03-02 15:09:07 +0000525 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000526 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
527 return s;
528 }
529 if( p->l_type==F_RDLCK ){
530 zType = "RDLCK";
531 }else if( p->l_type==F_WRLCK ){
532 zType = "WRLCK";
533 }else if( p->l_type==F_UNLCK ){
534 zType = "UNLCK";
535 }else{
536 assert( 0 );
537 }
538 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000539 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000540 savedErrno = errno;
541 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
542 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
543 (int)p->l_pid, s);
544 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
545 struct flock l2;
546 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000547 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000548 if( l2.l_type==F_RDLCK ){
549 zType = "RDLCK";
550 }else if( l2.l_type==F_WRLCK ){
551 zType = "WRLCK";
552 }else if( l2.l_type==F_UNLCK ){
553 zType = "UNLCK";
554 }else{
555 assert( 0 );
556 }
557 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
558 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
559 }
560 errno = savedErrno;
561 return s;
562}
drh99ab3b12011-03-02 15:09:07 +0000563#undef osFcntl
564#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000565#endif /* SQLITE_LOCK_TRACE */
566
drhff812312011-02-23 13:33:46 +0000567/*
568** Retry ftruncate() calls that fail due to EINTR
569*/
drhff812312011-02-23 13:33:46 +0000570static int robust_ftruncate(int h, sqlite3_int64 sz){
571 int rc;
drh99ab3b12011-03-02 15:09:07 +0000572 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000573 return rc;
574}
drh734c9862008-11-28 15:37:20 +0000575
576/*
577** This routine translates a standard POSIX errno code into something
578** useful to the clients of the sqlite3 functions. Specifically, it is
579** intended to translate a variety of "try again" errors into SQLITE_BUSY
580** and a variety of "please close the file descriptor NOW" errors into
581** SQLITE_IOERR
582**
583** Errors during initialization of locks, or file system support for locks,
584** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
585*/
586static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
587 switch (posixError) {
588 case 0:
589 return SQLITE_OK;
590
591 case EAGAIN:
592 case ETIMEDOUT:
593 case EBUSY:
594 case EINTR:
595 case ENOLCK:
596 /* random NFS retry error, unless during file system support
597 * introspection, in which it actually means what it says */
598 return SQLITE_BUSY;
599
600 case EACCES:
601 /* EACCES is like EAGAIN during locking operations, but not any other time*/
602 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
603 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
604 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
605 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
606 return SQLITE_BUSY;
607 }
608 /* else fall through */
609 case EPERM:
610 return SQLITE_PERM;
611
612 case EDEADLK:
613 return SQLITE_IOERR_BLOCKED;
614
615#if EOPNOTSUPP!=ENOTSUP
616 case EOPNOTSUPP:
617 /* something went terribly awry, unless during file system support
618 * introspection, in which it actually means what it says */
619#endif
620#ifdef ENOTSUP
621 case ENOTSUP:
622 /* invalid fd, unless during file system support introspection, in which
623 * it actually means what it says */
624#endif
625 case EIO:
626 case EBADF:
627 case EINVAL:
628 case ENOTCONN:
629 case ENODEV:
630 case ENXIO:
631 case ENOENT:
632 case ESTALE:
633 case ENOSYS:
634 /* these should force the client to close the file and reconnect */
635
636 default:
637 return sqliteIOErr;
638 }
639}
640
641
642
643/******************************************************************************
644****************** Begin Unique File ID Utility Used By VxWorks ***************
645**
646** On most versions of unix, we can get a unique ID for a file by concatenating
647** the device number and the inode number. But this does not work on VxWorks.
648** On VxWorks, a unique file id must be based on the canonical filename.
649**
650** A pointer to an instance of the following structure can be used as a
651** unique file ID in VxWorks. Each instance of this structure contains
652** a copy of the canonical filename. There is also a reference count.
653** The structure is reclaimed when the number of pointers to it drops to
654** zero.
655**
656** There are never very many files open at one time and lookups are not
657** a performance-critical path, so it is sufficient to put these
658** structures on a linked list.
659*/
660struct vxworksFileId {
661 struct vxworksFileId *pNext; /* Next in a list of them all */
662 int nRef; /* Number of references to this one */
663 int nName; /* Length of the zCanonicalName[] string */
664 char *zCanonicalName; /* Canonical filename */
665};
666
667#if OS_VXWORKS
668/*
drh9b35ea62008-11-29 02:20:26 +0000669** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000670** variable:
671*/
672static struct vxworksFileId *vxworksFileList = 0;
673
674/*
675** Simplify a filename into its canonical form
676** by making the following changes:
677**
678** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000679** * convert /./ into just /
680** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000681**
682** Changes are made in-place. Return the new name length.
683**
684** The original filename is in z[0..n-1]. Return the number of
685** characters in the simplified name.
686*/
687static int vxworksSimplifyName(char *z, int n){
688 int i, j;
689 while( n>1 && z[n-1]=='/' ){ n--; }
690 for(i=j=0; i<n; i++){
691 if( z[i]=='/' ){
692 if( z[i+1]=='/' ) continue;
693 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
694 i += 1;
695 continue;
696 }
697 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
698 while( j>0 && z[j-1]!='/' ){ j--; }
699 if( j>0 ){ j--; }
700 i += 2;
701 continue;
702 }
703 }
704 z[j++] = z[i];
705 }
706 z[j] = 0;
707 return j;
708}
709
710/*
711** Find a unique file ID for the given absolute pathname. Return
712** a pointer to the vxworksFileId object. This pointer is the unique
713** file ID.
714**
715** The nRef field of the vxworksFileId object is incremented before
716** the object is returned. A new vxworksFileId object is created
717** and added to the global list if necessary.
718**
719** If a memory allocation error occurs, return NULL.
720*/
721static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
722 struct vxworksFileId *pNew; /* search key and new file ID */
723 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
724 int n; /* Length of zAbsoluteName string */
725
726 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000727 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000728 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
729 if( pNew==0 ) return 0;
730 pNew->zCanonicalName = (char*)&pNew[1];
731 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
732 n = vxworksSimplifyName(pNew->zCanonicalName, n);
733
734 /* Search for an existing entry that matching the canonical name.
735 ** If found, increment the reference count and return a pointer to
736 ** the existing file ID.
737 */
738 unixEnterMutex();
739 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
740 if( pCandidate->nName==n
741 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
742 ){
743 sqlite3_free(pNew);
744 pCandidate->nRef++;
745 unixLeaveMutex();
746 return pCandidate;
747 }
748 }
749
750 /* No match was found. We will make a new file ID */
751 pNew->nRef = 1;
752 pNew->nName = n;
753 pNew->pNext = vxworksFileList;
754 vxworksFileList = pNew;
755 unixLeaveMutex();
756 return pNew;
757}
758
759/*
760** Decrement the reference count on a vxworksFileId object. Free
761** the object when the reference count reaches zero.
762*/
763static void vxworksReleaseFileId(struct vxworksFileId *pId){
764 unixEnterMutex();
765 assert( pId->nRef>0 );
766 pId->nRef--;
767 if( pId->nRef==0 ){
768 struct vxworksFileId **pp;
769 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
770 assert( *pp==pId );
771 *pp = pId->pNext;
772 sqlite3_free(pId);
773 }
774 unixLeaveMutex();
775}
776#endif /* OS_VXWORKS */
777/*************** End of Unique File ID Utility Used By VxWorks ****************
778******************************************************************************/
779
780
781/******************************************************************************
782*************************** Posix Advisory Locking ****************************
783**
drh9b35ea62008-11-29 02:20:26 +0000784** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000785** section 6.5.2.2 lines 483 through 490 specify that when a process
786** sets or clears a lock, that operation overrides any prior locks set
787** by the same process. It does not explicitly say so, but this implies
788** that it overrides locks set by the same process using a different
789** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000790**
791** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000792** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
793**
794** Suppose ./file1 and ./file2 are really the same file (because
795** one is a hard or symbolic link to the other) then if you set
796** an exclusive lock on fd1, then try to get an exclusive lock
797** on fd2, it works. I would have expected the second lock to
798** fail since there was already a lock on the file due to fd1.
799** But not so. Since both locks came from the same process, the
800** second overrides the first, even though they were on different
801** file descriptors opened on different file names.
802**
drh734c9862008-11-28 15:37:20 +0000803** This means that we cannot use POSIX locks to synchronize file access
804** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000805** to synchronize access for threads in separate processes, but not
806** threads within the same process.
807**
808** To work around the problem, SQLite has to manage file locks internally
809** on its own. Whenever a new database is opened, we have to find the
810** specific inode of the database file (the inode is determined by the
811** st_dev and st_ino fields of the stat structure that fstat() fills in)
812** and check for locks already existing on that inode. When locks are
813** created or removed, we have to look at our own internal record of the
814** locks to see if another thread has previously set a lock on that same
815** inode.
816**
drh9b35ea62008-11-29 02:20:26 +0000817** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
818** For VxWorks, we have to use the alternative unique ID system based on
819** canonical filename and implemented in the previous division.)
820**
danielk1977ad94b582007-08-20 06:44:22 +0000821** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000822** descriptor. It is now a structure that holds the integer file
823** descriptor and a pointer to a structure that describes the internal
824** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000825** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000826** point to the same locking structure. The locking structure keeps
827** a reference count (so we will know when to delete it) and a "cnt"
828** field that tells us its internal lock status. cnt==0 means the
829** file is unlocked. cnt==-1 means the file has an exclusive lock.
830** cnt>0 means there are cnt shared locks on the file.
831**
832** Any attempt to lock or unlock a file first checks the locking
833** structure. The fcntl() system call is only invoked to set a
834** POSIX lock if the internal lock structure transitions between
835** a locked and an unlocked state.
836**
drh734c9862008-11-28 15:37:20 +0000837** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000838**
839** If you close a file descriptor that points to a file that has locks,
840** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000841** released. To work around this problem, each unixInodeInfo object
842** maintains a count of the number of pending locks on tha inode.
843** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000844** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000845** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000846** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000847** be closed and that list is walked (and cleared) when the last lock
848** clears.
849**
drh9b35ea62008-11-29 02:20:26 +0000850** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000851**
drh9b35ea62008-11-29 02:20:26 +0000852** Many older versions of linux use the LinuxThreads library which is
853** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000854** A cannot be modified or overridden by a different thread B.
855** Only thread A can modify the lock. Locking behavior is correct
856** if the appliation uses the newer Native Posix Thread Library (NPTL)
857** on linux - with NPTL a lock created by thread A can override locks
858** in thread B. But there is no way to know at compile-time which
859** threading library is being used. So there is no way to know at
860** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000861** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000862** current process.
drh5fdae772004-06-29 03:29:00 +0000863**
drh8af6c222010-05-14 12:43:01 +0000864** SQLite used to support LinuxThreads. But support for LinuxThreads
865** was dropped beginning with version 3.7.0. SQLite will still work with
866** LinuxThreads provided that (1) there is no more than one connection
867** per database file in the same process and (2) database connections
868** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000869*/
870
871/*
872** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000873** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000874*/
875struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000876 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000877#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000878 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000879#else
drh107886a2008-11-21 22:21:50 +0000880 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000881#endif
882};
883
884/*
drhbbd42a62004-05-22 17:41:58 +0000885** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000886** inode. Or, on LinuxThreads, there is one of these structures for
887** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000888**
danielk1977ad94b582007-08-20 06:44:22 +0000889** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000890** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000891** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000892*/
drh8af6c222010-05-14 12:43:01 +0000893struct unixInodeInfo {
894 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000895 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000896 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
897 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000898 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000899 unixShmNode *pShmNode; /* Shared memory associated with this inode */
900 int nLock; /* Number of outstanding file locks */
901 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
902 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
903 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000904#if defined(SQLITE_ENABLE_LOCKING_STYLE)
905 unsigned long long sharedByte; /* for AFP simulated shared lock */
906#endif
drh6c7d5c52008-11-21 20:32:33 +0000907#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000908 sem_t *pSem; /* Named POSIX semaphore */
909 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000910#endif
drhbbd42a62004-05-22 17:41:58 +0000911};
912
drhda0e7682008-07-30 15:27:54 +0000913/*
drh8af6c222010-05-14 12:43:01 +0000914** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000915*/
drhd91c68f2010-05-14 14:52:25 +0000916static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000917
drh5fdae772004-06-29 03:29:00 +0000918/*
dane18d4952011-02-21 11:46:24 +0000919**
920** This function - unixLogError_x(), is only ever called via the macro
921** unixLogError().
922**
923** It is invoked after an error occurs in an OS function and errno has been
924** set. It logs a message using sqlite3_log() containing the current value of
925** errno and, if possible, the human-readable equivalent from strerror() or
926** strerror_r().
927**
928** The first argument passed to the macro should be the error code that
929** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
930** The two subsequent arguments should be the name of the OS function that
931** failed (e.g. "unlink", "open") and the the associated file-system path,
932** if any.
933*/
drh0e9365c2011-03-02 02:08:13 +0000934#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
935static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000936 int errcode, /* SQLite error code */
937 const char *zFunc, /* Name of OS function that failed */
938 const char *zPath, /* File path associated with error */
939 int iLine /* Source line number where error occurred */
940){
941 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000942 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000943
944 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
945 ** the strerror() function to obtain the human-readable error message
946 ** equivalent to errno. Otherwise, use strerror_r().
947 */
948#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
949 char aErr[80];
950 memset(aErr, 0, sizeof(aErr));
951 zErr = aErr;
952
953 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
954 ** assume that the system provides the the GNU version of strerror_r() that
955 ** returns a pointer to a buffer containing the error message. That pointer
956 ** may point to aErr[], or it may point to some static storage somewhere.
957 ** Otherwise, assume that the system provides the POSIX version of
958 ** strerror_r(), which always writes an error message into aErr[].
959 **
960 ** If the code incorrectly assumes that it is the POSIX version that is
961 ** available, the error message will often be an empty string. Not a
962 ** huge problem. Incorrectly concluding that the GNU version is available
963 ** could lead to a segfault though.
964 */
965#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
966 zErr =
967# endif
drh0e9365c2011-03-02 02:08:13 +0000968 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000969
970#elif SQLITE_THREADSAFE
971 /* This is a threadsafe build, but strerror_r() is not available. */
972 zErr = "";
973#else
974 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000975 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000976#endif
977
978 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000979 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000980 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000981 "os_unix.c:%d: (%d) %s(%s) - %s",
982 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000983 );
984
985 return errcode;
986}
987
drh0e9365c2011-03-02 02:08:13 +0000988/*
989** Close a file descriptor.
990**
991** We assume that close() almost always works, since it is only in a
992** very sick application or on a very sick platform that it might fail.
993** If it does fail, simply leak the file descriptor, but do log the
994** error.
995**
996** Note that it is not safe to retry close() after EINTR since the
997** file descriptor might have already been reused by another thread.
998** So we don't even try to recover from an EINTR. Just log the error
999** and move on.
1000*/
1001static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001002 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001003 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1004 pFile ? pFile->zPath : 0, lineno);
1005 }
1006}
dane18d4952011-02-21 11:46:24 +00001007
1008/*
danb0ac3e32010-06-16 10:55:42 +00001009** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001010*/
drh0e9365c2011-03-02 02:08:13 +00001011static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001012 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001013 UnixUnusedFd *p;
1014 UnixUnusedFd *pNext;
1015 for(p=pInode->pUnused; p; p=pNext){
1016 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001017 robust_close(pFile, p->fd, __LINE__);
1018 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001019 }
drh0e9365c2011-03-02 02:08:13 +00001020 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001021}
1022
1023/*
drh8af6c222010-05-14 12:43:01 +00001024** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001025**
1026** The mutex entered using the unixEnterMutex() function must be held
1027** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001028*/
danb0ac3e32010-06-16 10:55:42 +00001029static void releaseInodeInfo(unixFile *pFile){
1030 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001031 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001032 if( pInode ){
1033 pInode->nRef--;
1034 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001035 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001036 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001037 if( pInode->pPrev ){
1038 assert( pInode->pPrev->pNext==pInode );
1039 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001040 }else{
drh8af6c222010-05-14 12:43:01 +00001041 assert( inodeList==pInode );
1042 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001043 }
drh8af6c222010-05-14 12:43:01 +00001044 if( pInode->pNext ){
1045 assert( pInode->pNext->pPrev==pInode );
1046 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001047 }
drh8af6c222010-05-14 12:43:01 +00001048 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001049 }
drhbbd42a62004-05-22 17:41:58 +00001050 }
1051}
1052
1053/*
drh8af6c222010-05-14 12:43:01 +00001054** Given a file descriptor, locate the unixInodeInfo object that
1055** describes that file descriptor. Create a new one if necessary. The
1056** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001057**
dan9359c7b2009-08-21 08:29:10 +00001058** The mutex entered using the unixEnterMutex() function must be held
1059** when this function is called.
1060**
drh6c7d5c52008-11-21 20:32:33 +00001061** Return an appropriate error code.
1062*/
drh8af6c222010-05-14 12:43:01 +00001063static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001064 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001065 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001066){
1067 int rc; /* System call return code */
1068 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001069 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1070 struct stat statbuf; /* Low-level file information */
1071 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001072
dan9359c7b2009-08-21 08:29:10 +00001073 assert( unixMutexHeld() );
1074
drh6c7d5c52008-11-21 20:32:33 +00001075 /* Get low-level information about the file that we can used to
1076 ** create a unique name for the file.
1077 */
1078 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001079 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001080 if( rc!=0 ){
1081 pFile->lastErrno = errno;
1082#ifdef EOVERFLOW
1083 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1084#endif
1085 return SQLITE_IOERR;
1086 }
1087
drheb0d74f2009-02-03 15:27:02 +00001088#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001089 /* On OS X on an msdos filesystem, the inode number is reported
1090 ** incorrectly for zero-size files. See ticket #3260. To work
1091 ** around this problem (we consider it a bug in OS X, not SQLite)
1092 ** we always increase the file size to 1 by writing a single byte
1093 ** prior to accessing the inode number. The one byte written is
1094 ** an ASCII 'S' character which also happens to be the first byte
1095 ** in the header of every SQLite database. In this way, if there
1096 ** is a race condition such that another thread has already populated
1097 ** the first page of the database, no damage is done.
1098 */
drh7ed97b92010-01-20 13:07:21 +00001099 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001100 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001101 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001102 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001103 return SQLITE_IOERR;
1104 }
drh99ab3b12011-03-02 15:09:07 +00001105 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001106 if( rc!=0 ){
1107 pFile->lastErrno = errno;
1108 return SQLITE_IOERR;
1109 }
1110 }
drheb0d74f2009-02-03 15:27:02 +00001111#endif
drh6c7d5c52008-11-21 20:32:33 +00001112
drh8af6c222010-05-14 12:43:01 +00001113 memset(&fileId, 0, sizeof(fileId));
1114 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001115#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001116 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001117#else
drh8af6c222010-05-14 12:43:01 +00001118 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001119#endif
drh8af6c222010-05-14 12:43:01 +00001120 pInode = inodeList;
1121 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1122 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001123 }
drh8af6c222010-05-14 12:43:01 +00001124 if( pInode==0 ){
1125 pInode = sqlite3_malloc( sizeof(*pInode) );
1126 if( pInode==0 ){
1127 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001128 }
drh8af6c222010-05-14 12:43:01 +00001129 memset(pInode, 0, sizeof(*pInode));
1130 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1131 pInode->nRef = 1;
1132 pInode->pNext = inodeList;
1133 pInode->pPrev = 0;
1134 if( inodeList ) inodeList->pPrev = pInode;
1135 inodeList = pInode;
1136 }else{
1137 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001138 }
drh8af6c222010-05-14 12:43:01 +00001139 *ppInode = pInode;
1140 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001141}
drh6c7d5c52008-11-21 20:32:33 +00001142
aswift5b1a2562008-08-22 00:22:35 +00001143
1144/*
danielk197713adf8a2004-06-03 16:08:41 +00001145** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001146** file by this or any other process. If such a lock is held, set *pResOut
1147** to a non-zero value otherwise *pResOut is set to zero. The return value
1148** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001149*/
danielk1977861f7452008-06-05 11:39:11 +00001150static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001151 int rc = SQLITE_OK;
1152 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001153 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001154
danielk1977861f7452008-06-05 11:39:11 +00001155 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1156
drh054889e2005-11-30 03:20:31 +00001157 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001158 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001159
1160 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001161 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001162 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001163 }
1164
drh2ac3ee92004-06-07 16:27:46 +00001165 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001166 */
danielk197709480a92009-02-09 05:32:32 +00001167#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001168 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001169 struct flock lock;
1170 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001171 lock.l_start = RESERVED_BYTE;
1172 lock.l_len = 1;
1173 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001174 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001175 int tErrno = errno;
1176 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1177 pFile->lastErrno = tErrno;
1178 } else if( lock.l_type!=F_UNLCK ){
1179 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001180 }
1181 }
danielk197709480a92009-02-09 05:32:32 +00001182#endif
danielk197713adf8a2004-06-03 16:08:41 +00001183
drh6c7d5c52008-11-21 20:32:33 +00001184 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001185 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001186
aswift5b1a2562008-08-22 00:22:35 +00001187 *pResOut = reserved;
1188 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001189}
1190
1191/*
drha7e61d82011-03-12 17:02:57 +00001192** Attempt to set a system-lock on the file pFile. The lock is
1193** described by pLock.
1194**
1195** If the pFile was opened from unix-excl, then the only lock ever
1196** obtained is an exclusive lock, and it is obtained exactly once
1197** the first time any lock is attempted. All subsequent system locking
1198** operations become no-ops. Locking operations still happen internally,
1199** in order to coordinate access between separate database connections
1200** within this process, but all of that is handled in memory and the
1201** operating system does not participate.
1202*/
1203static int unixFileLock(unixFile *pFile, struct flock *pLock){
1204 int rc;
drh3cb93392011-03-12 18:10:44 +00001205 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001206 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001207 assert( pInode!=0 );
1208 if( (pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock ){
1209 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001210 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001211 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001212 lock.l_whence = SEEK_SET;
1213 lock.l_start = SHARED_FIRST;
1214 lock.l_len = SHARED_SIZE;
1215 lock.l_type = F_WRLCK;
1216 rc = osFcntl(pFile->h, F_SETLK, &lock);
1217 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001218 pInode->bProcessLock = 1;
1219 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001220 }else{
1221 rc = 0;
1222 }
1223 }else{
1224 rc = osFcntl(pFile->h, F_SETLK, pLock);
1225 }
1226 return rc;
1227}
1228
1229/*
drh308c2a52010-05-14 11:30:18 +00001230** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001231** of the following:
1232**
drh2ac3ee92004-06-07 16:27:46 +00001233** (1) SHARED_LOCK
1234** (2) RESERVED_LOCK
1235** (3) PENDING_LOCK
1236** (4) EXCLUSIVE_LOCK
1237**
drhb3e04342004-06-08 00:47:47 +00001238** Sometimes when requesting one lock state, additional lock states
1239** are inserted in between. The locking might fail on one of the later
1240** transitions leaving the lock state different from what it started but
1241** still short of its goal. The following chart shows the allowed
1242** transitions and the inserted intermediate states:
1243**
1244** UNLOCKED -> SHARED
1245** SHARED -> RESERVED
1246** SHARED -> (PENDING) -> EXCLUSIVE
1247** RESERVED -> (PENDING) -> EXCLUSIVE
1248** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001249**
drha6abd042004-06-09 17:37:22 +00001250** This routine will only increase a lock. Use the sqlite3OsUnlock()
1251** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001252*/
drh308c2a52010-05-14 11:30:18 +00001253static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001254 /* The following describes the implementation of the various locks and
1255 ** lock transitions in terms of the POSIX advisory shared and exclusive
1256 ** lock primitives (called read-locks and write-locks below, to avoid
1257 ** confusion with SQLite lock names). The algorithms are complicated
1258 ** slightly in order to be compatible with windows systems simultaneously
1259 ** accessing the same database file, in case that is ever required.
1260 **
1261 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1262 ** byte', each single bytes at well known offsets, and the 'shared byte
1263 ** range', a range of 510 bytes at a well known offset.
1264 **
1265 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1266 ** byte'. If this is successful, a random byte from the 'shared byte
1267 ** range' is read-locked and the lock on the 'pending byte' released.
1268 **
danielk197790ba3bd2004-06-25 08:32:25 +00001269 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1270 ** A RESERVED lock is implemented by grabbing a write-lock on the
1271 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001272 **
1273 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001274 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1275 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1276 ** obtained, but existing SHARED locks are allowed to persist. A process
1277 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1278 ** This property is used by the algorithm for rolling back a journal file
1279 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001280 **
danielk197790ba3bd2004-06-25 08:32:25 +00001281 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1282 ** implemented by obtaining a write-lock on the entire 'shared byte
1283 ** range'. Since all other locks require a read-lock on one of the bytes
1284 ** within this range, this ensures that no other locks are held on the
1285 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001286 **
1287 ** The reason a single byte cannot be used instead of the 'shared byte
1288 ** range' is that some versions of windows do not support read-locks. By
1289 ** locking a random byte from a range, concurrent SHARED locks may exist
1290 ** even if the locking primitive used is always a write-lock.
1291 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001292 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001293 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001294 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001296 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001297 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001298
drh054889e2005-11-30 03:20:31 +00001299 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001300 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1301 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001302 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001303
1304 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001305 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001306 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001307 */
drh308c2a52010-05-14 11:30:18 +00001308 if( pFile->eFileLock>=eFileLock ){
1309 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1310 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001311 return SQLITE_OK;
1312 }
1313
drh0c2694b2009-09-03 16:23:44 +00001314 /* Make sure the locking sequence is correct.
1315 ** (1) We never move from unlocked to anything higher than shared lock.
1316 ** (2) SQLite never explicitly requests a pendig lock.
1317 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001318 */
drh308c2a52010-05-14 11:30:18 +00001319 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1320 assert( eFileLock!=PENDING_LOCK );
1321 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001322
drh8af6c222010-05-14 12:43:01 +00001323 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001324 */
drh6c7d5c52008-11-21 20:32:33 +00001325 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001326 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001327
danielk1977ad94b582007-08-20 06:44:22 +00001328 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001329 ** handle that precludes the requested lock, return BUSY.
1330 */
drh8af6c222010-05-14 12:43:01 +00001331 if( (pFile->eFileLock!=pInode->eFileLock &&
1332 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001333 ){
1334 rc = SQLITE_BUSY;
1335 goto end_lock;
1336 }
1337
1338 /* If a SHARED lock is requested, and some thread using this PID already
1339 ** has a SHARED or RESERVED lock, then increment reference counts and
1340 ** return SQLITE_OK.
1341 */
drh308c2a52010-05-14 11:30:18 +00001342 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001343 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001344 assert( eFileLock==SHARED_LOCK );
1345 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001346 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001347 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001348 pInode->nShared++;
1349 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 goto end_lock;
1351 }
1352
danielk19779a1d0ab2004-06-01 14:09:28 +00001353
drh3cde3bb2004-06-12 02:17:14 +00001354 /* A PENDING lock is needed before acquiring a SHARED lock and before
1355 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1356 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001357 */
drh0c2694b2009-09-03 16:23:44 +00001358 lock.l_len = 1L;
1359 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001360 if( eFileLock==SHARED_LOCK
1361 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001362 ){
drh308c2a52010-05-14 11:30:18 +00001363 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001364 lock.l_start = PENDING_BYTE;
drha7e61d82011-03-12 17:02:57 +00001365 s = unixFileLock(pFile, &lock);
drhe2396a12007-03-29 20:19:58 +00001366 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001367 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001368 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1369 if( IS_LOCK_ERROR(rc) ){
1370 pFile->lastErrno = tErrno;
1371 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 goto end_lock;
1373 }
drh3cde3bb2004-06-12 02:17:14 +00001374 }
1375
1376
1377 /* If control gets to this point, then actually go ahead and make
1378 ** operating system calls for the specified lock.
1379 */
drh308c2a52010-05-14 11:30:18 +00001380 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001381 assert( pInode->nShared==0 );
1382 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001383
drh2ac3ee92004-06-07 16:27:46 +00001384 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001385 lock.l_start = SHARED_FIRST;
1386 lock.l_len = SHARED_SIZE;
drha7e61d82011-03-12 17:02:57 +00001387 if( (s = unixFileLock(pFile, &lock))==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001388 tErrno = errno;
1389 }
drh2ac3ee92004-06-07 16:27:46 +00001390 /* Drop the temporary PENDING lock */
1391 lock.l_start = PENDING_BYTE;
1392 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001393 lock.l_type = F_UNLCK;
drha7e61d82011-03-12 17:02:57 +00001394 if( unixFileLock(pFile, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001395 if( s != -1 ){
1396 /* This could happen with a network mount */
1397 tErrno = errno;
1398 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1399 if( IS_LOCK_ERROR(rc) ){
1400 pFile->lastErrno = tErrno;
1401 }
1402 goto end_lock;
1403 }
drh2b4b5962005-06-15 17:47:55 +00001404 }
drhe2396a12007-03-29 20:19:58 +00001405 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1407 if( IS_LOCK_ERROR(rc) ){
1408 pFile->lastErrno = tErrno;
1409 }
drhbbd42a62004-05-22 17:41:58 +00001410 }else{
drh308c2a52010-05-14 11:30:18 +00001411 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001412 pInode->nLock++;
1413 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001414 }
drh8af6c222010-05-14 12:43:01 +00001415 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001416 /* We are trying for an exclusive lock but another thread in this
1417 ** same process is still holding a shared lock. */
1418 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001419 }else{
drh3cde3bb2004-06-12 02:17:14 +00001420 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001421 ** assumed that there is a SHARED or greater lock on the file
1422 ** already.
1423 */
drh308c2a52010-05-14 11:30:18 +00001424 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001425 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001426 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001427 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001428 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001429 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001430 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001431 lock.l_start = SHARED_FIRST;
1432 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001433 break;
1434 default:
1435 assert(0);
1436 }
drha7e61d82011-03-12 17:02:57 +00001437 s = unixFileLock(pFile, &lock);
drhe2396a12007-03-29 20:19:58 +00001438 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001439 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001440 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1441 if( IS_LOCK_ERROR(rc) ){
1442 pFile->lastErrno = tErrno;
1443 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001444 }
drhbbd42a62004-05-22 17:41:58 +00001445 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001446
drh8f941bc2009-01-14 23:03:40 +00001447
1448#ifndef NDEBUG
1449 /* Set up the transaction-counter change checking flags when
1450 ** transitioning from a SHARED to a RESERVED lock. The change
1451 ** from SHARED to RESERVED marks the beginning of a normal
1452 ** write operation (not a hot journal rollback).
1453 */
1454 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001455 && pFile->eFileLock<=SHARED_LOCK
1456 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001457 ){
1458 pFile->transCntrChng = 0;
1459 pFile->dbUpdate = 0;
1460 pFile->inNormalWrite = 1;
1461 }
1462#endif
1463
1464
danielk1977ecb2a962004-06-02 06:30:16 +00001465 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001466 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001467 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001468 }else if( eFileLock==EXCLUSIVE_LOCK ){
1469 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001470 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001471 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001472
1473end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001474 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001475 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1476 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001477 return rc;
1478}
1479
1480/*
dan08da86a2009-08-21 17:18:03 +00001481** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001482** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001483*/
1484static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001485 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001486 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001487 p->pNext = pInode->pUnused;
1488 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001489 pFile->h = -1;
1490 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001491}
1492
1493/*
drh308c2a52010-05-14 11:30:18 +00001494** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001495** must be either NO_LOCK or SHARED_LOCK.
1496**
1497** If the locking level of the file descriptor is already at or below
1498** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001499**
1500** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1501** the byte range is divided into 2 parts and the first part is unlocked then
1502** set to a read lock, then the other part is simply unlocked. This works
1503** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1504** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001505*/
drha7e61d82011-03-12 17:02:57 +00001506static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001507 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001508 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001509 struct flock lock;
1510 int rc = SQLITE_OK;
1511 int h;
drh0c2694b2009-09-03 16:23:44 +00001512 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001513
drh054889e2005-11-30 03:20:31 +00001514 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001515 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001516 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001517 getpid()));
drha6abd042004-06-09 17:37:22 +00001518
drh308c2a52010-05-14 11:30:18 +00001519 assert( eFileLock<=SHARED_LOCK );
1520 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001521 return SQLITE_OK;
1522 }
drh6c7d5c52008-11-21 20:32:33 +00001523 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001524 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001525 pInode = pFile->pInode;
1526 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001527 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001528 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001529 SimulateIOErrorBenign(1);
1530 SimulateIOError( h=(-1) )
1531 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001532
1533#ifndef NDEBUG
1534 /* When reducing a lock such that other processes can start
1535 ** reading the database file again, make sure that the
1536 ** transaction counter was updated if any part of the database
1537 ** file changed. If the transaction counter is not updated,
1538 ** other connections to the same file might not realize that
1539 ** the file has changed and hence might not know to flush their
1540 ** cache. The use of a stale cache can lead to database corruption.
1541 */
dan7c246102010-04-12 19:00:29 +00001542#if 0
drh8f941bc2009-01-14 23:03:40 +00001543 assert( pFile->inNormalWrite==0
1544 || pFile->dbUpdate==0
1545 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001546#endif
drh8f941bc2009-01-14 23:03:40 +00001547 pFile->inNormalWrite = 0;
1548#endif
1549
drh7ed97b92010-01-20 13:07:21 +00001550 /* downgrading to a shared lock on NFS involves clearing the write lock
1551 ** before establishing the readlock - to avoid a race condition we downgrade
1552 ** the lock in 2 blocks, so that part of the range will be covered by a
1553 ** write lock until the rest is covered by a read lock:
1554 ** 1: [WWWWW]
1555 ** 2: [....W]
1556 ** 3: [RRRRW]
1557 ** 4: [RRRR.]
1558 */
drh308c2a52010-05-14 11:30:18 +00001559 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001560
1561#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001562 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001563 assert( handleNFSUnlock==0 );
1564#endif
1565#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001566 if( handleNFSUnlock ){
1567 off_t divSize = SHARED_SIZE - 1;
1568
1569 lock.l_type = F_UNLCK;
1570 lock.l_whence = SEEK_SET;
1571 lock.l_start = SHARED_FIRST;
1572 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001573 if( unixFileLock(pFile,, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001574 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001575 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1576 if( IS_LOCK_ERROR(rc) ){
1577 pFile->lastErrno = tErrno;
1578 }
1579 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001580 }
drh7ed97b92010-01-20 13:07:21 +00001581 lock.l_type = F_RDLCK;
1582 lock.l_whence = SEEK_SET;
1583 lock.l_start = SHARED_FIRST;
1584 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001585 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001586 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001587 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1588 if( IS_LOCK_ERROR(rc) ){
1589 pFile->lastErrno = tErrno;
1590 }
1591 goto end_unlock;
1592 }
1593 lock.l_type = F_UNLCK;
1594 lock.l_whence = SEEK_SET;
1595 lock.l_start = SHARED_FIRST+divSize;
1596 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001597 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001598 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001599 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1600 if( IS_LOCK_ERROR(rc) ){
1601 pFile->lastErrno = tErrno;
1602 }
1603 goto end_unlock;
1604 }
drh30f776f2011-02-25 03:25:07 +00001605 }else
1606#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1607 {
drh7ed97b92010-01-20 13:07:21 +00001608 lock.l_type = F_RDLCK;
1609 lock.l_whence = SEEK_SET;
1610 lock.l_start = SHARED_FIRST;
1611 lock.l_len = SHARED_SIZE;
drha7e61d82011-03-12 17:02:57 +00001612 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001613 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001614 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1615 if( IS_LOCK_ERROR(rc) ){
1616 pFile->lastErrno = tErrno;
1617 }
1618 goto end_unlock;
1619 }
drh9c105bb2004-10-02 20:38:28 +00001620 }
1621 }
drhbbd42a62004-05-22 17:41:58 +00001622 lock.l_type = F_UNLCK;
1623 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001624 lock.l_start = PENDING_BYTE;
1625 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drha7e61d82011-03-12 17:02:57 +00001626 if( unixFileLock(pFile, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001627 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001628 }else{
drh0c2694b2009-09-03 16:23:44 +00001629 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001630 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1631 if( IS_LOCK_ERROR(rc) ){
1632 pFile->lastErrno = tErrno;
1633 }
drhcd731cf2009-03-28 23:23:02 +00001634 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001635 }
drhbbd42a62004-05-22 17:41:58 +00001636 }
drh308c2a52010-05-14 11:30:18 +00001637 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001638 /* Decrement the shared lock counter. Release the lock using an
1639 ** OS call only when all threads in this same process have released
1640 ** the lock.
1641 */
drh8af6c222010-05-14 12:43:01 +00001642 pInode->nShared--;
1643 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001644 lock.l_type = F_UNLCK;
1645 lock.l_whence = SEEK_SET;
1646 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001647 SimulateIOErrorBenign(1);
1648 SimulateIOError( h=(-1) )
1649 SimulateIOErrorBenign(0);
drha7e61d82011-03-12 17:02:57 +00001650 if( unixFileLock(pFile, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001651 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001652 }else{
drh0c2694b2009-09-03 16:23:44 +00001653 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001654 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001655 if( IS_LOCK_ERROR(rc) ){
1656 pFile->lastErrno = tErrno;
1657 }
drh8af6c222010-05-14 12:43:01 +00001658 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001659 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001660 }
drha6abd042004-06-09 17:37:22 +00001661 }
1662
drhbbd42a62004-05-22 17:41:58 +00001663 /* Decrement the count of locks against this same file. When the
1664 ** count reaches zero, close any other file descriptors whose close
1665 ** was deferred because of outstanding locks.
1666 */
drh8af6c222010-05-14 12:43:01 +00001667 pInode->nLock--;
1668 assert( pInode->nLock>=0 );
1669 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001670 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001671 }
1672 }
aswift5b1a2562008-08-22 00:22:35 +00001673
1674end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001675 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001676 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001677 return rc;
drhbbd42a62004-05-22 17:41:58 +00001678}
1679
1680/*
drh308c2a52010-05-14 11:30:18 +00001681** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001682** must be either NO_LOCK or SHARED_LOCK.
1683**
1684** If the locking level of the file descriptor is already at or below
1685** the requested locking level, this routine is a no-op.
1686*/
drh308c2a52010-05-14 11:30:18 +00001687static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001688 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001689}
1690
1691/*
danielk1977e339d652008-06-28 11:23:00 +00001692** This function performs the parts of the "close file" operation
1693** common to all locking schemes. It closes the directory and file
1694** handles, if they are valid, and sets all fields of the unixFile
1695** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001696**
1697** It is *not* necessary to hold the mutex when this routine is called,
1698** even on VxWorks. A mutex will be acquired on VxWorks by the
1699** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001700*/
1701static int closeUnixFile(sqlite3_file *id){
1702 unixFile *pFile = (unixFile*)id;
1703 if( pFile ){
1704 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001705 robust_close(pFile, pFile->dirfd, __LINE__);
1706 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001707 }
1708 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001709 robust_close(pFile, pFile->h, __LINE__);
1710 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001711 }
drh6c7d5c52008-11-21 20:32:33 +00001712#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001713 if( pFile->pId ){
1714 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001715 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001716 }
drh107886a2008-11-21 22:21:50 +00001717 vxworksReleaseFileId(pFile->pId);
1718 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001719 }
1720#endif
drhff59a112010-05-14 20:15:51 +00001721 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001722 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001723 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001724 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001725 }
1726 return SQLITE_OK;
1727}
1728
1729/*
danielk1977e3026632004-06-22 11:29:02 +00001730** Close a file.
1731*/
danielk197762079062007-08-15 17:08:46 +00001732static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001733 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001734 if( id ){
1735 unixFile *pFile = (unixFile *)id;
1736 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001737 unixEnterMutex();
drh3cb93392011-03-12 18:10:44 +00001738 assert( pFile->pInode==0 || pFile->pInode->nLock>0
1739 || pFile->pInode->bProcessLock==0 );
drh8af6c222010-05-14 12:43:01 +00001740 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001741 /* If there are outstanding locks, do not actually close the file just
1742 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001743 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001744 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001745 */
dan08da86a2009-08-21 17:18:03 +00001746 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001747 }
danb0ac3e32010-06-16 10:55:42 +00001748 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001749 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001750 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001751 }
aswiftaebf4132008-11-21 00:10:35 +00001752 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001753}
1754
drh734c9862008-11-28 15:37:20 +00001755/************** End of the posix advisory lock implementation *****************
1756******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001757
drh734c9862008-11-28 15:37:20 +00001758/******************************************************************************
1759****************************** No-op Locking **********************************
1760**
1761** Of the various locking implementations available, this is by far the
1762** simplest: locking is ignored. No attempt is made to lock the database
1763** file for reading or writing.
1764**
1765** This locking mode is appropriate for use on read-only databases
1766** (ex: databases that are burned into CD-ROM, for example.) It can
1767** also be used if the application employs some external mechanism to
1768** prevent simultaneous access of the same database by two or more
1769** database connections. But there is a serious risk of database
1770** corruption if this locking mode is used in situations where multiple
1771** database connections are accessing the same database file at the same
1772** time and one or more of those connections are writing.
1773*/
drhbfe66312006-10-03 17:40:40 +00001774
drh734c9862008-11-28 15:37:20 +00001775static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1776 UNUSED_PARAMETER(NotUsed);
1777 *pResOut = 0;
1778 return SQLITE_OK;
1779}
drh734c9862008-11-28 15:37:20 +00001780static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1781 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1782 return SQLITE_OK;
1783}
drh734c9862008-11-28 15:37:20 +00001784static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1785 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1786 return SQLITE_OK;
1787}
1788
1789/*
drh9b35ea62008-11-29 02:20:26 +00001790** Close the file.
drh734c9862008-11-28 15:37:20 +00001791*/
1792static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001793 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001794}
1795
1796/******************* End of the no-op lock implementation *********************
1797******************************************************************************/
1798
1799/******************************************************************************
1800************************* Begin dot-file Locking ******************************
1801**
drh0c2694b2009-09-03 16:23:44 +00001802** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001803** files in order to control access to the database. This works on just
1804** about every filesystem imaginable. But there are serious downsides:
1805**
1806** (1) There is zero concurrency. A single reader blocks all other
1807** connections from reading or writing the database.
1808**
1809** (2) An application crash or power loss can leave stale lock files
1810** sitting around that need to be cleared manually.
1811**
1812** Nevertheless, a dotlock is an appropriate locking mode for use if no
1813** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001814**
1815** Dotfile locking works by creating a file in the same directory as the
1816** database and with the same name but with a ".lock" extension added.
1817** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1818** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001819*/
1820
1821/*
1822** The file suffix added to the data base filename in order to create the
1823** lock file.
1824*/
1825#define DOTLOCK_SUFFIX ".lock"
1826
drh7708e972008-11-29 00:56:52 +00001827/*
1828** This routine checks if there is a RESERVED lock held on the specified
1829** file by this or any other process. If such a lock is held, set *pResOut
1830** to a non-zero value otherwise *pResOut is set to zero. The return value
1831** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1832**
1833** In dotfile locking, either a lock exists or it does not. So in this
1834** variation of CheckReservedLock(), *pResOut is set to true if any lock
1835** is held on the file and false if the file is unlocked.
1836*/
drh734c9862008-11-28 15:37:20 +00001837static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1838 int rc = SQLITE_OK;
1839 int reserved = 0;
1840 unixFile *pFile = (unixFile*)id;
1841
1842 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1843
1844 assert( pFile );
1845
1846 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001847 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001848 /* Either this connection or some other connection in the same process
1849 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001850 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001851 }else{
1852 /* The lock is held if and only if the lockfile exists */
1853 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001854 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001855 }
drh308c2a52010-05-14 11:30:18 +00001856 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001857 *pResOut = reserved;
1858 return rc;
1859}
1860
drh7708e972008-11-29 00:56:52 +00001861/*
drh308c2a52010-05-14 11:30:18 +00001862** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001863** of the following:
1864**
1865** (1) SHARED_LOCK
1866** (2) RESERVED_LOCK
1867** (3) PENDING_LOCK
1868** (4) EXCLUSIVE_LOCK
1869**
1870** Sometimes when requesting one lock state, additional lock states
1871** are inserted in between. The locking might fail on one of the later
1872** transitions leaving the lock state different from what it started but
1873** still short of its goal. The following chart shows the allowed
1874** transitions and the inserted intermediate states:
1875**
1876** UNLOCKED -> SHARED
1877** SHARED -> RESERVED
1878** SHARED -> (PENDING) -> EXCLUSIVE
1879** RESERVED -> (PENDING) -> EXCLUSIVE
1880** PENDING -> EXCLUSIVE
1881**
1882** This routine will only increase a lock. Use the sqlite3OsUnlock()
1883** routine to lower a locking level.
1884**
1885** With dotfile locking, we really only support state (4): EXCLUSIVE.
1886** But we track the other locking levels internally.
1887*/
drh308c2a52010-05-14 11:30:18 +00001888static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001889 unixFile *pFile = (unixFile*)id;
1890 int fd;
1891 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001892 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001893
drh7708e972008-11-29 00:56:52 +00001894
1895 /* If we have any lock, then the lock file already exists. All we have
1896 ** to do is adjust our internal record of the lock level.
1897 */
drh308c2a52010-05-14 11:30:18 +00001898 if( pFile->eFileLock > NO_LOCK ){
1899 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001900#if !OS_VXWORKS
1901 /* Always update the timestamp on the old file */
1902 utimes(zLockFile, NULL);
1903#endif
drh7708e972008-11-29 00:56:52 +00001904 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001905 }
1906
1907 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001908 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001909 if( fd<0 ){
1910 /* failed to open/create the file, someone else may have stolen the lock */
1911 int tErrno = errno;
1912 if( EEXIST == tErrno ){
1913 rc = SQLITE_BUSY;
1914 } else {
1915 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1916 if( IS_LOCK_ERROR(rc) ){
1917 pFile->lastErrno = tErrno;
1918 }
1919 }
drh7708e972008-11-29 00:56:52 +00001920 return rc;
drh734c9862008-11-28 15:37:20 +00001921 }
drh0e9365c2011-03-02 02:08:13 +00001922 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001923
1924 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001925 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001926 return rc;
1927}
1928
drh7708e972008-11-29 00:56:52 +00001929/*
drh308c2a52010-05-14 11:30:18 +00001930** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001931** must be either NO_LOCK or SHARED_LOCK.
1932**
1933** If the locking level of the file descriptor is already at or below
1934** the requested locking level, this routine is a no-op.
1935**
1936** When the locking level reaches NO_LOCK, delete the lock file.
1937*/
drh308c2a52010-05-14 11:30:18 +00001938static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001939 unixFile *pFile = (unixFile*)id;
1940 char *zLockFile = (char *)pFile->lockingContext;
1941
1942 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001943 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1944 pFile->eFileLock, getpid()));
1945 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001946
1947 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001948 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001949 return SQLITE_OK;
1950 }
drh7708e972008-11-29 00:56:52 +00001951
1952 /* To downgrade to shared, simply update our internal notion of the
1953 ** lock state. No need to mess with the file on disk.
1954 */
drh308c2a52010-05-14 11:30:18 +00001955 if( eFileLock==SHARED_LOCK ){
1956 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001957 return SQLITE_OK;
1958 }
1959
drh7708e972008-11-29 00:56:52 +00001960 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001961 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001962 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001963 int rc = 0;
1964 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001965 if( ENOENT != tErrno ){
1966 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1967 }
1968 if( IS_LOCK_ERROR(rc) ){
1969 pFile->lastErrno = tErrno;
1970 }
1971 return rc;
1972 }
drh308c2a52010-05-14 11:30:18 +00001973 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001974 return SQLITE_OK;
1975}
1976
1977/*
drh9b35ea62008-11-29 02:20:26 +00001978** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001979*/
1980static int dotlockClose(sqlite3_file *id) {
1981 int rc;
1982 if( id ){
1983 unixFile *pFile = (unixFile*)id;
1984 dotlockUnlock(id, NO_LOCK);
1985 sqlite3_free(pFile->lockingContext);
1986 }
drh734c9862008-11-28 15:37:20 +00001987 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001988 return rc;
1989}
1990/****************** End of the dot-file lock implementation *******************
1991******************************************************************************/
1992
1993/******************************************************************************
1994************************** Begin flock Locking ********************************
1995**
1996** Use the flock() system call to do file locking.
1997**
drh6b9d6dd2008-12-03 19:34:47 +00001998** flock() locking is like dot-file locking in that the various
1999** fine-grain locking levels supported by SQLite are collapsed into
2000** a single exclusive lock. In other words, SHARED, RESERVED, and
2001** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2002** still works when you do this, but concurrency is reduced since
2003** only a single process can be reading the database at a time.
2004**
drh734c9862008-11-28 15:37:20 +00002005** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2006** compiling for VXWORKS.
2007*/
2008#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002009
drh6b9d6dd2008-12-03 19:34:47 +00002010/*
drhff812312011-02-23 13:33:46 +00002011** Retry flock() calls that fail with EINTR
2012*/
2013#ifdef EINTR
2014static int robust_flock(int fd, int op){
2015 int rc;
2016 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2017 return rc;
2018}
2019#else
drh5c819272011-02-23 14:00:12 +00002020# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002021#endif
2022
2023
2024/*
drh6b9d6dd2008-12-03 19:34:47 +00002025** This routine checks if there is a RESERVED lock held on the specified
2026** file by this or any other process. If such a lock is held, set *pResOut
2027** to a non-zero value otherwise *pResOut is set to zero. The return value
2028** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2029*/
drh734c9862008-11-28 15:37:20 +00002030static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2031 int rc = SQLITE_OK;
2032 int reserved = 0;
2033 unixFile *pFile = (unixFile*)id;
2034
2035 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2036
2037 assert( pFile );
2038
2039 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002040 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002041 reserved = 1;
2042 }
2043
2044 /* Otherwise see if some other process holds it. */
2045 if( !reserved ){
2046 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002047 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002048 if( !lrc ){
2049 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002050 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002051 if ( lrc ) {
2052 int tErrno = errno;
2053 /* unlock failed with an error */
2054 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2055 if( IS_LOCK_ERROR(lrc) ){
2056 pFile->lastErrno = tErrno;
2057 rc = lrc;
2058 }
2059 }
2060 } else {
2061 int tErrno = errno;
2062 reserved = 1;
2063 /* someone else might have it reserved */
2064 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2065 if( IS_LOCK_ERROR(lrc) ){
2066 pFile->lastErrno = tErrno;
2067 rc = lrc;
2068 }
2069 }
2070 }
drh308c2a52010-05-14 11:30:18 +00002071 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002072
2073#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2074 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2075 rc = SQLITE_OK;
2076 reserved=1;
2077 }
2078#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2079 *pResOut = reserved;
2080 return rc;
2081}
2082
drh6b9d6dd2008-12-03 19:34:47 +00002083/*
drh308c2a52010-05-14 11:30:18 +00002084** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002085** of the following:
2086**
2087** (1) SHARED_LOCK
2088** (2) RESERVED_LOCK
2089** (3) PENDING_LOCK
2090** (4) EXCLUSIVE_LOCK
2091**
2092** Sometimes when requesting one lock state, additional lock states
2093** are inserted in between. The locking might fail on one of the later
2094** transitions leaving the lock state different from what it started but
2095** still short of its goal. The following chart shows the allowed
2096** transitions and the inserted intermediate states:
2097**
2098** UNLOCKED -> SHARED
2099** SHARED -> RESERVED
2100** SHARED -> (PENDING) -> EXCLUSIVE
2101** RESERVED -> (PENDING) -> EXCLUSIVE
2102** PENDING -> EXCLUSIVE
2103**
2104** flock() only really support EXCLUSIVE locks. We track intermediate
2105** lock states in the sqlite3_file structure, but all locks SHARED or
2106** above are really EXCLUSIVE locks and exclude all other processes from
2107** access the file.
2108**
2109** This routine will only increase a lock. Use the sqlite3OsUnlock()
2110** routine to lower a locking level.
2111*/
drh308c2a52010-05-14 11:30:18 +00002112static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002113 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002114 unixFile *pFile = (unixFile*)id;
2115
2116 assert( pFile );
2117
2118 /* if we already have a lock, it is exclusive.
2119 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002120 if (pFile->eFileLock > NO_LOCK) {
2121 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002122 return SQLITE_OK;
2123 }
2124
2125 /* grab an exclusive lock */
2126
drhff812312011-02-23 13:33:46 +00002127 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002128 int tErrno = errno;
2129 /* didn't get, must be busy */
2130 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2131 if( IS_LOCK_ERROR(rc) ){
2132 pFile->lastErrno = tErrno;
2133 }
2134 } else {
2135 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002136 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002137 }
drh308c2a52010-05-14 11:30:18 +00002138 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2139 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002140#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2141 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2142 rc = SQLITE_BUSY;
2143 }
2144#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2145 return rc;
2146}
2147
drh6b9d6dd2008-12-03 19:34:47 +00002148
2149/*
drh308c2a52010-05-14 11:30:18 +00002150** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002151** must be either NO_LOCK or SHARED_LOCK.
2152**
2153** If the locking level of the file descriptor is already at or below
2154** the requested locking level, this routine is a no-op.
2155*/
drh308c2a52010-05-14 11:30:18 +00002156static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002157 unixFile *pFile = (unixFile*)id;
2158
2159 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002160 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2161 pFile->eFileLock, getpid()));
2162 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002163
2164 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002165 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002166 return SQLITE_OK;
2167 }
2168
2169 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002170 if (eFileLock==SHARED_LOCK) {
2171 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002172 return SQLITE_OK;
2173 }
2174
2175 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002176 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002177 if (rc) {
2178 int r, tErrno = errno;
2179 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2180 if( IS_LOCK_ERROR(r) ){
2181 pFile->lastErrno = tErrno;
2182 }
2183#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2184 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2185 r = SQLITE_BUSY;
2186 }
2187#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2188
2189 return r;
2190 } else {
drh308c2a52010-05-14 11:30:18 +00002191 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002192 return SQLITE_OK;
2193 }
2194}
2195
2196/*
2197** Close a file.
2198*/
2199static int flockClose(sqlite3_file *id) {
2200 if( id ){
2201 flockUnlock(id, NO_LOCK);
2202 }
2203 return closeUnixFile(id);
2204}
2205
2206#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2207
2208/******************* End of the flock lock implementation *********************
2209******************************************************************************/
2210
2211/******************************************************************************
2212************************ Begin Named Semaphore Locking ************************
2213**
2214** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002215**
2216** Semaphore locking is like dot-lock and flock in that it really only
2217** supports EXCLUSIVE locking. Only a single process can read or write
2218** the database file at a time. This reduces potential concurrency, but
2219** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002220*/
2221#if OS_VXWORKS
2222
drh6b9d6dd2008-12-03 19:34:47 +00002223/*
2224** This routine checks if there is a RESERVED lock held on the specified
2225** file by this or any other process. If such a lock is held, set *pResOut
2226** to a non-zero value otherwise *pResOut is set to zero. The return value
2227** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2228*/
drh734c9862008-11-28 15:37:20 +00002229static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2230 int rc = SQLITE_OK;
2231 int reserved = 0;
2232 unixFile *pFile = (unixFile*)id;
2233
2234 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2235
2236 assert( pFile );
2237
2238 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002239 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002240 reserved = 1;
2241 }
2242
2243 /* Otherwise see if some other process holds it. */
2244 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002245 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002246 struct stat statBuf;
2247
2248 if( sem_trywait(pSem)==-1 ){
2249 int tErrno = errno;
2250 if( EAGAIN != tErrno ){
2251 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2252 pFile->lastErrno = tErrno;
2253 } else {
2254 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002255 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002256 }
2257 }else{
2258 /* we could have it if we want it */
2259 sem_post(pSem);
2260 }
2261 }
drh308c2a52010-05-14 11:30:18 +00002262 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002263
2264 *pResOut = reserved;
2265 return rc;
2266}
2267
drh6b9d6dd2008-12-03 19:34:47 +00002268/*
drh308c2a52010-05-14 11:30:18 +00002269** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002270** of the following:
2271**
2272** (1) SHARED_LOCK
2273** (2) RESERVED_LOCK
2274** (3) PENDING_LOCK
2275** (4) EXCLUSIVE_LOCK
2276**
2277** Sometimes when requesting one lock state, additional lock states
2278** are inserted in between. The locking might fail on one of the later
2279** transitions leaving the lock state different from what it started but
2280** still short of its goal. The following chart shows the allowed
2281** transitions and the inserted intermediate states:
2282**
2283** UNLOCKED -> SHARED
2284** SHARED -> RESERVED
2285** SHARED -> (PENDING) -> EXCLUSIVE
2286** RESERVED -> (PENDING) -> EXCLUSIVE
2287** PENDING -> EXCLUSIVE
2288**
2289** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2290** lock states in the sqlite3_file structure, but all locks SHARED or
2291** above are really EXCLUSIVE locks and exclude all other processes from
2292** access the file.
2293**
2294** This routine will only increase a lock. Use the sqlite3OsUnlock()
2295** routine to lower a locking level.
2296*/
drh308c2a52010-05-14 11:30:18 +00002297static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002298 unixFile *pFile = (unixFile*)id;
2299 int fd;
drh8af6c222010-05-14 12:43:01 +00002300 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002301 int rc = SQLITE_OK;
2302
2303 /* if we already have a lock, it is exclusive.
2304 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002305 if (pFile->eFileLock > NO_LOCK) {
2306 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002307 rc = SQLITE_OK;
2308 goto sem_end_lock;
2309 }
2310
2311 /* lock semaphore now but bail out when already locked. */
2312 if( sem_trywait(pSem)==-1 ){
2313 rc = SQLITE_BUSY;
2314 goto sem_end_lock;
2315 }
2316
2317 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002318 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002319
2320 sem_end_lock:
2321 return rc;
2322}
2323
drh6b9d6dd2008-12-03 19:34:47 +00002324/*
drh308c2a52010-05-14 11:30:18 +00002325** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002326** must be either NO_LOCK or SHARED_LOCK.
2327**
2328** If the locking level of the file descriptor is already at or below
2329** the requested locking level, this routine is a no-op.
2330*/
drh308c2a52010-05-14 11:30:18 +00002331static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002332 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002333 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002334
2335 assert( pFile );
2336 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002337 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2338 pFile->eFileLock, getpid()));
2339 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002340
2341 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002342 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002343 return SQLITE_OK;
2344 }
2345
2346 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002347 if (eFileLock==SHARED_LOCK) {
2348 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002349 return SQLITE_OK;
2350 }
2351
2352 /* no, really unlock. */
2353 if ( sem_post(pSem)==-1 ) {
2354 int rc, tErrno = errno;
2355 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2356 if( IS_LOCK_ERROR(rc) ){
2357 pFile->lastErrno = tErrno;
2358 }
2359 return rc;
2360 }
drh308c2a52010-05-14 11:30:18 +00002361 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002362 return SQLITE_OK;
2363}
2364
2365/*
2366 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002367 */
drh734c9862008-11-28 15:37:20 +00002368static int semClose(sqlite3_file *id) {
2369 if( id ){
2370 unixFile *pFile = (unixFile*)id;
2371 semUnlock(id, NO_LOCK);
2372 assert( pFile );
2373 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002374 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002375 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002376 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002377 }
2378 return SQLITE_OK;
2379}
2380
2381#endif /* OS_VXWORKS */
2382/*
2383** Named semaphore locking is only available on VxWorks.
2384**
2385*************** End of the named semaphore lock implementation ****************
2386******************************************************************************/
2387
2388
2389/******************************************************************************
2390*************************** Begin AFP Locking *********************************
2391**
2392** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2393** on Apple Macintosh computers - both OS9 and OSX.
2394**
2395** Third-party implementations of AFP are available. But this code here
2396** only works on OSX.
2397*/
2398
drhd2cb50b2009-01-09 21:41:17 +00002399#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002400/*
2401** The afpLockingContext structure contains all afp lock specific state
2402*/
drhbfe66312006-10-03 17:40:40 +00002403typedef struct afpLockingContext afpLockingContext;
2404struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002405 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002406 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002407};
2408
2409struct ByteRangeLockPB2
2410{
2411 unsigned long long offset; /* offset to first byte to lock */
2412 unsigned long long length; /* nbr of bytes to lock */
2413 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2414 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2415 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2416 int fd; /* file desc to assoc this lock with */
2417};
2418
drhfd131da2007-08-07 17:13:03 +00002419#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002420
drh6b9d6dd2008-12-03 19:34:47 +00002421/*
2422** This is a utility for setting or clearing a bit-range lock on an
2423** AFP filesystem.
2424**
2425** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2426*/
2427static int afpSetLock(
2428 const char *path, /* Name of the file to be locked or unlocked */
2429 unixFile *pFile, /* Open file descriptor on path */
2430 unsigned long long offset, /* First byte to be locked */
2431 unsigned long long length, /* Number of bytes to lock */
2432 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002433){
drh6b9d6dd2008-12-03 19:34:47 +00002434 struct ByteRangeLockPB2 pb;
2435 int err;
drhbfe66312006-10-03 17:40:40 +00002436
2437 pb.unLockFlag = setLockFlag ? 0 : 1;
2438 pb.startEndFlag = 0;
2439 pb.offset = offset;
2440 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002441 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002442
drh308c2a52010-05-14 11:30:18 +00002443 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002444 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002445 offset, length));
drhbfe66312006-10-03 17:40:40 +00002446 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2447 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002448 int rc;
2449 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002450 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2451 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002452#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2453 rc = SQLITE_BUSY;
2454#else
drh734c9862008-11-28 15:37:20 +00002455 rc = sqliteErrorFromPosixError(tErrno,
2456 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002457#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002458 if( IS_LOCK_ERROR(rc) ){
2459 pFile->lastErrno = tErrno;
2460 }
2461 return rc;
drhbfe66312006-10-03 17:40:40 +00002462 } else {
aswift5b1a2562008-08-22 00:22:35 +00002463 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002464 }
2465}
2466
drh6b9d6dd2008-12-03 19:34:47 +00002467/*
2468** This routine checks if there is a RESERVED lock held on the specified
2469** file by this or any other process. If such a lock is held, set *pResOut
2470** to a non-zero value otherwise *pResOut is set to zero. The return value
2471** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2472*/
danielk1977e339d652008-06-28 11:23:00 +00002473static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002474 int rc = SQLITE_OK;
2475 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002476 unixFile *pFile = (unixFile*)id;
2477
aswift5b1a2562008-08-22 00:22:35 +00002478 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2479
2480 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002481 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002482 if( context->reserved ){
2483 *pResOut = 1;
2484 return SQLITE_OK;
2485 }
drh8af6c222010-05-14 12:43:01 +00002486 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002487
2488 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002489 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002490 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002491 }
2492
2493 /* Otherwise see if some other process holds it.
2494 */
aswift5b1a2562008-08-22 00:22:35 +00002495 if( !reserved ){
2496 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002497 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002498 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002499 /* if we succeeded in taking the reserved lock, unlock it to restore
2500 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002501 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002502 } else {
2503 /* if we failed to get the lock then someone else must have it */
2504 reserved = 1;
2505 }
2506 if( IS_LOCK_ERROR(lrc) ){
2507 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002508 }
2509 }
drhbfe66312006-10-03 17:40:40 +00002510
drh7ed97b92010-01-20 13:07:21 +00002511 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002512 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002513
2514 *pResOut = reserved;
2515 return rc;
drhbfe66312006-10-03 17:40:40 +00002516}
2517
drh6b9d6dd2008-12-03 19:34:47 +00002518/*
drh308c2a52010-05-14 11:30:18 +00002519** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002520** of the following:
2521**
2522** (1) SHARED_LOCK
2523** (2) RESERVED_LOCK
2524** (3) PENDING_LOCK
2525** (4) EXCLUSIVE_LOCK
2526**
2527** Sometimes when requesting one lock state, additional lock states
2528** are inserted in between. The locking might fail on one of the later
2529** transitions leaving the lock state different from what it started but
2530** still short of its goal. The following chart shows the allowed
2531** transitions and the inserted intermediate states:
2532**
2533** UNLOCKED -> SHARED
2534** SHARED -> RESERVED
2535** SHARED -> (PENDING) -> EXCLUSIVE
2536** RESERVED -> (PENDING) -> EXCLUSIVE
2537** PENDING -> EXCLUSIVE
2538**
2539** This routine will only increase a lock. Use the sqlite3OsUnlock()
2540** routine to lower a locking level.
2541*/
drh308c2a52010-05-14 11:30:18 +00002542static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002543 int rc = SQLITE_OK;
2544 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002545 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002546 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002547
2548 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002549 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2550 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002551 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002552
drhbfe66312006-10-03 17:40:40 +00002553 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002554 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002555 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002556 */
drh308c2a52010-05-14 11:30:18 +00002557 if( pFile->eFileLock>=eFileLock ){
2558 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2559 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002560 return SQLITE_OK;
2561 }
2562
2563 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002564 ** (1) We never move from unlocked to anything higher than shared lock.
2565 ** (2) SQLite never explicitly requests a pendig lock.
2566 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002567 */
drh308c2a52010-05-14 11:30:18 +00002568 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2569 assert( eFileLock!=PENDING_LOCK );
2570 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002571
drh8af6c222010-05-14 12:43:01 +00002572 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002573 */
drh6c7d5c52008-11-21 20:32:33 +00002574 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002575 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002576
2577 /* If some thread using this PID has a lock via a different unixFile*
2578 ** handle that precludes the requested lock, return BUSY.
2579 */
drh8af6c222010-05-14 12:43:01 +00002580 if( (pFile->eFileLock!=pInode->eFileLock &&
2581 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002582 ){
2583 rc = SQLITE_BUSY;
2584 goto afp_end_lock;
2585 }
2586
2587 /* If a SHARED lock is requested, and some thread using this PID already
2588 ** has a SHARED or RESERVED lock, then increment reference counts and
2589 ** return SQLITE_OK.
2590 */
drh308c2a52010-05-14 11:30:18 +00002591 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002592 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002593 assert( eFileLock==SHARED_LOCK );
2594 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002595 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002596 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002597 pInode->nShared++;
2598 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002599 goto afp_end_lock;
2600 }
drhbfe66312006-10-03 17:40:40 +00002601
2602 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002603 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2604 ** be released.
2605 */
drh308c2a52010-05-14 11:30:18 +00002606 if( eFileLock==SHARED_LOCK
2607 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002608 ){
2609 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002610 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002611 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002612 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002613 goto afp_end_lock;
2614 }
2615 }
2616
2617 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002618 ** operating system calls for the specified lock.
2619 */
drh308c2a52010-05-14 11:30:18 +00002620 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002621 int lrc1, lrc2, lrc1Errno;
2622 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002623
drh8af6c222010-05-14 12:43:01 +00002624 assert( pInode->nShared==0 );
2625 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002626
2627 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002628 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002629 /* note that the quality of the randomness doesn't matter that much */
2630 lk = random();
drh8af6c222010-05-14 12:43:01 +00002631 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002632 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002633 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002634 if( IS_LOCK_ERROR(lrc1) ){
2635 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002636 }
aswift5b1a2562008-08-22 00:22:35 +00002637 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002638 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002639
aswift5b1a2562008-08-22 00:22:35 +00002640 if( IS_LOCK_ERROR(lrc1) ) {
2641 pFile->lastErrno = lrc1Errno;
2642 rc = lrc1;
2643 goto afp_end_lock;
2644 } else if( IS_LOCK_ERROR(lrc2) ){
2645 rc = lrc2;
2646 goto afp_end_lock;
2647 } else if( lrc1 != SQLITE_OK ) {
2648 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002649 } else {
drh308c2a52010-05-14 11:30:18 +00002650 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002651 pInode->nLock++;
2652 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002653 }
drh8af6c222010-05-14 12:43:01 +00002654 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002655 /* We are trying for an exclusive lock but another thread in this
2656 ** same process is still holding a shared lock. */
2657 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002658 }else{
2659 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2660 ** assumed that there is a SHARED or greater lock on the file
2661 ** already.
2662 */
2663 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002664 assert( 0!=pFile->eFileLock );
2665 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002666 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002667 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002668 if( !failed ){
2669 context->reserved = 1;
2670 }
drhbfe66312006-10-03 17:40:40 +00002671 }
drh308c2a52010-05-14 11:30:18 +00002672 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002673 /* Acquire an EXCLUSIVE lock */
2674
2675 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002676 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002677 */
drh6b9d6dd2008-12-03 19:34:47 +00002678 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002679 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002680 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002681 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002682 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002683 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002684 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002685 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002686 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2687 ** a critical I/O error
2688 */
2689 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2690 SQLITE_IOERR_LOCK;
2691 goto afp_end_lock;
2692 }
2693 }else{
aswift5b1a2562008-08-22 00:22:35 +00002694 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002695 }
2696 }
aswift5b1a2562008-08-22 00:22:35 +00002697 if( failed ){
2698 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002699 }
2700 }
2701
2702 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002703 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002704 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002705 }else if( eFileLock==EXCLUSIVE_LOCK ){
2706 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002707 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002708 }
2709
2710afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002711 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002712 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2713 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002714 return rc;
2715}
2716
2717/*
drh308c2a52010-05-14 11:30:18 +00002718** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002719** must be either NO_LOCK or SHARED_LOCK.
2720**
2721** If the locking level of the file descriptor is already at or below
2722** the requested locking level, this routine is a no-op.
2723*/
drh308c2a52010-05-14 11:30:18 +00002724static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002725 int rc = SQLITE_OK;
2726 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002727 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002728 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2729 int skipShared = 0;
2730#ifdef SQLITE_TEST
2731 int h = pFile->h;
2732#endif
drhbfe66312006-10-03 17:40:40 +00002733
2734 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002735 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002736 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002737 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002738
drh308c2a52010-05-14 11:30:18 +00002739 assert( eFileLock<=SHARED_LOCK );
2740 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002741 return SQLITE_OK;
2742 }
drh6c7d5c52008-11-21 20:32:33 +00002743 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002744 pInode = pFile->pInode;
2745 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002746 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002747 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002748 SimulateIOErrorBenign(1);
2749 SimulateIOError( h=(-1) )
2750 SimulateIOErrorBenign(0);
2751
2752#ifndef NDEBUG
2753 /* When reducing a lock such that other processes can start
2754 ** reading the database file again, make sure that the
2755 ** transaction counter was updated if any part of the database
2756 ** file changed. If the transaction counter is not updated,
2757 ** other connections to the same file might not realize that
2758 ** the file has changed and hence might not know to flush their
2759 ** cache. The use of a stale cache can lead to database corruption.
2760 */
2761 assert( pFile->inNormalWrite==0
2762 || pFile->dbUpdate==0
2763 || pFile->transCntrChng==1 );
2764 pFile->inNormalWrite = 0;
2765#endif
aswiftaebf4132008-11-21 00:10:35 +00002766
drh308c2a52010-05-14 11:30:18 +00002767 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002768 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002769 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002770 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002771 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002772 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2773 } else {
2774 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002775 }
2776 }
drh308c2a52010-05-14 11:30:18 +00002777 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002778 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002779 }
drh308c2a52010-05-14 11:30:18 +00002780 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002781 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2782 if( !rc ){
2783 context->reserved = 0;
2784 }
aswiftaebf4132008-11-21 00:10:35 +00002785 }
drh8af6c222010-05-14 12:43:01 +00002786 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2787 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002788 }
aswiftaebf4132008-11-21 00:10:35 +00002789 }
drh308c2a52010-05-14 11:30:18 +00002790 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002791
drh7ed97b92010-01-20 13:07:21 +00002792 /* Decrement the shared lock counter. Release the lock using an
2793 ** OS call only when all threads in this same process have released
2794 ** the lock.
2795 */
drh8af6c222010-05-14 12:43:01 +00002796 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2797 pInode->nShared--;
2798 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002799 SimulateIOErrorBenign(1);
2800 SimulateIOError( h=(-1) )
2801 SimulateIOErrorBenign(0);
2802 if( !skipShared ){
2803 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2804 }
2805 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002806 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002807 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002808 }
2809 }
2810 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002811 pInode->nLock--;
2812 assert( pInode->nLock>=0 );
2813 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002814 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002815 }
2816 }
drhbfe66312006-10-03 17:40:40 +00002817 }
drh7ed97b92010-01-20 13:07:21 +00002818
drh6c7d5c52008-11-21 20:32:33 +00002819 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002820 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002821 return rc;
2822}
2823
2824/*
drh339eb0b2008-03-07 15:34:11 +00002825** Close a file & cleanup AFP specific locking context
2826*/
danielk1977e339d652008-06-28 11:23:00 +00002827static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002828 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002829 if( id ){
2830 unixFile *pFile = (unixFile*)id;
2831 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002832 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002833 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002834 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002835 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002836 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002837 ** the last lock is cleared.
2838 */
dan08da86a2009-08-21 17:18:03 +00002839 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002840 }
danb0ac3e32010-06-16 10:55:42 +00002841 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002842 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002843 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002844 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002845 }
drh7ed97b92010-01-20 13:07:21 +00002846 return rc;
drhbfe66312006-10-03 17:40:40 +00002847}
2848
drhd2cb50b2009-01-09 21:41:17 +00002849#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002850/*
2851** The code above is the AFP lock implementation. The code is specific
2852** to MacOSX and does not work on other unix platforms. No alternative
2853** is available. If you don't compile for a mac, then the "unix-afp"
2854** VFS is not available.
2855**
2856********************* End of the AFP lock implementation **********************
2857******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002858
drh7ed97b92010-01-20 13:07:21 +00002859/******************************************************************************
2860*************************** Begin NFS Locking ********************************/
2861
2862#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2863/*
drh308c2a52010-05-14 11:30:18 +00002864 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002865 ** must be either NO_LOCK or SHARED_LOCK.
2866 **
2867 ** If the locking level of the file descriptor is already at or below
2868 ** the requested locking level, this routine is a no-op.
2869 */
drh308c2a52010-05-14 11:30:18 +00002870static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002871 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002872}
2873
2874#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2875/*
2876** The code above is the NFS lock implementation. The code is specific
2877** to MacOSX and does not work on other unix platforms. No alternative
2878** is available.
2879**
2880********************* End of the NFS lock implementation **********************
2881******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002882
2883/******************************************************************************
2884**************** Non-locking sqlite3_file methods *****************************
2885**
2886** The next division contains implementations for all methods of the
2887** sqlite3_file object other than the locking methods. The locking
2888** methods were defined in divisions above (one locking method per
2889** division). Those methods that are common to all locking modes
2890** are gather together into this division.
2891*/
drhbfe66312006-10-03 17:40:40 +00002892
2893/*
drh734c9862008-11-28 15:37:20 +00002894** Seek to the offset passed as the second argument, then read cnt
2895** bytes into pBuf. Return the number of bytes actually read.
2896**
2897** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2898** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2899** one system to another. Since SQLite does not define USE_PREAD
2900** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2901** See tickets #2741 and #2681.
2902**
2903** To avoid stomping the errno value on a failed read the lastErrno value
2904** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002905*/
drh734c9862008-11-28 15:37:20 +00002906static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2907 int got;
drh7ed97b92010-01-20 13:07:21 +00002908#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002909 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002910#endif
drh734c9862008-11-28 15:37:20 +00002911 TIMER_START;
2912#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002913 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002914 SimulateIOError( got = -1 );
2915#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002916 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002917 SimulateIOError( got = -1 );
2918#else
2919 newOffset = lseek(id->h, offset, SEEK_SET);
2920 SimulateIOError( newOffset-- );
2921 if( newOffset!=offset ){
2922 if( newOffset == -1 ){
2923 ((unixFile*)id)->lastErrno = errno;
2924 }else{
2925 ((unixFile*)id)->lastErrno = 0;
2926 }
2927 return -1;
2928 }
drhe562be52011-03-02 18:01:10 +00002929 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002930#endif
2931 TIMER_END;
2932 if( got<0 ){
2933 ((unixFile*)id)->lastErrno = errno;
2934 }
drh308c2a52010-05-14 11:30:18 +00002935 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002936 return got;
drhbfe66312006-10-03 17:40:40 +00002937}
2938
2939/*
drh734c9862008-11-28 15:37:20 +00002940** Read data from a file into a buffer. Return SQLITE_OK if all
2941** bytes were read successfully and SQLITE_IOERR if anything goes
2942** wrong.
drh339eb0b2008-03-07 15:34:11 +00002943*/
drh734c9862008-11-28 15:37:20 +00002944static int unixRead(
2945 sqlite3_file *id,
2946 void *pBuf,
2947 int amt,
2948 sqlite3_int64 offset
2949){
dan08da86a2009-08-21 17:18:03 +00002950 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002951 int got;
2952 assert( id );
drh08c6d442009-02-09 17:34:07 +00002953
dan08da86a2009-08-21 17:18:03 +00002954 /* If this is a database file (not a journal, master-journal or temp
2955 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002956#if 0
dane946c392009-08-22 11:39:46 +00002957 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002958 || offset>=PENDING_BYTE+512
2959 || offset+amt<=PENDING_BYTE
2960 );
dan7c246102010-04-12 19:00:29 +00002961#endif
drh08c6d442009-02-09 17:34:07 +00002962
dan08da86a2009-08-21 17:18:03 +00002963 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002964 if( got==amt ){
2965 return SQLITE_OK;
2966 }else if( got<0 ){
2967 /* lastErrno set by seekAndRead */
2968 return SQLITE_IOERR_READ;
2969 }else{
dan08da86a2009-08-21 17:18:03 +00002970 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002971 /* Unread parts of the buffer must be zero-filled */
2972 memset(&((char*)pBuf)[got], 0, amt-got);
2973 return SQLITE_IOERR_SHORT_READ;
2974 }
2975}
2976
2977/*
2978** Seek to the offset in id->offset then read cnt bytes into pBuf.
2979** Return the number of bytes actually read. Update the offset.
2980**
2981** To avoid stomping the errno value on a failed write the lastErrno value
2982** is set before returning.
2983*/
2984static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2985 int got;
drh7ed97b92010-01-20 13:07:21 +00002986#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002987 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002988#endif
drh734c9862008-11-28 15:37:20 +00002989 TIMER_START;
2990#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002991 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002992#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002993 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002994#else
2995 newOffset = lseek(id->h, offset, SEEK_SET);
2996 if( newOffset!=offset ){
2997 if( newOffset == -1 ){
2998 ((unixFile*)id)->lastErrno = errno;
2999 }else{
3000 ((unixFile*)id)->lastErrno = 0;
3001 }
3002 return -1;
3003 }
drhe562be52011-03-02 18:01:10 +00003004 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003005#endif
3006 TIMER_END;
3007 if( got<0 ){
3008 ((unixFile*)id)->lastErrno = errno;
3009 }
3010
drh308c2a52010-05-14 11:30:18 +00003011 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003012 return got;
3013}
3014
3015
3016/*
3017** Write data from a buffer into a file. Return SQLITE_OK on success
3018** or some other error code on failure.
3019*/
3020static int unixWrite(
3021 sqlite3_file *id,
3022 const void *pBuf,
3023 int amt,
3024 sqlite3_int64 offset
3025){
dan08da86a2009-08-21 17:18:03 +00003026 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003027 int wrote = 0;
3028 assert( id );
3029 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003030
dan08da86a2009-08-21 17:18:03 +00003031 /* If this is a database file (not a journal, master-journal or temp
3032 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003033#if 0
dane946c392009-08-22 11:39:46 +00003034 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003035 || offset>=PENDING_BYTE+512
3036 || offset+amt<=PENDING_BYTE
3037 );
dan7c246102010-04-12 19:00:29 +00003038#endif
drh08c6d442009-02-09 17:34:07 +00003039
drh8f941bc2009-01-14 23:03:40 +00003040#ifndef NDEBUG
3041 /* If we are doing a normal write to a database file (as opposed to
3042 ** doing a hot-journal rollback or a write to some file other than a
3043 ** normal database file) then record the fact that the database
3044 ** has changed. If the transaction counter is modified, record that
3045 ** fact too.
3046 */
dan08da86a2009-08-21 17:18:03 +00003047 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003048 pFile->dbUpdate = 1; /* The database has been modified */
3049 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003050 int rc;
drh8f941bc2009-01-14 23:03:40 +00003051 char oldCntr[4];
3052 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003053 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003054 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003055 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003056 pFile->transCntrChng = 1; /* The transaction counter has changed */
3057 }
3058 }
3059 }
3060#endif
3061
dan08da86a2009-08-21 17:18:03 +00003062 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003063 amt -= wrote;
3064 offset += wrote;
3065 pBuf = &((char*)pBuf)[wrote];
3066 }
3067 SimulateIOError(( wrote=(-1), amt=1 ));
3068 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003069
drh734c9862008-11-28 15:37:20 +00003070 if( amt>0 ){
3071 if( wrote<0 ){
3072 /* lastErrno set by seekAndWrite */
3073 return SQLITE_IOERR_WRITE;
3074 }else{
dan08da86a2009-08-21 17:18:03 +00003075 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003076 return SQLITE_FULL;
3077 }
3078 }
dan6e09d692010-07-27 18:34:15 +00003079
drh734c9862008-11-28 15:37:20 +00003080 return SQLITE_OK;
3081}
3082
3083#ifdef SQLITE_TEST
3084/*
3085** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003086** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003087*/
3088int sqlite3_sync_count = 0;
3089int sqlite3_fullsync_count = 0;
3090#endif
3091
3092/*
drh89240432009-03-25 01:06:01 +00003093** We do not trust systems to provide a working fdatasync(). Some do.
3094** Others do no. To be safe, we will stick with the (slower) fsync().
3095** If you know that your system does support fdatasync() correctly,
3096** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003097*/
drh89240432009-03-25 01:06:01 +00003098#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003099# define fdatasync fsync
3100#endif
3101
3102/*
3103** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3104** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3105** only available on Mac OS X. But that could change.
3106*/
3107#ifdef F_FULLFSYNC
3108# define HAVE_FULLFSYNC 1
3109#else
3110# define HAVE_FULLFSYNC 0
3111#endif
3112
3113
3114/*
3115** The fsync() system call does not work as advertised on many
3116** unix systems. The following procedure is an attempt to make
3117** it work better.
3118**
3119** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3120** for testing when we want to run through the test suite quickly.
3121** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3122** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3123** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003124**
3125** SQLite sets the dataOnly flag if the size of the file is unchanged.
3126** The idea behind dataOnly is that it should only write the file content
3127** to disk, not the inode. We only set dataOnly if the file size is
3128** unchanged since the file size is part of the inode. However,
3129** Ted Ts'o tells us that fdatasync() will also write the inode if the
3130** file size has changed. The only real difference between fdatasync()
3131** and fsync(), Ted tells us, is that fdatasync() will not flush the
3132** inode if the mtime or owner or other inode attributes have changed.
3133** We only care about the file size, not the other file attributes, so
3134** as far as SQLite is concerned, an fdatasync() is always adequate.
3135** So, we always use fdatasync() if it is available, regardless of
3136** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003137*/
3138static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003139 int rc;
drh734c9862008-11-28 15:37:20 +00003140
3141 /* The following "ifdef/elif/else/" block has the same structure as
3142 ** the one below. It is replicated here solely to avoid cluttering
3143 ** up the real code with the UNUSED_PARAMETER() macros.
3144 */
3145#ifdef SQLITE_NO_SYNC
3146 UNUSED_PARAMETER(fd);
3147 UNUSED_PARAMETER(fullSync);
3148 UNUSED_PARAMETER(dataOnly);
3149#elif HAVE_FULLFSYNC
3150 UNUSED_PARAMETER(dataOnly);
3151#else
3152 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003153 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003154#endif
3155
3156 /* Record the number of times that we do a normal fsync() and
3157 ** FULLSYNC. This is used during testing to verify that this procedure
3158 ** gets called with the correct arguments.
3159 */
3160#ifdef SQLITE_TEST
3161 if( fullSync ) sqlite3_fullsync_count++;
3162 sqlite3_sync_count++;
3163#endif
3164
3165 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3166 ** no-op
3167 */
3168#ifdef SQLITE_NO_SYNC
3169 rc = SQLITE_OK;
3170#elif HAVE_FULLFSYNC
3171 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003172 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003173 }else{
3174 rc = 1;
3175 }
3176 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003177 ** It shouldn't be possible for fullfsync to fail on the local
3178 ** file system (on OSX), so failure indicates that FULLFSYNC
3179 ** isn't supported for this file system. So, attempt an fsync
3180 ** and (for now) ignore the overhead of a superfluous fcntl call.
3181 ** It'd be better to detect fullfsync support once and avoid
3182 ** the fcntl call every time sync is called.
3183 */
drh734c9862008-11-28 15:37:20 +00003184 if( rc ) rc = fsync(fd);
3185
drh7ed97b92010-01-20 13:07:21 +00003186#elif defined(__APPLE__)
3187 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3188 ** so currently we default to the macro that redefines fdatasync to fsync
3189 */
3190 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003191#else
drh0b647ff2009-03-21 14:41:04 +00003192 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003193#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003194 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003195 rc = fsync(fd);
3196 }
drh0b647ff2009-03-21 14:41:04 +00003197#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003198#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3199
3200 if( OS_VXWORKS && rc!= -1 ){
3201 rc = 0;
3202 }
chw97185482008-11-17 08:05:31 +00003203 return rc;
drhbfe66312006-10-03 17:40:40 +00003204}
3205
drh734c9862008-11-28 15:37:20 +00003206/*
3207** Make sure all writes to a particular file are committed to disk.
3208**
3209** If dataOnly==0 then both the file itself and its metadata (file
3210** size, access time, etc) are synced. If dataOnly!=0 then only the
3211** file data is synced.
3212**
3213** Under Unix, also make sure that the directory entry for the file
3214** has been created by fsync-ing the directory that contains the file.
3215** If we do not do this and we encounter a power failure, the directory
3216** entry for the journal might not exist after we reboot. The next
3217** SQLite to access the file will not know that the journal exists (because
3218** the directory entry for the journal was never created) and the transaction
3219** will not roll back - possibly leading to database corruption.
3220*/
3221static int unixSync(sqlite3_file *id, int flags){
3222 int rc;
3223 unixFile *pFile = (unixFile*)id;
3224
3225 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3226 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3227
3228 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3229 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3230 || (flags&0x0F)==SQLITE_SYNC_FULL
3231 );
3232
3233 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3234 ** line is to test that doing so does not cause any problems.
3235 */
3236 SimulateDiskfullError( return SQLITE_FULL );
3237
3238 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003239 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003240 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3241 SimulateIOError( rc=1 );
3242 if( rc ){
3243 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003244 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003245 }
3246 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003247 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3248 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003249#ifndef SQLITE_DISABLE_DIRSYNC
3250 /* The directory sync is only attempted if full_fsync is
3251 ** turned off or unavailable. If a full_fsync occurred above,
3252 ** then the directory sync is superfluous.
3253 */
3254 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3255 /*
3256 ** We have received multiple reports of fsync() returning
3257 ** errors when applied to directories on certain file systems.
3258 ** A failed directory sync is not a big deal. So it seems
3259 ** better to ignore the error. Ticket #1657
3260 */
3261 /* pFile->lastErrno = errno; */
3262 /* return SQLITE_IOERR; */
3263 }
3264#endif
drh0e9365c2011-03-02 02:08:13 +00003265 /* Only need to sync once, so close the directory when we are done */
3266 robust_close(pFile, pFile->dirfd, __LINE__);
3267 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003268 }
3269 return rc;
3270}
3271
3272/*
3273** Truncate an open file to a specified size
3274*/
3275static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003276 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003277 int rc;
dan6e09d692010-07-27 18:34:15 +00003278 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003279 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003280
3281 /* If the user has configured a chunk-size for this file, truncate the
3282 ** file so that it consists of an integer number of chunks (i.e. the
3283 ** actual file size after the operation may be larger than the requested
3284 ** size).
3285 */
3286 if( pFile->szChunk ){
3287 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3288 }
3289
drhff812312011-02-23 13:33:46 +00003290 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003291 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003292 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003293 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003294 }else{
drh3313b142009-11-06 04:13:18 +00003295#ifndef NDEBUG
3296 /* If we are doing a normal write to a database file (as opposed to
3297 ** doing a hot-journal rollback or a write to some file other than a
3298 ** normal database file) and we truncate the file to zero length,
3299 ** that effectively updates the change counter. This might happen
3300 ** when restoring a database using the backup API from a zero-length
3301 ** source.
3302 */
dan6e09d692010-07-27 18:34:15 +00003303 if( pFile->inNormalWrite && nByte==0 ){
3304 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003305 }
3306#endif
3307
drh734c9862008-11-28 15:37:20 +00003308 return SQLITE_OK;
3309 }
3310}
3311
3312/*
3313** Determine the current size of a file in bytes
3314*/
3315static int unixFileSize(sqlite3_file *id, i64 *pSize){
3316 int rc;
3317 struct stat buf;
3318 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003319 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003320 SimulateIOError( rc=1 );
3321 if( rc!=0 ){
3322 ((unixFile*)id)->lastErrno = errno;
3323 return SQLITE_IOERR_FSTAT;
3324 }
3325 *pSize = buf.st_size;
3326
drh8af6c222010-05-14 12:43:01 +00003327 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003328 ** writes a single byte into that file in order to work around a bug
3329 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3330 ** layers, we need to report this file size as zero even though it is
3331 ** really 1. Ticket #3260.
3332 */
3333 if( *pSize==1 ) *pSize = 0;
3334
3335
3336 return SQLITE_OK;
3337}
3338
drhd2cb50b2009-01-09 21:41:17 +00003339#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003340/*
3341** Handler for proxy-locking file-control verbs. Defined below in the
3342** proxying locking division.
3343*/
3344static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003345#endif
drh715ff302008-12-03 22:32:44 +00003346
dan502019c2010-07-28 14:26:17 +00003347/*
3348** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3349** file-control operation.
3350**
3351** If the user has configured a chunk-size for this file, it could be
3352** that the file needs to be extended at this point. Otherwise, the
3353** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3354*/
3355static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3356 if( pFile->szChunk ){
3357 i64 nSize; /* Required file size */
3358 struct stat buf; /* Used to hold return values of fstat() */
3359
drh99ab3b12011-03-02 15:09:07 +00003360 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003361
3362 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3363 if( nSize>(i64)buf.st_size ){
3364#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003365 int rc;
3366 do{
drhe562be52011-03-02 18:01:10 +00003367 rc = osFallocate(pFile->.h, buf.st_size, nSize-buf.st_size;
drhff812312011-02-23 13:33:46 +00003368 }while( rc<0 && errno=EINTR );
3369 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003370#else
3371 /* If the OS does not have posix_fallocate(), fake it. First use
3372 ** ftruncate() to set the file size, then write a single byte to
3373 ** the last byte in each block within the extended region. This
3374 ** is the same technique used by glibc to implement posix_fallocate()
3375 ** on systems that do not have a real fallocate() system call.
3376 */
3377 int nBlk = buf.st_blksize; /* File-system block size */
3378 i64 iWrite; /* Next offset to write to */
3379 int nWrite; /* Return value from seekAndWrite() */
3380
drhff812312011-02-23 13:33:46 +00003381 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003382 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003383 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003384 }
3385 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3386 do {
3387 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3388 iWrite += nBlk;
3389 } while( nWrite==1 && iWrite<nSize );
3390 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3391#endif
3392 }
3393 }
3394
3395 return SQLITE_OK;
3396}
danielk1977ad94b582007-08-20 06:44:22 +00003397
danielk1977e3026632004-06-22 11:29:02 +00003398/*
drh9e33c2c2007-08-31 18:34:59 +00003399** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003400*/
drhcc6bb3e2007-08-31 16:11:35 +00003401static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003402 switch( op ){
3403 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003404 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003405 return SQLITE_OK;
3406 }
drh7708e972008-11-29 00:56:52 +00003407 case SQLITE_LAST_ERRNO: {
3408 *(int*)pArg = ((unixFile*)id)->lastErrno;
3409 return SQLITE_OK;
3410 }
dan6e09d692010-07-27 18:34:15 +00003411 case SQLITE_FCNTL_CHUNK_SIZE: {
3412 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003413 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003414 }
drh9ff27ec2010-05-19 19:26:05 +00003415 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003416 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003417 }
drh8f941bc2009-01-14 23:03:40 +00003418#ifndef NDEBUG
3419 /* The pager calls this method to signal that it has done
3420 ** a rollback and that the database is therefore unchanged and
3421 ** it hence it is OK for the transaction change counter to be
3422 ** unchanged.
3423 */
3424 case SQLITE_FCNTL_DB_UNCHANGED: {
3425 ((unixFile*)id)->dbUpdate = 0;
3426 return SQLITE_OK;
3427 }
3428#endif
drhd2cb50b2009-01-09 21:41:17 +00003429#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003430 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003431 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003432 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003433 }
drhd2cb50b2009-01-09 21:41:17 +00003434#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003435 case SQLITE_FCNTL_SYNC_OMITTED: {
3436 return SQLITE_OK; /* A no-op */
3437 }
drh9e33c2c2007-08-31 18:34:59 +00003438 }
drh0b52b7d2011-01-26 19:46:22 +00003439 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003440}
3441
3442/*
danielk1977a3d4c882007-03-23 10:08:38 +00003443** Return the sector size in bytes of the underlying block device for
3444** the specified file. This is almost always 512 bytes, but may be
3445** larger for some devices.
3446**
3447** SQLite code assumes this function cannot fail. It also assumes that
3448** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003449** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003450** same for both.
3451*/
danielk1977397d65f2008-11-19 11:35:39 +00003452static int unixSectorSize(sqlite3_file *NotUsed){
3453 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003454 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003455}
3456
danielk197790949c22007-08-17 16:50:38 +00003457/*
danielk1977397d65f2008-11-19 11:35:39 +00003458** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003459*/
danielk1977397d65f2008-11-19 11:35:39 +00003460static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3461 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003462 return 0;
3463}
3464
drhd9e5c4f2010-05-12 18:01:39 +00003465#ifndef SQLITE_OMIT_WAL
3466
3467
3468/*
drhd91c68f2010-05-14 14:52:25 +00003469** Object used to represent an shared memory buffer.
3470**
3471** When multiple threads all reference the same wal-index, each thread
3472** has its own unixShm object, but they all point to a single instance
3473** of this unixShmNode object. In other words, each wal-index is opened
3474** only once per process.
3475**
3476** Each unixShmNode object is connected to a single unixInodeInfo object.
3477** We could coalesce this object into unixInodeInfo, but that would mean
3478** every open file that does not use shared memory (in other words, most
3479** open files) would have to carry around this extra information. So
3480** the unixInodeInfo object contains a pointer to this unixShmNode object
3481** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003482**
3483** unixMutexHeld() must be true when creating or destroying
3484** this object or while reading or writing the following fields:
3485**
3486** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003487**
3488** The following fields are read-only after the object is created:
3489**
3490** fid
3491** zFilename
3492**
drhd91c68f2010-05-14 14:52:25 +00003493** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003494** unixMutexHeld() is true when reading or writing any other field
3495** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003496*/
drhd91c68f2010-05-14 14:52:25 +00003497struct unixShmNode {
3498 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003499 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003500 char *zFilename; /* Name of the mmapped file */
3501 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003502 int szRegion; /* Size of shared-memory regions */
3503 int nRegion; /* Size of array apRegion */
3504 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003505 int nRef; /* Number of unixShm objects pointing to this */
3506 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003507#ifdef SQLITE_DEBUG
3508 u8 exclMask; /* Mask of exclusive locks held */
3509 u8 sharedMask; /* Mask of shared locks held */
3510 u8 nextShmId; /* Next available unixShm.id value */
3511#endif
3512};
3513
3514/*
drhd9e5c4f2010-05-12 18:01:39 +00003515** Structure used internally by this VFS to record the state of an
3516** open shared memory connection.
3517**
drhd91c68f2010-05-14 14:52:25 +00003518** The following fields are initialized when this object is created and
3519** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003520**
drhd91c68f2010-05-14 14:52:25 +00003521** unixShm.pFile
3522** unixShm.id
3523**
3524** All other fields are read/write. The unixShm.pFile->mutex must be held
3525** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003526*/
3527struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003528 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3529 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003530 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003531 u16 sharedMask; /* Mask of shared locks held */
3532 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003533#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003534 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003535#endif
3536};
3537
3538/*
drhd9e5c4f2010-05-12 18:01:39 +00003539** Constants used for locking
3540*/
drhbd9676c2010-06-23 17:58:38 +00003541#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003542#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003543
drhd9e5c4f2010-05-12 18:01:39 +00003544/*
drh73b64e42010-05-30 19:55:15 +00003545** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003546**
3547** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3548** otherwise.
3549*/
3550static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003551 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3552 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003553 int ofst, /* First byte of the locking range */
3554 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003555){
3556 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003557 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003558
drhd91c68f2010-05-14 14:52:25 +00003559 /* Access to the unixShmNode object is serialized by the caller */
3560 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003561
drh73b64e42010-05-30 19:55:15 +00003562 /* Shared locks never span more than one byte */
3563 assert( n==1 || lockType!=F_RDLCK );
3564
3565 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003566 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003567
drh3cb93392011-03-12 18:10:44 +00003568 if( pShmNode->h>=0 ){
3569 /* Initialize the locking parameters */
3570 memset(&f, 0, sizeof(f));
3571 f.l_type = lockType;
3572 f.l_whence = SEEK_SET;
3573 f.l_start = ofst;
3574 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003575
drh3cb93392011-03-12 18:10:44 +00003576 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3577 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3578 }
drhd9e5c4f2010-05-12 18:01:39 +00003579
3580 /* Update the global lock state and do debug tracing */
3581#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003582 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003583 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003584 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003585 if( rc==SQLITE_OK ){
3586 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003587 OSTRACE(("unlock %d ok", ofst));
3588 pShmNode->exclMask &= ~mask;
3589 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003590 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003591 OSTRACE(("read-lock %d ok", ofst));
3592 pShmNode->exclMask &= ~mask;
3593 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003594 }else{
3595 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003596 OSTRACE(("write-lock %d ok", ofst));
3597 pShmNode->exclMask |= mask;
3598 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003599 }
3600 }else{
3601 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003602 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003603 }else if( lockType==F_RDLCK ){
3604 OSTRACE(("read-lock failed"));
3605 }else{
3606 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003607 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003608 }
3609 }
drh20e1f082010-05-31 16:10:12 +00003610 OSTRACE((" - afterwards %03x,%03x\n",
3611 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003612 }
drhd9e5c4f2010-05-12 18:01:39 +00003613#endif
3614
3615 return rc;
3616}
3617
drhd9e5c4f2010-05-12 18:01:39 +00003618
3619/*
drhd91c68f2010-05-14 14:52:25 +00003620** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003621**
3622** This is not a VFS shared-memory method; it is a utility function called
3623** by VFS shared-memory methods.
3624*/
drhd91c68f2010-05-14 14:52:25 +00003625static void unixShmPurge(unixFile *pFd){
3626 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003627 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003628 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003629 int i;
drhd91c68f2010-05-14 14:52:25 +00003630 assert( p->pInode==pFd->pInode );
3631 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003632 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003633 if( p->h>=0 ){
3634 munmap(p->apRegion[i], p->szRegion);
3635 }else{
3636 sqlite3_free(p->apRegion[i]);
3637 }
dan13a3cb82010-06-11 19:04:21 +00003638 }
dan18801912010-06-14 14:07:50 +00003639 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003640 if( p->h>=0 ){
3641 robust_close(pFd, p->h, __LINE__);
3642 p->h = -1;
3643 }
drhd91c68f2010-05-14 14:52:25 +00003644 p->pInode->pShmNode = 0;
3645 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003646 }
3647}
3648
3649/*
danda9fe0c2010-07-13 18:44:03 +00003650** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003651** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003652**
drh7234c6d2010-06-19 15:10:09 +00003653** The file used to implement shared-memory is in the same directory
3654** as the open database file and has the same name as the open database
3655** file with the "-shm" suffix added. For example, if the database file
3656** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003657** for shared memory will be called "/home/user1/config.db-shm".
3658**
3659** Another approach to is to use files in /dev/shm or /dev/tmp or an
3660** some other tmpfs mount. But if a file in a different directory
3661** from the database file is used, then differing access permissions
3662** or a chroot() might cause two different processes on the same
3663** database to end up using different files for shared memory -
3664** meaning that their memory would not really be shared - resulting
3665** in database corruption. Nevertheless, this tmpfs file usage
3666** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3667** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3668** option results in an incompatible build of SQLite; builds of SQLite
3669** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3670** same database file at the same time, database corruption will likely
3671** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3672** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003673**
3674** When opening a new shared-memory file, if no other instances of that
3675** file are currently open, in this process or in other processes, then
3676** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003677**
3678** If the original database file (pDbFd) is using the "unix-excl" VFS
3679** that means that an exclusive lock is held on the database file and
3680** that no other processes are able to read or write the database. In
3681** that case, we do not really need shared memory. No shared memory
3682** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003683*/
danda9fe0c2010-07-13 18:44:03 +00003684static int unixOpenSharedMemory(unixFile *pDbFd){
3685 struct unixShm *p = 0; /* The connection to be opened */
3686 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3687 int rc; /* Result code */
3688 unixInodeInfo *pInode; /* The inode of fd */
3689 char *zShmFilename; /* Name of the file used for SHM */
3690 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003691
danda9fe0c2010-07-13 18:44:03 +00003692 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003693 p = sqlite3_malloc( sizeof(*p) );
3694 if( p==0 ) return SQLITE_NOMEM;
3695 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003696 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003697
danda9fe0c2010-07-13 18:44:03 +00003698 /* Check to see if a unixShmNode object already exists. Reuse an existing
3699 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003700 */
3701 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003702 pInode = pDbFd->pInode;
3703 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003704 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003705 struct stat sStat; /* fstat() info for database file */
3706
3707 /* Call fstat() to figure out the permissions on the database file. If
3708 ** a new *-shm file is created, an attempt will be made to create it
3709 ** with the same permissions. The actual permissions the file is created
3710 ** with are subject to the current umask setting.
3711 */
drh3cb93392011-03-12 18:10:44 +00003712 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003713 rc = SQLITE_IOERR_FSTAT;
3714 goto shm_open_err;
3715 }
3716
drha4ced192010-07-15 18:32:40 +00003717#ifdef SQLITE_SHM_DIRECTORY
3718 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3719#else
drh7234c6d2010-06-19 15:10:09 +00003720 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003721#endif
drh7234c6d2010-06-19 15:10:09 +00003722 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003723 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003724 rc = SQLITE_NOMEM;
3725 goto shm_open_err;
3726 }
drhd91c68f2010-05-14 14:52:25 +00003727 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003728 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003729#ifdef SQLITE_SHM_DIRECTORY
3730 sqlite3_snprintf(nShmFilename, zShmFilename,
3731 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3732 (u32)sStat.st_ino, (u32)sStat.st_dev);
3733#else
drh7234c6d2010-06-19 15:10:09 +00003734 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003735#endif
drhd91c68f2010-05-14 14:52:25 +00003736 pShmNode->h = -1;
3737 pDbFd->pInode->pShmNode = pShmNode;
3738 pShmNode->pInode = pDbFd->pInode;
3739 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3740 if( pShmNode->mutex==0 ){
3741 rc = SQLITE_NOMEM;
3742 goto shm_open_err;
3743 }
drhd9e5c4f2010-05-12 18:01:39 +00003744
drh3cb93392011-03-12 18:10:44 +00003745 if( pInode->bProcessLock==0 ){
3746 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3747 (sStat.st_mode & 0777));
3748 if( pShmNode->h<0 ){
3749 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3750 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003751 }
drh3cb93392011-03-12 18:10:44 +00003752
3753 /* Check to see if another process is holding the dead-man switch.
3754 ** If not, truncate the file to zero length.
3755 */
3756 rc = SQLITE_OK;
3757 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3758 if( robust_ftruncate(pShmNode->h, 0) ){
3759 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3760 }
3761 }
3762 if( rc==SQLITE_OK ){
3763 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3764 }
3765 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003766 }
drhd9e5c4f2010-05-12 18:01:39 +00003767 }
3768
drhd91c68f2010-05-14 14:52:25 +00003769 /* Make the new connection a child of the unixShmNode */
3770 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003771#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003772 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003773#endif
drhd91c68f2010-05-14 14:52:25 +00003774 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003775 pDbFd->pShm = p;
3776 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003777
3778 /* The reference count on pShmNode has already been incremented under
3779 ** the cover of the unixEnterMutex() mutex and the pointer from the
3780 ** new (struct unixShm) object to the pShmNode has been set. All that is
3781 ** left to do is to link the new object into the linked list starting
3782 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3783 ** mutex.
3784 */
3785 sqlite3_mutex_enter(pShmNode->mutex);
3786 p->pNext = pShmNode->pFirst;
3787 pShmNode->pFirst = p;
3788 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003789 return SQLITE_OK;
3790
3791 /* Jump here on any error */
3792shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003793 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003794 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003795 unixLeaveMutex();
3796 return rc;
3797}
3798
3799/*
danda9fe0c2010-07-13 18:44:03 +00003800** This function is called to obtain a pointer to region iRegion of the
3801** shared-memory associated with the database file fd. Shared-memory regions
3802** are numbered starting from zero. Each shared-memory region is szRegion
3803** bytes in size.
3804**
3805** If an error occurs, an error code is returned and *pp is set to NULL.
3806**
3807** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3808** region has not been allocated (by any client, including one running in a
3809** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3810** bExtend is non-zero and the requested shared-memory region has not yet
3811** been allocated, it is allocated by this function.
3812**
3813** If the shared-memory region has already been allocated or is allocated by
3814** this call as described above, then it is mapped into this processes
3815** address space (if it is not already), *pp is set to point to the mapped
3816** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003817*/
danda9fe0c2010-07-13 18:44:03 +00003818static int unixShmMap(
3819 sqlite3_file *fd, /* Handle open on database file */
3820 int iRegion, /* Region to retrieve */
3821 int szRegion, /* Size of regions */
3822 int bExtend, /* True to extend file if necessary */
3823 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003824){
danda9fe0c2010-07-13 18:44:03 +00003825 unixFile *pDbFd = (unixFile*)fd;
3826 unixShm *p;
3827 unixShmNode *pShmNode;
3828 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003829
danda9fe0c2010-07-13 18:44:03 +00003830 /* If the shared-memory file has not yet been opened, open it now. */
3831 if( pDbFd->pShm==0 ){
3832 rc = unixOpenSharedMemory(pDbFd);
3833 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003834 }
drhd9e5c4f2010-05-12 18:01:39 +00003835
danda9fe0c2010-07-13 18:44:03 +00003836 p = pDbFd->pShm;
3837 pShmNode = p->pShmNode;
3838 sqlite3_mutex_enter(pShmNode->mutex);
3839 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003840 assert( pShmNode->pInode==pDbFd->pInode );
3841 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3842 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003843
3844 if( pShmNode->nRegion<=iRegion ){
3845 char **apNew; /* New apRegion[] array */
3846 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3847 struct stat sStat; /* Used by fstat() */
3848
3849 pShmNode->szRegion = szRegion;
3850
drh3cb93392011-03-12 18:10:44 +00003851 if( pShmNode->h>=0 ){
3852 /* The requested region is not mapped into this processes address space.
3853 ** Check to see if it has been allocated (i.e. if the wal-index file is
3854 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003855 */
drh3cb93392011-03-12 18:10:44 +00003856 if( osFstat(pShmNode->h, &sStat) ){
3857 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003858 goto shmpage_out;
3859 }
drh3cb93392011-03-12 18:10:44 +00003860
3861 if( sStat.st_size<nByte ){
3862 /* The requested memory region does not exist. If bExtend is set to
3863 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3864 **
3865 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3866 ** the requested memory region.
3867 */
3868 if( !bExtend ) goto shmpage_out;
3869 if( robust_ftruncate(pShmNode->h, nByte) ){
3870 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3871 pShmNode->zFilename);
3872 goto shmpage_out;
3873 }
3874 }
danda9fe0c2010-07-13 18:44:03 +00003875 }
3876
3877 /* Map the requested memory region into this processes address space. */
3878 apNew = (char **)sqlite3_realloc(
3879 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3880 );
3881 if( !apNew ){
3882 rc = SQLITE_IOERR_NOMEM;
3883 goto shmpage_out;
3884 }
3885 pShmNode->apRegion = apNew;
3886 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003887 void *pMem;
3888 if( pShmNode->h>=0 ){
3889 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3890 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3891 );
3892 if( pMem==MAP_FAILED ){
3893 rc = SQLITE_IOERR;
3894 goto shmpage_out;
3895 }
3896 }else{
3897 pMem = sqlite3_malloc(szRegion);
3898 if( pMem==0 ){
3899 rc = SQLITE_NOMEM;
3900 goto shmpage_out;
3901 }
3902 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003903 }
3904 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3905 pShmNode->nRegion++;
3906 }
3907 }
3908
3909shmpage_out:
3910 if( pShmNode->nRegion>iRegion ){
3911 *pp = pShmNode->apRegion[iRegion];
3912 }else{
3913 *pp = 0;
3914 }
3915 sqlite3_mutex_leave(pShmNode->mutex);
3916 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003917}
3918
3919/*
drhd9e5c4f2010-05-12 18:01:39 +00003920** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003921**
3922** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3923** different here than in posix. In xShmLock(), one can go from unlocked
3924** to shared and back or from unlocked to exclusive and back. But one may
3925** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003926*/
3927static int unixShmLock(
3928 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003929 int ofst, /* First lock to acquire or release */
3930 int n, /* Number of locks to acquire or release */
3931 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003932){
drh73b64e42010-05-30 19:55:15 +00003933 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3934 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3935 unixShm *pX; /* For looping over all siblings */
3936 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3937 int rc = SQLITE_OK; /* Result code */
3938 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003939
drhd91c68f2010-05-14 14:52:25 +00003940 assert( pShmNode==pDbFd->pInode->pShmNode );
3941 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003942 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003943 assert( n>=1 );
3944 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3945 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3946 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3947 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3948 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003949 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3950 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003951
drhc99597c2010-05-31 01:41:15 +00003952 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003953 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003954 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003955 if( flags & SQLITE_SHM_UNLOCK ){
3956 u16 allMask = 0; /* Mask of locks held by siblings */
3957
3958 /* See if any siblings hold this same lock */
3959 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3960 if( pX==p ) continue;
3961 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3962 allMask |= pX->sharedMask;
3963 }
3964
3965 /* Unlock the system-level locks */
3966 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003967 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003968 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003969 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003970 }
drh73b64e42010-05-30 19:55:15 +00003971
3972 /* Undo the local locks */
3973 if( rc==SQLITE_OK ){
3974 p->exclMask &= ~mask;
3975 p->sharedMask &= ~mask;
3976 }
3977 }else if( flags & SQLITE_SHM_SHARED ){
3978 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3979
3980 /* Find out which shared locks are already held by sibling connections.
3981 ** If any sibling already holds an exclusive lock, go ahead and return
3982 ** SQLITE_BUSY.
3983 */
3984 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003985 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003986 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003987 break;
3988 }
3989 allShared |= pX->sharedMask;
3990 }
3991
3992 /* Get shared locks at the system level, if necessary */
3993 if( rc==SQLITE_OK ){
3994 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003995 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003996 }else{
drh73b64e42010-05-30 19:55:15 +00003997 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003998 }
drhd9e5c4f2010-05-12 18:01:39 +00003999 }
drh73b64e42010-05-30 19:55:15 +00004000
4001 /* Get the local shared locks */
4002 if( rc==SQLITE_OK ){
4003 p->sharedMask |= mask;
4004 }
4005 }else{
4006 /* Make sure no sibling connections hold locks that will block this
4007 ** lock. If any do, return SQLITE_BUSY right away.
4008 */
4009 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004010 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4011 rc = SQLITE_BUSY;
4012 break;
4013 }
4014 }
4015
4016 /* Get the exclusive locks at the system level. Then if successful
4017 ** also mark the local connection as being locked.
4018 */
4019 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004020 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004021 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004022 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004023 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004024 }
drhd9e5c4f2010-05-12 18:01:39 +00004025 }
4026 }
drhd91c68f2010-05-14 14:52:25 +00004027 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004028 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4029 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004030 return rc;
4031}
4032
drh286a2882010-05-20 23:51:06 +00004033/*
4034** Implement a memory barrier or memory fence on shared memory.
4035**
4036** All loads and stores begun before the barrier must complete before
4037** any load or store begun after the barrier.
4038*/
4039static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004040 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004041){
drhff828942010-06-26 21:34:06 +00004042 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004043 unixEnterMutex();
4044 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004045}
4046
dan18801912010-06-14 14:07:50 +00004047/*
danda9fe0c2010-07-13 18:44:03 +00004048** Close a connection to shared-memory. Delete the underlying
4049** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004050**
4051** If there is no shared memory associated with the connection then this
4052** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004053*/
danda9fe0c2010-07-13 18:44:03 +00004054static int unixShmUnmap(
4055 sqlite3_file *fd, /* The underlying database file */
4056 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004057){
danda9fe0c2010-07-13 18:44:03 +00004058 unixShm *p; /* The connection to be closed */
4059 unixShmNode *pShmNode; /* The underlying shared-memory file */
4060 unixShm **pp; /* For looping over sibling connections */
4061 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004062
danda9fe0c2010-07-13 18:44:03 +00004063 pDbFd = (unixFile*)fd;
4064 p = pDbFd->pShm;
4065 if( p==0 ) return SQLITE_OK;
4066 pShmNode = p->pShmNode;
4067
4068 assert( pShmNode==pDbFd->pInode->pShmNode );
4069 assert( pShmNode->pInode==pDbFd->pInode );
4070
4071 /* Remove connection p from the set of connections associated
4072 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004073 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004074 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4075 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004076
danda9fe0c2010-07-13 18:44:03 +00004077 /* Free the connection p */
4078 sqlite3_free(p);
4079 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004080 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004081
4082 /* If pShmNode->nRef has reached 0, then close the underlying
4083 ** shared-memory file, too */
4084 unixEnterMutex();
4085 assert( pShmNode->nRef>0 );
4086 pShmNode->nRef--;
4087 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004088 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004089 unixShmPurge(pDbFd);
4090 }
4091 unixLeaveMutex();
4092
4093 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004094}
drh286a2882010-05-20 23:51:06 +00004095
danda9fe0c2010-07-13 18:44:03 +00004096
drhd9e5c4f2010-05-12 18:01:39 +00004097#else
drh6b017cc2010-06-14 18:01:46 +00004098# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004099# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004100# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004101# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004102#endif /* #ifndef SQLITE_OMIT_WAL */
4103
drh734c9862008-11-28 15:37:20 +00004104/*
4105** Here ends the implementation of all sqlite3_file methods.
4106**
4107********************** End sqlite3_file Methods *******************************
4108******************************************************************************/
4109
4110/*
drh6b9d6dd2008-12-03 19:34:47 +00004111** This division contains definitions of sqlite3_io_methods objects that
4112** implement various file locking strategies. It also contains definitions
4113** of "finder" functions. A finder-function is used to locate the appropriate
4114** sqlite3_io_methods object for a particular database file. The pAppData
4115** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4116** the correct finder-function for that VFS.
4117**
4118** Most finder functions return a pointer to a fixed sqlite3_io_methods
4119** object. The only interesting finder-function is autolockIoFinder, which
4120** looks at the filesystem type and tries to guess the best locking
4121** strategy from that.
4122**
drh1875f7a2008-12-08 18:19:17 +00004123** For finder-funtion F, two objects are created:
4124**
4125** (1) The real finder-function named "FImpt()".
4126**
dane946c392009-08-22 11:39:46 +00004127** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004128**
4129**
4130** A pointer to the F pointer is used as the pAppData value for VFS
4131** objects. We have to do this instead of letting pAppData point
4132** directly at the finder-function since C90 rules prevent a void*
4133** from be cast into a function pointer.
4134**
drh6b9d6dd2008-12-03 19:34:47 +00004135**
drh7708e972008-11-29 00:56:52 +00004136** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004137**
drh7708e972008-11-29 00:56:52 +00004138** * A constant sqlite3_io_methods object call METHOD that has locking
4139** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4140**
4141** * An I/O method finder function called FINDER that returns a pointer
4142** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004143*/
drhd9e5c4f2010-05-12 18:01:39 +00004144#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004145static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004146 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004147 CLOSE, /* xClose */ \
4148 unixRead, /* xRead */ \
4149 unixWrite, /* xWrite */ \
4150 unixTruncate, /* xTruncate */ \
4151 unixSync, /* xSync */ \
4152 unixFileSize, /* xFileSize */ \
4153 LOCK, /* xLock */ \
4154 UNLOCK, /* xUnlock */ \
4155 CKLOCK, /* xCheckReservedLock */ \
4156 unixFileControl, /* xFileControl */ \
4157 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004158 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004159 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004160 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004161 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004162 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004163}; \
drh0c2694b2009-09-03 16:23:44 +00004164static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4165 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004166 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004167} \
drh0c2694b2009-09-03 16:23:44 +00004168static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004169 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004170
4171/*
4172** Here are all of the sqlite3_io_methods objects for each of the
4173** locking strategies. Functions that return pointers to these methods
4174** are also created.
4175*/
4176IOMETHODS(
4177 posixIoFinder, /* Finder function name */
4178 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004179 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004180 unixClose, /* xClose method */
4181 unixLock, /* xLock method */
4182 unixUnlock, /* xUnlock method */
4183 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004184)
drh7708e972008-11-29 00:56:52 +00004185IOMETHODS(
4186 nolockIoFinder, /* Finder function name */
4187 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004188 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004189 nolockClose, /* xClose method */
4190 nolockLock, /* xLock method */
4191 nolockUnlock, /* xUnlock method */
4192 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004193)
drh7708e972008-11-29 00:56:52 +00004194IOMETHODS(
4195 dotlockIoFinder, /* Finder function name */
4196 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004197 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004198 dotlockClose, /* xClose method */
4199 dotlockLock, /* xLock method */
4200 dotlockUnlock, /* xUnlock method */
4201 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004202)
drh7708e972008-11-29 00:56:52 +00004203
chw78a13182009-04-07 05:35:03 +00004204#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004205IOMETHODS(
4206 flockIoFinder, /* Finder function name */
4207 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004208 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004209 flockClose, /* xClose method */
4210 flockLock, /* xLock method */
4211 flockUnlock, /* xUnlock method */
4212 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004213)
drh7708e972008-11-29 00:56:52 +00004214#endif
4215
drh6c7d5c52008-11-21 20:32:33 +00004216#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004217IOMETHODS(
4218 semIoFinder, /* Finder function name */
4219 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004220 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004221 semClose, /* xClose method */
4222 semLock, /* xLock method */
4223 semUnlock, /* xUnlock method */
4224 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004225)
aswiftaebf4132008-11-21 00:10:35 +00004226#endif
drh7708e972008-11-29 00:56:52 +00004227
drhd2cb50b2009-01-09 21:41:17 +00004228#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004229IOMETHODS(
4230 afpIoFinder, /* Finder function name */
4231 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004232 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004233 afpClose, /* xClose method */
4234 afpLock, /* xLock method */
4235 afpUnlock, /* xUnlock method */
4236 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004237)
drh715ff302008-12-03 22:32:44 +00004238#endif
4239
4240/*
4241** The proxy locking method is a "super-method" in the sense that it
4242** opens secondary file descriptors for the conch and lock files and
4243** it uses proxy, dot-file, AFP, and flock() locking methods on those
4244** secondary files. For this reason, the division that implements
4245** proxy locking is located much further down in the file. But we need
4246** to go ahead and define the sqlite3_io_methods and finder function
4247** for proxy locking here. So we forward declare the I/O methods.
4248*/
drhd2cb50b2009-01-09 21:41:17 +00004249#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004250static int proxyClose(sqlite3_file*);
4251static int proxyLock(sqlite3_file*, int);
4252static int proxyUnlock(sqlite3_file*, int);
4253static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004254IOMETHODS(
4255 proxyIoFinder, /* Finder function name */
4256 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004257 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004258 proxyClose, /* xClose method */
4259 proxyLock, /* xLock method */
4260 proxyUnlock, /* xUnlock method */
4261 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004262)
aswiftaebf4132008-11-21 00:10:35 +00004263#endif
drh7708e972008-11-29 00:56:52 +00004264
drh7ed97b92010-01-20 13:07:21 +00004265/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4266#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4267IOMETHODS(
4268 nfsIoFinder, /* Finder function name */
4269 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004270 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004271 unixClose, /* xClose method */
4272 unixLock, /* xLock method */
4273 nfsUnlock, /* xUnlock method */
4274 unixCheckReservedLock /* xCheckReservedLock method */
4275)
4276#endif
drh7708e972008-11-29 00:56:52 +00004277
drhd2cb50b2009-01-09 21:41:17 +00004278#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004279/*
drh6b9d6dd2008-12-03 19:34:47 +00004280** This "finder" function attempts to determine the best locking strategy
4281** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004282** object that implements that strategy.
4283**
4284** This is for MacOSX only.
4285*/
drh1875f7a2008-12-08 18:19:17 +00004286static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004287 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004288 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004289){
4290 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004291 const char *zFilesystem; /* Filesystem type name */
4292 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004293 } aMap[] = {
4294 { "hfs", &posixIoMethods },
4295 { "ufs", &posixIoMethods },
4296 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004297 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004298 { "webdav", &nolockIoMethods },
4299 { 0, 0 }
4300 };
4301 int i;
4302 struct statfs fsInfo;
4303 struct flock lockInfo;
4304
4305 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004306 /* If filePath==NULL that means we are dealing with a transient file
4307 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004308 return &nolockIoMethods;
4309 }
4310 if( statfs(filePath, &fsInfo) != -1 ){
4311 if( fsInfo.f_flags & MNT_RDONLY ){
4312 return &nolockIoMethods;
4313 }
4314 for(i=0; aMap[i].zFilesystem; i++){
4315 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4316 return aMap[i].pMethods;
4317 }
4318 }
4319 }
4320
4321 /* Default case. Handles, amongst others, "nfs".
4322 ** Test byte-range lock using fcntl(). If the call succeeds,
4323 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004324 */
drh7708e972008-11-29 00:56:52 +00004325 lockInfo.l_len = 1;
4326 lockInfo.l_start = 0;
4327 lockInfo.l_whence = SEEK_SET;
4328 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004329 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004330 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4331 return &nfsIoMethods;
4332 } else {
4333 return &posixIoMethods;
4334 }
drh7708e972008-11-29 00:56:52 +00004335 }else{
4336 return &dotlockIoMethods;
4337 }
4338}
drh0c2694b2009-09-03 16:23:44 +00004339static const sqlite3_io_methods
4340 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004341
drhd2cb50b2009-01-09 21:41:17 +00004342#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004343
chw78a13182009-04-07 05:35:03 +00004344#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4345/*
4346** This "finder" function attempts to determine the best locking strategy
4347** for the database file "filePath". It then returns the sqlite3_io_methods
4348** object that implements that strategy.
4349**
4350** This is for VXWorks only.
4351*/
4352static const sqlite3_io_methods *autolockIoFinderImpl(
4353 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004354 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004355){
4356 struct flock lockInfo;
4357
4358 if( !filePath ){
4359 /* If filePath==NULL that means we are dealing with a transient file
4360 ** that does not need to be locked. */
4361 return &nolockIoMethods;
4362 }
4363
4364 /* Test if fcntl() is supported and use POSIX style locks.
4365 ** Otherwise fall back to the named semaphore method.
4366 */
4367 lockInfo.l_len = 1;
4368 lockInfo.l_start = 0;
4369 lockInfo.l_whence = SEEK_SET;
4370 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004371 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004372 return &posixIoMethods;
4373 }else{
4374 return &semIoMethods;
4375 }
4376}
drh0c2694b2009-09-03 16:23:44 +00004377static const sqlite3_io_methods
4378 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004379
4380#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4381
drh7708e972008-11-29 00:56:52 +00004382/*
4383** An abstract type for a pointer to a IO method finder function:
4384*/
drh0c2694b2009-09-03 16:23:44 +00004385typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004386
aswiftaebf4132008-11-21 00:10:35 +00004387
drh734c9862008-11-28 15:37:20 +00004388/****************************************************************************
4389**************************** sqlite3_vfs methods ****************************
4390**
4391** This division contains the implementation of methods on the
4392** sqlite3_vfs object.
4393*/
4394
danielk1977a3d4c882007-03-23 10:08:38 +00004395/*
danielk1977e339d652008-06-28 11:23:00 +00004396** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004397*/
4398static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004399 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004400 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004401 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004402 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004403 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004404 int noLock, /* Omit locking if true */
4405 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004406){
drh7708e972008-11-29 00:56:52 +00004407 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004408 unixFile *pNew = (unixFile *)pId;
4409 int rc = SQLITE_OK;
4410
drh8af6c222010-05-14 12:43:01 +00004411 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004412
dane946c392009-08-22 11:39:46 +00004413 /* Parameter isDelete is only used on vxworks. Express this explicitly
4414 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004415 */
drh7708e972008-11-29 00:56:52 +00004416 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004417
dan00157392010-10-05 11:33:15 +00004418 /* Usually the path zFilename should not be a relative pathname. The
4419 ** exception is when opening the proxy "conch" file in builds that
4420 ** include the special Apple locking styles.
4421 */
dan00157392010-10-05 11:33:15 +00004422#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004423 assert( zFilename==0 || zFilename[0]=='/'
4424 || pVfs->pAppData==(void*)&autolockIoFinder );
4425#else
4426 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004427#endif
dan00157392010-10-05 11:33:15 +00004428
drh308c2a52010-05-14 11:30:18 +00004429 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004430 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004431 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004432 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004433 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4434 pNew->ctrlFlags = UNIXFILE_EXCL;
4435 }else{
4436 pNew->ctrlFlags = 0;
4437 }
drh339eb0b2008-03-07 15:34:11 +00004438
drh6c7d5c52008-11-21 20:32:33 +00004439#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004440 pNew->pId = vxworksFindFileId(zFilename);
4441 if( pNew->pId==0 ){
4442 noLock = 1;
4443 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004444 }
4445#endif
4446
drhda0e7682008-07-30 15:27:54 +00004447 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004448 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004449 }else{
drh0c2694b2009-09-03 16:23:44 +00004450 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004451#if SQLITE_ENABLE_LOCKING_STYLE
4452 /* Cache zFilename in the locking context (AFP and dotlock override) for
4453 ** proxyLock activation is possible (remote proxy is based on db name)
4454 ** zFilename remains valid until file is closed, to support */
4455 pNew->lockingContext = (void*)zFilename;
4456#endif
drhda0e7682008-07-30 15:27:54 +00004457 }
danielk1977e339d652008-06-28 11:23:00 +00004458
drh7ed97b92010-01-20 13:07:21 +00004459 if( pLockingStyle == &posixIoMethods
4460#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4461 || pLockingStyle == &nfsIoMethods
4462#endif
4463 ){
drh7708e972008-11-29 00:56:52 +00004464 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004465 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004466 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004467 /* If an error occured in findInodeInfo(), close the file descriptor
4468 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004469 ** in two scenarios:
4470 **
4471 ** (a) A call to fstat() failed.
4472 ** (b) A malloc failed.
4473 **
4474 ** Scenario (b) may only occur if the process is holding no other
4475 ** file descriptors open on the same file. If there were other file
4476 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004477 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004478 ** handle h - as it is guaranteed that no posix locks will be released
4479 ** by doing so.
4480 **
4481 ** If scenario (a) caused the error then things are not so safe. The
4482 ** implicit assumption here is that if fstat() fails, things are in
4483 ** such bad shape that dropping a lock or two doesn't matter much.
4484 */
drh0e9365c2011-03-02 02:08:13 +00004485 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004486 h = -1;
4487 }
drh7708e972008-11-29 00:56:52 +00004488 unixLeaveMutex();
4489 }
danielk1977e339d652008-06-28 11:23:00 +00004490
drhd2cb50b2009-01-09 21:41:17 +00004491#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004492 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004493 /* AFP locking uses the file path so it needs to be included in
4494 ** the afpLockingContext.
4495 */
4496 afpLockingContext *pCtx;
4497 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4498 if( pCtx==0 ){
4499 rc = SQLITE_NOMEM;
4500 }else{
4501 /* NB: zFilename exists and remains valid until the file is closed
4502 ** according to requirement F11141. So we do not need to make a
4503 ** copy of the filename. */
4504 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004505 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004506 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004507 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004508 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004509 if( rc!=SQLITE_OK ){
4510 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004511 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004512 h = -1;
4513 }
drh7708e972008-11-29 00:56:52 +00004514 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004515 }
drh7708e972008-11-29 00:56:52 +00004516 }
4517#endif
danielk1977e339d652008-06-28 11:23:00 +00004518
drh7708e972008-11-29 00:56:52 +00004519 else if( pLockingStyle == &dotlockIoMethods ){
4520 /* Dotfile locking uses the file path so it needs to be included in
4521 ** the dotlockLockingContext
4522 */
4523 char *zLockFile;
4524 int nFilename;
drhea678832008-12-10 19:26:22 +00004525 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004526 zLockFile = (char *)sqlite3_malloc(nFilename);
4527 if( zLockFile==0 ){
4528 rc = SQLITE_NOMEM;
4529 }else{
4530 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004531 }
drh7708e972008-11-29 00:56:52 +00004532 pNew->lockingContext = zLockFile;
4533 }
danielk1977e339d652008-06-28 11:23:00 +00004534
drh6c7d5c52008-11-21 20:32:33 +00004535#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004536 else if( pLockingStyle == &semIoMethods ){
4537 /* Named semaphore locking uses the file path so it needs to be
4538 ** included in the semLockingContext
4539 */
4540 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004541 rc = findInodeInfo(pNew, &pNew->pInode);
4542 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4543 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004544 int n;
drh2238dcc2009-08-27 17:56:20 +00004545 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004546 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004547 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004548 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004549 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4550 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004551 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004552 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004553 }
chw97185482008-11-17 08:05:31 +00004554 }
drh7708e972008-11-29 00:56:52 +00004555 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004556 }
drh7708e972008-11-29 00:56:52 +00004557#endif
aswift5b1a2562008-08-22 00:22:35 +00004558
4559 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004560#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004561 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004562 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004563 h = -1;
chw97185482008-11-17 08:05:31 +00004564 unlink(zFilename);
4565 isDelete = 0;
4566 }
4567 pNew->isDelete = isDelete;
4568#endif
danielk1977e339d652008-06-28 11:23:00 +00004569 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004570 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4571 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004572 }else{
drh7708e972008-11-29 00:56:52 +00004573 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004574 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004575 }
danielk1977e339d652008-06-28 11:23:00 +00004576 return rc;
drh054889e2005-11-30 03:20:31 +00004577}
drh9c06c952005-11-26 00:25:00 +00004578
danielk1977ad94b582007-08-20 06:44:22 +00004579/*
4580** Open a file descriptor to the directory containing file zFilename.
4581** If successful, *pFd is set to the opened file descriptor and
4582** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4583** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4584** value.
4585**
4586** If SQLITE_OK is returned, the caller is responsible for closing
4587** the file descriptor *pFd using close().
4588*/
danielk1977fee2d252007-08-18 10:59:19 +00004589static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004590 int ii;
drh777b17a2007-09-20 10:02:54 +00004591 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004592 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004593
drh153c62c2007-08-24 03:51:33 +00004594 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004595 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004596 if( ii>0 ){
4597 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004598 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004599 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004600#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004601 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004602#endif
drh308c2a52010-05-14 11:30:18 +00004603 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004604 }
4605 }
danielk1977fee2d252007-08-18 10:59:19 +00004606 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004607 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004608}
4609
danielk1977b4b47412007-08-17 15:53:36 +00004610/*
drh8b3cf822010-06-01 21:02:51 +00004611** Return the name of a directory in which to put temporary files.
4612** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004613*/
drh7234c6d2010-06-19 15:10:09 +00004614static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004615 static const char *azDirs[] = {
4616 0,
aswiftaebf4132008-11-21 00:10:35 +00004617 0,
danielk197717b90b52008-06-06 11:11:25 +00004618 "/var/tmp",
4619 "/usr/tmp",
4620 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004621 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004622 };
drh8b3cf822010-06-01 21:02:51 +00004623 unsigned int i;
4624 struct stat buf;
4625 const char *zDir = 0;
4626
4627 azDirs[0] = sqlite3_temp_directory;
4628 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004629 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004630 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004631 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004632 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004633 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004634 break;
4635 }
4636 return zDir;
4637}
4638
4639/*
4640** Create a temporary file name in zBuf. zBuf must be allocated
4641** by the calling process and must be big enough to hold at least
4642** pVfs->mxPathname bytes.
4643*/
4644static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004645 static const unsigned char zChars[] =
4646 "abcdefghijklmnopqrstuvwxyz"
4647 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4648 "0123456789";
drh41022642008-11-21 00:24:42 +00004649 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004650 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004651
4652 /* It's odd to simulate an io-error here, but really this is just
4653 ** using the io-error infrastructure to test that SQLite handles this
4654 ** function failing.
4655 */
4656 SimulateIOError( return SQLITE_IOERR );
4657
drh7234c6d2010-06-19 15:10:09 +00004658 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004659 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004660
4661 /* Check that the output buffer is large enough for the temporary file
4662 ** name. If it is not, return SQLITE_ERROR.
4663 */
danielk197700e13612008-11-17 19:18:54 +00004664 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004665 return SQLITE_ERROR;
4666 }
4667
4668 do{
4669 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004670 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004671 sqlite3_randomness(15, &zBuf[j]);
4672 for(i=0; i<15; i++, j++){
4673 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4674 }
4675 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004676 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004677 return SQLITE_OK;
4678}
4679
drhd2cb50b2009-01-09 21:41:17 +00004680#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004681/*
4682** Routine to transform a unixFile into a proxy-locking unixFile.
4683** Implementation in the proxy-lock division, but used by unixOpen()
4684** if SQLITE_PREFER_PROXY_LOCKING is defined.
4685*/
4686static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004687#endif
drhc66d5b62008-12-03 22:48:32 +00004688
dan08da86a2009-08-21 17:18:03 +00004689/*
4690** Search for an unused file descriptor that was opened on the database
4691** file (not a journal or master-journal file) identified by pathname
4692** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4693** argument to this function.
4694**
4695** Such a file descriptor may exist if a database connection was closed
4696** but the associated file descriptor could not be closed because some
4697** other file descriptor open on the same file is holding a file-lock.
4698** Refer to comments in the unixClose() function and the lengthy comment
4699** describing "Posix Advisory Locking" at the start of this file for
4700** further details. Also, ticket #4018.
4701**
4702** If a suitable file descriptor is found, then it is returned. If no
4703** such file descriptor is located, -1 is returned.
4704*/
dane946c392009-08-22 11:39:46 +00004705static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4706 UnixUnusedFd *pUnused = 0;
4707
4708 /* Do not search for an unused file descriptor on vxworks. Not because
4709 ** vxworks would not benefit from the change (it might, we're not sure),
4710 ** but because no way to test it is currently available. It is better
4711 ** not to risk breaking vxworks support for the sake of such an obscure
4712 ** feature. */
4713#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004714 struct stat sStat; /* Results of stat() call */
4715
4716 /* A stat() call may fail for various reasons. If this happens, it is
4717 ** almost certain that an open() call on the same path will also fail.
4718 ** For this reason, if an error occurs in the stat() call here, it is
4719 ** ignored and -1 is returned. The caller will try to open a new file
4720 ** descriptor on the same path, fail, and return an error to SQLite.
4721 **
4722 ** Even if a subsequent open() call does succeed, the consequences of
4723 ** not searching for a resusable file descriptor are not dire. */
4724 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004725 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004726
4727 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004728 pInode = inodeList;
4729 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4730 || pInode->fileId.ino!=sStat.st_ino) ){
4731 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004732 }
drh8af6c222010-05-14 12:43:01 +00004733 if( pInode ){
dane946c392009-08-22 11:39:46 +00004734 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004735 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004736 pUnused = *pp;
4737 if( pUnused ){
4738 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004739 }
4740 }
4741 unixLeaveMutex();
4742 }
dane946c392009-08-22 11:39:46 +00004743#endif /* if !OS_VXWORKS */
4744 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004745}
danielk197717b90b52008-06-06 11:11:25 +00004746
4747/*
danddb0ac42010-07-14 14:48:58 +00004748** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004749** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004750** and a value suitable for passing as the third argument to open(2) is
4751** written to *pMode. If an IO error occurs, an SQLite error code is
4752** returned and the value of *pMode is not modified.
4753**
4754** If the file being opened is a temporary file, it is always created with
4755** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004756** is a database or master journal file, it is created with the permissions
4757** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004758**
drh8ab58662010-07-15 18:38:39 +00004759** Finally, if the file being opened is a WAL or regular journal file, then
4760** this function queries the file-system for the permissions on the
4761** corresponding database file and sets *pMode to this value. Whenever
4762** possible, WAL and journal files are created using the same permissions
4763** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004764*/
4765static int findCreateFileMode(
4766 const char *zPath, /* Path of file (possibly) being created */
4767 int flags, /* Flags passed as 4th argument to xOpen() */
4768 mode_t *pMode /* OUT: Permissions to open file with */
4769){
4770 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004771 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004772 char zDb[MAX_PATHNAME+1]; /* Database file path */
4773 int nDb; /* Number of valid bytes in zDb */
4774 struct stat sStat; /* Output of stat() on database file */
4775
dana0c989d2010-11-05 18:07:37 +00004776 /* zPath is a path to a WAL or journal file. The following block derives
4777 ** the path to the associated database file from zPath. This block handles
4778 ** the following naming conventions:
4779 **
4780 ** "<path to db>-journal"
4781 ** "<path to db>-wal"
4782 ** "<path to db>-journal-NNNN"
4783 ** "<path to db>-wal-NNNN"
4784 **
4785 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4786 ** used by the test_multiplex.c module.
4787 */
4788 nDb = sqlite3Strlen30(zPath) - 1;
4789 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4790 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004791 memcpy(zDb, zPath, nDb);
4792 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004793
danddb0ac42010-07-14 14:48:58 +00004794 if( 0==stat(zDb, &sStat) ){
4795 *pMode = sStat.st_mode & 0777;
4796 }else{
4797 rc = SQLITE_IOERR_FSTAT;
4798 }
4799 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4800 *pMode = 0600;
4801 }else{
4802 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4803 }
4804 return rc;
4805}
4806
4807/*
danielk1977ad94b582007-08-20 06:44:22 +00004808** Open the file zPath.
4809**
danielk1977b4b47412007-08-17 15:53:36 +00004810** Previously, the SQLite OS layer used three functions in place of this
4811** one:
4812**
4813** sqlite3OsOpenReadWrite();
4814** sqlite3OsOpenReadOnly();
4815** sqlite3OsOpenExclusive();
4816**
4817** These calls correspond to the following combinations of flags:
4818**
4819** ReadWrite() -> (READWRITE | CREATE)
4820** ReadOnly() -> (READONLY)
4821** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4822**
4823** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4824** true, the file was configured to be automatically deleted when the
4825** file handle closed. To achieve the same effect using this new
4826** interface, add the DELETEONCLOSE flag to those specified above for
4827** OpenExclusive().
4828*/
4829static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004830 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4831 const char *zPath, /* Pathname of file to be opened */
4832 sqlite3_file *pFile, /* The file descriptor to be filled in */
4833 int flags, /* Input flags to control the opening */
4834 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004835){
dan08da86a2009-08-21 17:18:03 +00004836 unixFile *p = (unixFile *)pFile;
4837 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004838 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004839 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004840 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004841 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004842 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004843
4844 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4845 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4846 int isCreate = (flags & SQLITE_OPEN_CREATE);
4847 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4848 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004849#if SQLITE_ENABLE_LOCKING_STYLE
4850 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4851#endif
danielk1977b4b47412007-08-17 15:53:36 +00004852
danielk1977fee2d252007-08-18 10:59:19 +00004853 /* If creating a master or main-file journal, this function will open
4854 ** a file-descriptor on the directory too. The first time unixSync()
4855 ** is called the directory file descriptor will be fsync()ed and close()d.
4856 */
danddb0ac42010-07-14 14:48:58 +00004857 int isOpenDirectory = (isCreate && (
4858 eType==SQLITE_OPEN_MASTER_JOURNAL
4859 || eType==SQLITE_OPEN_MAIN_JOURNAL
4860 || eType==SQLITE_OPEN_WAL
4861 ));
danielk1977fee2d252007-08-18 10:59:19 +00004862
danielk197717b90b52008-06-06 11:11:25 +00004863 /* If argument zPath is a NULL pointer, this function is required to open
4864 ** a temporary file. Use this buffer to store the file name in.
4865 */
4866 char zTmpname[MAX_PATHNAME+1];
4867 const char *zName = zPath;
4868
danielk1977fee2d252007-08-18 10:59:19 +00004869 /* Check the following statements are true:
4870 **
4871 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4872 ** (b) if CREATE is set, then READWRITE must also be set, and
4873 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004874 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004875 */
danielk1977b4b47412007-08-17 15:53:36 +00004876 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004877 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004878 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004879 assert(isDelete==0 || isCreate);
4880
danddb0ac42010-07-14 14:48:58 +00004881 /* The main DB, main journal, WAL file and master journal are never
4882 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004883 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4884 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4885 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004886 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004887
danielk1977fee2d252007-08-18 10:59:19 +00004888 /* Assert that the upper layer has set one of the "file-type" flags. */
4889 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4890 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4891 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004892 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004893 );
4894
dan08da86a2009-08-21 17:18:03 +00004895 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004896
dan08da86a2009-08-21 17:18:03 +00004897 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004898 UnixUnusedFd *pUnused;
4899 pUnused = findReusableFd(zName, flags);
4900 if( pUnused ){
4901 fd = pUnused->fd;
4902 }else{
dan6aa657f2009-08-24 18:57:58 +00004903 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004904 if( !pUnused ){
4905 return SQLITE_NOMEM;
4906 }
4907 }
4908 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004909 }else if( !zName ){
4910 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004911 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004912 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004913 if( rc!=SQLITE_OK ){
4914 return rc;
4915 }
4916 zName = zTmpname;
4917 }
4918
dan08da86a2009-08-21 17:18:03 +00004919 /* Determine the value of the flags parameter passed to POSIX function
4920 ** open(). These must be calculated even if open() is not called, as
4921 ** they may be stored as part of the file handle and used by the
4922 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004923 if( isReadonly ) openFlags |= O_RDONLY;
4924 if( isReadWrite ) openFlags |= O_RDWR;
4925 if( isCreate ) openFlags |= O_CREAT;
4926 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4927 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004928
danielk1977b4b47412007-08-17 15:53:36 +00004929 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004930 mode_t openMode; /* Permissions to create file with */
4931 rc = findCreateFileMode(zName, flags, &openMode);
4932 if( rc!=SQLITE_OK ){
4933 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004934 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004935 return rc;
4936 }
drhad4f1e52011-03-04 15:43:57 +00004937 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004938 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004939 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4940 /* Failed to open the file for read/write access. Try read-only. */
4941 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004942 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004943 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004944 openFlags |= O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00004945 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004946 }
4947 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004948 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004949 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004950 }
danielk1977b4b47412007-08-17 15:53:36 +00004951 }
dan08da86a2009-08-21 17:18:03 +00004952 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004953 if( pOutFlags ){
4954 *pOutFlags = flags;
4955 }
4956
dane946c392009-08-22 11:39:46 +00004957 if( p->pUnused ){
4958 p->pUnused->fd = fd;
4959 p->pUnused->flags = flags;
4960 }
4961
danielk1977b4b47412007-08-17 15:53:36 +00004962 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004963#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004964 zPath = zName;
4965#else
danielk197717b90b52008-06-06 11:11:25 +00004966 unlink(zName);
chw97185482008-11-17 08:05:31 +00004967#endif
danielk1977b4b47412007-08-17 15:53:36 +00004968 }
drh41022642008-11-21 00:24:42 +00004969#if SQLITE_ENABLE_LOCKING_STYLE
4970 else{
dan08da86a2009-08-21 17:18:03 +00004971 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004972 }
4973#endif
4974
danielk1977fee2d252007-08-18 10:59:19 +00004975 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004976 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004977 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004978 /* It is safe to close fd at this point, because it is guaranteed not
4979 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004980 ** it would not be safe to close as this would release any locks held
4981 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004982 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00004983 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004984 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004985 }
4986 }
danielk1977e339d652008-06-28 11:23:00 +00004987
4988#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004989 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00004990#endif
4991
drhda0e7682008-07-30 15:27:54 +00004992 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004993
drh7ed97b92010-01-20 13:07:21 +00004994
4995#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4996 struct statfs fsInfo;
4997 if( fstatfs(fd, &fsInfo) == -1 ){
4998 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00004999 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5000 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005001 return SQLITE_IOERR_ACCESS;
5002 }
5003 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5004 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5005 }
5006#endif
5007
5008#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005009#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005010 isAutoProxy = 1;
5011#endif
5012 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005013 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5014 int useProxy = 0;
5015
dan08da86a2009-08-21 17:18:03 +00005016 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5017 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005018 if( envforce!=NULL ){
5019 useProxy = atoi(envforce)>0;
5020 }else{
5021 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005022 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005023 /* In theory, the close(fd) call is sub-optimal. If the file opened
5024 ** with fd is a database file, and there are other connections open
5025 ** on that file that are currently holding advisory locks on it,
5026 ** then the call to close() will cancel those locks. In practice,
5027 ** we're assuming that statfs() doesn't fail very often. At least
5028 ** not while other file descriptors opened by the same process on
5029 ** the same file are working. */
5030 p->lastErrno = errno;
5031 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005032 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005033 }
drh0e9365c2011-03-02 02:08:13 +00005034 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005035 rc = SQLITE_IOERR_ACCESS;
5036 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005037 }
5038 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5039 }
5040 if( useProxy ){
5041 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
5042 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005043 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005044 if( rc!=SQLITE_OK ){
5045 /* Use unixClose to clean up the resources added in fillInUnixFile
5046 ** and clear all the structure's references. Specifically,
5047 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5048 */
5049 unixClose(pFile);
5050 return rc;
5051 }
aswiftaebf4132008-11-21 00:10:35 +00005052 }
dane946c392009-08-22 11:39:46 +00005053 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005054 }
5055 }
5056#endif
5057
dane946c392009-08-22 11:39:46 +00005058 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
5059open_finished:
5060 if( rc!=SQLITE_OK ){
5061 sqlite3_free(p->pUnused);
5062 }
5063 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005064}
5065
dane946c392009-08-22 11:39:46 +00005066
danielk1977b4b47412007-08-17 15:53:36 +00005067/*
danielk1977fee2d252007-08-18 10:59:19 +00005068** Delete the file at zPath. If the dirSync argument is true, fsync()
5069** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005070*/
drh6b9d6dd2008-12-03 19:34:47 +00005071static int unixDelete(
5072 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5073 const char *zPath, /* Name of file to be deleted */
5074 int dirSync /* If true, fsync() directory after deleting file */
5075){
danielk1977fee2d252007-08-18 10:59:19 +00005076 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005077 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005078 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005079 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005080 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005081 }
danielk1977d39fa702008-10-16 13:27:40 +00005082#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005083 if( dirSync ){
5084 int fd;
5085 rc = openDirectory(zPath, &fd);
5086 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005087#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005088 if( fsync(fd)==-1 )
5089#else
5090 if( fsync(fd) )
5091#endif
5092 {
dane18d4952011-02-21 11:46:24 +00005093 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005094 }
drh0e9365c2011-03-02 02:08:13 +00005095 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005096 }
5097 }
danielk1977d138dd82008-10-15 16:02:48 +00005098#endif
danielk1977fee2d252007-08-18 10:59:19 +00005099 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005100}
5101
danielk197790949c22007-08-17 16:50:38 +00005102/*
5103** Test the existance of or access permissions of file zPath. The
5104** test performed depends on the value of flags:
5105**
5106** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5107** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5108** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5109**
5110** Otherwise return 0.
5111*/
danielk1977861f7452008-06-05 11:39:11 +00005112static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005113 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5114 const char *zPath, /* Path of the file to examine */
5115 int flags, /* What do we want to learn about the zPath file? */
5116 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005117){
rse25c0d1a2007-09-20 08:38:14 +00005118 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005119 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005120 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005121 switch( flags ){
5122 case SQLITE_ACCESS_EXISTS:
5123 amode = F_OK;
5124 break;
5125 case SQLITE_ACCESS_READWRITE:
5126 amode = W_OK|R_OK;
5127 break;
drh50d3f902007-08-27 21:10:36 +00005128 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005129 amode = R_OK;
5130 break;
5131
5132 default:
5133 assert(!"Invalid flags argument");
5134 }
drh99ab3b12011-03-02 15:09:07 +00005135 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005136 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5137 struct stat buf;
5138 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5139 *pResOut = 0;
5140 }
5141 }
danielk1977861f7452008-06-05 11:39:11 +00005142 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005143}
5144
danielk1977b4b47412007-08-17 15:53:36 +00005145
5146/*
5147** Turn a relative pathname into a full pathname. The relative path
5148** is stored as a nul-terminated string in the buffer pointed to by
5149** zPath.
5150**
5151** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5152** (in this case, MAX_PATHNAME bytes). The full-path is written to
5153** this buffer before returning.
5154*/
danielk1977adfb9b02007-09-17 07:02:56 +00005155static int unixFullPathname(
5156 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5157 const char *zPath, /* Possibly relative input path */
5158 int nOut, /* Size of output buffer in bytes */
5159 char *zOut /* Output buffer */
5160){
danielk1977843e65f2007-09-01 16:16:15 +00005161
5162 /* It's odd to simulate an io-error here, but really this is just
5163 ** using the io-error infrastructure to test that SQLite handles this
5164 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005165 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005166 */
5167 SimulateIOError( return SQLITE_ERROR );
5168
drh153c62c2007-08-24 03:51:33 +00005169 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005170 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005171
drh3c7f2dc2007-12-06 13:26:20 +00005172 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005173 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005174 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005175 }else{
5176 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005177 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005178 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005179 }
drhea678832008-12-10 19:26:22 +00005180 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005181 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005182 }
5183 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005184}
5185
drh0ccebe72005-06-07 22:22:50 +00005186
drh761df872006-12-21 01:29:22 +00005187#ifndef SQLITE_OMIT_LOAD_EXTENSION
5188/*
5189** Interfaces for opening a shared library, finding entry points
5190** within the shared library, and closing the shared library.
5191*/
5192#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005193static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5194 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005195 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5196}
danielk197795c8a542007-09-01 06:51:27 +00005197
5198/*
5199** SQLite calls this function immediately after a call to unixDlSym() or
5200** unixDlOpen() fails (returns a null pointer). If a more detailed error
5201** message is available, it is written to zBufOut. If no error message
5202** is available, zBufOut is left unmodified and SQLite uses a default
5203** error message.
5204*/
danielk1977397d65f2008-11-19 11:35:39 +00005205static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005206 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005207 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005208 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005209 zErr = dlerror();
5210 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005211 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005212 }
drh6c7d5c52008-11-21 20:32:33 +00005213 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005214}
drh1875f7a2008-12-08 18:19:17 +00005215static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5216 /*
5217 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5218 ** cast into a pointer to a function. And yet the library dlsym() routine
5219 ** returns a void* which is really a pointer to a function. So how do we
5220 ** use dlsym() with -pedantic-errors?
5221 **
5222 ** Variable x below is defined to be a pointer to a function taking
5223 ** parameters void* and const char* and returning a pointer to a function.
5224 ** We initialize x by assigning it a pointer to the dlsym() function.
5225 ** (That assignment requires a cast.) Then we call the function that
5226 ** x points to.
5227 **
5228 ** This work-around is unlikely to work correctly on any system where
5229 ** you really cannot cast a function pointer into void*. But then, on the
5230 ** other hand, dlsym() will not work on such a system either, so we have
5231 ** not really lost anything.
5232 */
5233 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005234 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005235 x = (void(*(*)(void*,const char*))(void))dlsym;
5236 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005237}
danielk1977397d65f2008-11-19 11:35:39 +00005238static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5239 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005240 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005241}
danielk1977b4b47412007-08-17 15:53:36 +00005242#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5243 #define unixDlOpen 0
5244 #define unixDlError 0
5245 #define unixDlSym 0
5246 #define unixDlClose 0
5247#endif
5248
5249/*
danielk197790949c22007-08-17 16:50:38 +00005250** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005251*/
danielk1977397d65f2008-11-19 11:35:39 +00005252static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5253 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005254 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005255
drhbbd42a62004-05-22 17:41:58 +00005256 /* We have to initialize zBuf to prevent valgrind from reporting
5257 ** errors. The reports issued by valgrind are incorrect - we would
5258 ** prefer that the randomness be increased by making use of the
5259 ** uninitialized space in zBuf - but valgrind errors tend to worry
5260 ** some users. Rather than argue, it seems easier just to initialize
5261 ** the whole array and silence valgrind, even if that means less randomness
5262 ** in the random seed.
5263 **
5264 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005265 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005266 ** tests repeatable.
5267 */
danielk1977b4b47412007-08-17 15:53:36 +00005268 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005269#if !defined(SQLITE_TEST)
5270 {
drh842b8642005-01-21 17:53:17 +00005271 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005272 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005273 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005274 time_t t;
5275 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005276 memcpy(zBuf, &t, sizeof(t));
5277 pid = getpid();
5278 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005279 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005280 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005281 }else{
drhe562be52011-03-02 18:01:10 +00005282 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005283 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005284 }
drhbbd42a62004-05-22 17:41:58 +00005285 }
5286#endif
drh72cbd072008-10-14 17:58:38 +00005287 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005288}
5289
danielk1977b4b47412007-08-17 15:53:36 +00005290
drhbbd42a62004-05-22 17:41:58 +00005291/*
5292** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005293** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005294** The return value is the number of microseconds of sleep actually
5295** requested from the underlying operating system, a number which
5296** might be greater than or equal to the argument, but not less
5297** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005298*/
danielk1977397d65f2008-11-19 11:35:39 +00005299static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005300#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005301 struct timespec sp;
5302
5303 sp.tv_sec = microseconds / 1000000;
5304 sp.tv_nsec = (microseconds % 1000000) * 1000;
5305 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005306 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005307 return microseconds;
5308#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005309 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005310 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005311 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005312#else
danielk1977b4b47412007-08-17 15:53:36 +00005313 int seconds = (microseconds+999999)/1000000;
5314 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005315 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005316 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005317#endif
drh88f474a2006-01-02 20:00:12 +00005318}
5319
5320/*
drh6b9d6dd2008-12-03 19:34:47 +00005321** The following variable, if set to a non-zero value, is interpreted as
5322** the number of seconds since 1970 and is used to set the result of
5323** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005324*/
5325#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005326int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005327#endif
5328
5329/*
drhb7e8ea22010-05-03 14:32:30 +00005330** Find the current time (in Universal Coordinated Time). Write into *piNow
5331** the current time and date as a Julian Day number times 86_400_000. In
5332** other words, write into *piNow the number of milliseconds since the Julian
5333** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5334** proleptic Gregorian calendar.
5335**
5336** On success, return 0. Return 1 if the time and date cannot be found.
5337*/
5338static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5339 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5340#if defined(NO_GETTOD)
5341 time_t t;
5342 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005343 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005344#elif OS_VXWORKS
5345 struct timespec sNow;
5346 clock_gettime(CLOCK_REALTIME, &sNow);
5347 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5348#else
5349 struct timeval sNow;
5350 gettimeofday(&sNow, 0);
5351 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5352#endif
5353
5354#ifdef SQLITE_TEST
5355 if( sqlite3_current_time ){
5356 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5357 }
5358#endif
5359 UNUSED_PARAMETER(NotUsed);
5360 return 0;
5361}
5362
5363/*
drhbbd42a62004-05-22 17:41:58 +00005364** Find the current time (in Universal Coordinated Time). Write the
5365** current time and date as a Julian Day number into *prNow and
5366** return 0. Return 1 if the time and date cannot be found.
5367*/
danielk1977397d65f2008-11-19 11:35:39 +00005368static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005369 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005370 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005371 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005372 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005373 return 0;
5374}
danielk1977b4b47412007-08-17 15:53:36 +00005375
drh6b9d6dd2008-12-03 19:34:47 +00005376/*
5377** We added the xGetLastError() method with the intention of providing
5378** better low-level error messages when operating-system problems come up
5379** during SQLite operation. But so far, none of that has been implemented
5380** in the core. So this routine is never called. For now, it is merely
5381** a place-holder.
5382*/
danielk1977397d65f2008-11-19 11:35:39 +00005383static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5384 UNUSED_PARAMETER(NotUsed);
5385 UNUSED_PARAMETER(NotUsed2);
5386 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005387 return 0;
5388}
5389
drhf2424c52010-04-26 00:04:55 +00005390
5391/*
drh734c9862008-11-28 15:37:20 +00005392************************ End of sqlite3_vfs methods ***************************
5393******************************************************************************/
5394
drh715ff302008-12-03 22:32:44 +00005395/******************************************************************************
5396************************** Begin Proxy Locking ********************************
5397**
5398** Proxy locking is a "uber-locking-method" in this sense: It uses the
5399** other locking methods on secondary lock files. Proxy locking is a
5400** meta-layer over top of the primitive locking implemented above. For
5401** this reason, the division that implements of proxy locking is deferred
5402** until late in the file (here) after all of the other I/O methods have
5403** been defined - so that the primitive locking methods are available
5404** as services to help with the implementation of proxy locking.
5405**
5406****
5407**
5408** The default locking schemes in SQLite use byte-range locks on the
5409** database file to coordinate safe, concurrent access by multiple readers
5410** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5411** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5412** as POSIX read & write locks over fixed set of locations (via fsctl),
5413** on AFP and SMB only exclusive byte-range locks are available via fsctl
5414** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5415** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5416** address in the shared range is taken for a SHARED lock, the entire
5417** shared range is taken for an EXCLUSIVE lock):
5418**
5419** PENDING_BYTE 0x40000000
5420** RESERVED_BYTE 0x40000001
5421** SHARED_RANGE 0x40000002 -> 0x40000200
5422**
5423** This works well on the local file system, but shows a nearly 100x
5424** slowdown in read performance on AFP because the AFP client disables
5425** the read cache when byte-range locks are present. Enabling the read
5426** cache exposes a cache coherency problem that is present on all OS X
5427** supported network file systems. NFS and AFP both observe the
5428** close-to-open semantics for ensuring cache coherency
5429** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5430** address the requirements for concurrent database access by multiple
5431** readers and writers
5432** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5433**
5434** To address the performance and cache coherency issues, proxy file locking
5435** changes the way database access is controlled by limiting access to a
5436** single host at a time and moving file locks off of the database file
5437** and onto a proxy file on the local file system.
5438**
5439**
5440** Using proxy locks
5441** -----------------
5442**
5443** C APIs
5444**
5445** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5446** <proxy_path> | ":auto:");
5447** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5448**
5449**
5450** SQL pragmas
5451**
5452** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5453** PRAGMA [database.]lock_proxy_file
5454**
5455** Specifying ":auto:" means that if there is a conch file with a matching
5456** host ID in it, the proxy path in the conch file will be used, otherwise
5457** a proxy path based on the user's temp dir
5458** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5459** actual proxy file name is generated from the name and path of the
5460** database file. For example:
5461**
5462** For database path "/Users/me/foo.db"
5463** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5464**
5465** Once a lock proxy is configured for a database connection, it can not
5466** be removed, however it may be switched to a different proxy path via
5467** the above APIs (assuming the conch file is not being held by another
5468** connection or process).
5469**
5470**
5471** How proxy locking works
5472** -----------------------
5473**
5474** Proxy file locking relies primarily on two new supporting files:
5475**
5476** * conch file to limit access to the database file to a single host
5477** at a time
5478**
5479** * proxy file to act as a proxy for the advisory locks normally
5480** taken on the database
5481**
5482** The conch file - to use a proxy file, sqlite must first "hold the conch"
5483** by taking an sqlite-style shared lock on the conch file, reading the
5484** contents and comparing the host's unique host ID (see below) and lock
5485** proxy path against the values stored in the conch. The conch file is
5486** stored in the same directory as the database file and the file name
5487** is patterned after the database file name as ".<databasename>-conch".
5488** If the conch file does not exist, or it's contents do not match the
5489** host ID and/or proxy path, then the lock is escalated to an exclusive
5490** lock and the conch file contents is updated with the host ID and proxy
5491** path and the lock is downgraded to a shared lock again. If the conch
5492** is held by another process (with a shared lock), the exclusive lock
5493** will fail and SQLITE_BUSY is returned.
5494**
5495** The proxy file - a single-byte file used for all advisory file locks
5496** normally taken on the database file. This allows for safe sharing
5497** of the database file for multiple readers and writers on the same
5498** host (the conch ensures that they all use the same local lock file).
5499**
drh715ff302008-12-03 22:32:44 +00005500** Requesting the lock proxy does not immediately take the conch, it is
5501** only taken when the first request to lock database file is made.
5502** This matches the semantics of the traditional locking behavior, where
5503** opening a connection to a database file does not take a lock on it.
5504** The shared lock and an open file descriptor are maintained until
5505** the connection to the database is closed.
5506**
5507** The proxy file and the lock file are never deleted so they only need
5508** to be created the first time they are used.
5509**
5510** Configuration options
5511** ---------------------
5512**
5513** SQLITE_PREFER_PROXY_LOCKING
5514**
5515** Database files accessed on non-local file systems are
5516** automatically configured for proxy locking, lock files are
5517** named automatically using the same logic as
5518** PRAGMA lock_proxy_file=":auto:"
5519**
5520** SQLITE_PROXY_DEBUG
5521**
5522** Enables the logging of error messages during host id file
5523** retrieval and creation
5524**
drh715ff302008-12-03 22:32:44 +00005525** LOCKPROXYDIR
5526**
5527** Overrides the default directory used for lock proxy files that
5528** are named automatically via the ":auto:" setting
5529**
5530** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5531**
5532** Permissions to use when creating a directory for storing the
5533** lock proxy files, only used when LOCKPROXYDIR is not set.
5534**
5535**
5536** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5537** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5538** force proxy locking to be used for every database file opened, and 0
5539** will force automatic proxy locking to be disabled for all database
5540** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5541** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5542*/
5543
5544/*
5545** Proxy locking is only available on MacOSX
5546*/
drhd2cb50b2009-01-09 21:41:17 +00005547#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005548
drh715ff302008-12-03 22:32:44 +00005549/*
5550** The proxyLockingContext has the path and file structures for the remote
5551** and local proxy files in it
5552*/
5553typedef struct proxyLockingContext proxyLockingContext;
5554struct proxyLockingContext {
5555 unixFile *conchFile; /* Open conch file */
5556 char *conchFilePath; /* Name of the conch file */
5557 unixFile *lockProxy; /* Open proxy lock file */
5558 char *lockProxyPath; /* Name of the proxy lock file */
5559 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005560 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005561 void *oldLockingContext; /* Original lockingcontext to restore on close */
5562 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5563};
5564
drh7ed97b92010-01-20 13:07:21 +00005565/*
5566** The proxy lock file path for the database at dbPath is written into lPath,
5567** which must point to valid, writable memory large enough for a maxLen length
5568** file path.
drh715ff302008-12-03 22:32:44 +00005569*/
drh715ff302008-12-03 22:32:44 +00005570static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5571 int len;
5572 int dbLen;
5573 int i;
5574
5575#ifdef LOCKPROXYDIR
5576 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5577#else
5578# ifdef _CS_DARWIN_USER_TEMP_DIR
5579 {
drh7ed97b92010-01-20 13:07:21 +00005580 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005581 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5582 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005583 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005584 }
drh7ed97b92010-01-20 13:07:21 +00005585 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005586 }
5587# else
5588 len = strlcpy(lPath, "/tmp/", maxLen);
5589# endif
5590#endif
5591
5592 if( lPath[len-1]!='/' ){
5593 len = strlcat(lPath, "/", maxLen);
5594 }
5595
5596 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005597 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005598 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005599 char c = dbPath[i];
5600 lPath[i+len] = (c=='/')?'_':c;
5601 }
5602 lPath[i+len]='\0';
5603 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005604 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005605 return SQLITE_OK;
5606}
5607
drh7ed97b92010-01-20 13:07:21 +00005608/*
5609 ** Creates the lock file and any missing directories in lockPath
5610 */
5611static int proxyCreateLockPath(const char *lockPath){
5612 int i, len;
5613 char buf[MAXPATHLEN];
5614 int start = 0;
5615
5616 assert(lockPath!=NULL);
5617 /* try to create all the intermediate directories */
5618 len = (int)strlen(lockPath);
5619 buf[0] = lockPath[0];
5620 for( i=1; i<len; i++ ){
5621 if( lockPath[i] == '/' && (i - start > 0) ){
5622 /* only mkdir if leaf dir != "." or "/" or ".." */
5623 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5624 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5625 buf[i]='\0';
5626 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5627 int err=errno;
5628 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005629 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005630 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005631 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005632 return err;
5633 }
5634 }
5635 }
5636 start=i+1;
5637 }
5638 buf[i] = lockPath[i];
5639 }
drh308c2a52010-05-14 11:30:18 +00005640 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005641 return 0;
5642}
5643
drh715ff302008-12-03 22:32:44 +00005644/*
5645** Create a new VFS file descriptor (stored in memory obtained from
5646** sqlite3_malloc) and open the file named "path" in the file descriptor.
5647**
5648** The caller is responsible not only for closing the file descriptor
5649** but also for freeing the memory associated with the file descriptor.
5650*/
drh7ed97b92010-01-20 13:07:21 +00005651static int proxyCreateUnixFile(
5652 const char *path, /* path for the new unixFile */
5653 unixFile **ppFile, /* unixFile created and returned by ref */
5654 int islockfile /* if non zero missing dirs will be created */
5655) {
5656 int fd = -1;
5657 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005658 unixFile *pNew;
5659 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005660 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005661 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005662 int terrno = 0;
5663 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005664
drh7ed97b92010-01-20 13:07:21 +00005665 /* 1. first try to open/create the file
5666 ** 2. if that fails, and this is a lock file (not-conch), try creating
5667 ** the parent directories and then try again.
5668 ** 3. if that fails, try to open the file read-only
5669 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5670 */
5671 pUnused = findReusableFd(path, openFlags);
5672 if( pUnused ){
5673 fd = pUnused->fd;
5674 }else{
5675 pUnused = sqlite3_malloc(sizeof(*pUnused));
5676 if( !pUnused ){
5677 return SQLITE_NOMEM;
5678 }
5679 }
5680 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005681 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005682 terrno = errno;
5683 if( fd<0 && errno==ENOENT && islockfile ){
5684 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005685 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005686 }
5687 }
5688 }
5689 if( fd<0 ){
5690 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005691 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005692 terrno = errno;
5693 }
5694 if( fd<0 ){
5695 if( islockfile ){
5696 return SQLITE_BUSY;
5697 }
5698 switch (terrno) {
5699 case EACCES:
5700 return SQLITE_PERM;
5701 case EIO:
5702 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5703 default:
drh9978c972010-02-23 17:36:32 +00005704 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005705 }
5706 }
5707
5708 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5709 if( pNew==NULL ){
5710 rc = SQLITE_NOMEM;
5711 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005712 }
5713 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005714 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005715 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005716 pUnused->fd = fd;
5717 pUnused->flags = openFlags;
5718 pNew->pUnused = pUnused;
5719
5720 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5721 if( rc==SQLITE_OK ){
5722 *ppFile = pNew;
5723 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005724 }
drh7ed97b92010-01-20 13:07:21 +00005725end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005726 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005727 sqlite3_free(pNew);
5728 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005729 return rc;
5730}
5731
drh7ed97b92010-01-20 13:07:21 +00005732#ifdef SQLITE_TEST
5733/* simulate multiple hosts by creating unique hostid file paths */
5734int sqlite3_hostid_num = 0;
5735#endif
5736
5737#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5738
drh0ab216a2010-07-02 17:10:40 +00005739/* Not always defined in the headers as it ought to be */
5740extern int gethostuuid(uuid_t id, const struct timespec *wait);
5741
drh7ed97b92010-01-20 13:07:21 +00005742/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5743** bytes of writable memory.
5744*/
5745static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005746 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5747 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005748#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5749 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005750 {
5751 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5752 if( gethostuuid(pHostID, &timeout) ){
5753 int err = errno;
5754 if( pError ){
5755 *pError = err;
5756 }
5757 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005758 }
drh7ed97b92010-01-20 13:07:21 +00005759 }
drhe8b0c9b2010-09-25 14:13:17 +00005760#endif
drh7ed97b92010-01-20 13:07:21 +00005761#ifdef SQLITE_TEST
5762 /* simulate multiple hosts by creating unique hostid file paths */
5763 if( sqlite3_hostid_num != 0){
5764 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5765 }
5766#endif
5767
5768 return SQLITE_OK;
5769}
5770
5771/* The conch file contains the header, host id and lock file path
5772 */
5773#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5774#define PROXY_HEADERLEN 1 /* conch file header length */
5775#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5776#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5777
5778/*
5779** Takes an open conch file, copies the contents to a new path and then moves
5780** it back. The newly created file's file descriptor is assigned to the
5781** conch file structure and finally the original conch file descriptor is
5782** closed. Returns zero if successful.
5783*/
5784static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5785 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5786 unixFile *conchFile = pCtx->conchFile;
5787 char tPath[MAXPATHLEN];
5788 char buf[PROXY_MAXCONCHLEN];
5789 char *cPath = pCtx->conchFilePath;
5790 size_t readLen = 0;
5791 size_t pathLen = 0;
5792 char errmsg[64] = "";
5793 int fd = -1;
5794 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005795 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005796
5797 /* create a new path by replace the trailing '-conch' with '-break' */
5798 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5799 if( pathLen>MAXPATHLEN || pathLen<6 ||
5800 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005801 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005802 goto end_breaklock;
5803 }
5804 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005805 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005806 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005807 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005808 goto end_breaklock;
5809 }
5810 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005811 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5812 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005813 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005814 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005815 goto end_breaklock;
5816 }
drhe562be52011-03-02 18:01:10 +00005817 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005818 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005819 goto end_breaklock;
5820 }
5821 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005822 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005823 goto end_breaklock;
5824 }
5825 rc = 0;
5826 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005827 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005828 conchFile->h = fd;
5829 conchFile->openFlags = O_RDWR | O_CREAT;
5830
5831end_breaklock:
5832 if( rc ){
5833 if( fd>=0 ){
5834 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005835 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005836 }
5837 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5838 }
5839 return rc;
5840}
5841
5842/* Take the requested lock on the conch file and break a stale lock if the
5843** host id matches.
5844*/
5845static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5846 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5847 unixFile *conchFile = pCtx->conchFile;
5848 int rc = SQLITE_OK;
5849 int nTries = 0;
5850 struct timespec conchModTime;
5851
5852 do {
5853 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5854 nTries ++;
5855 if( rc==SQLITE_BUSY ){
5856 /* If the lock failed (busy):
5857 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5858 * 2nd try: fail if the mod time changed or host id is different, wait
5859 * 10 sec and try again
5860 * 3rd try: break the lock unless the mod time has changed.
5861 */
5862 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005863 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005864 pFile->lastErrno = errno;
5865 return SQLITE_IOERR_LOCK;
5866 }
5867
5868 if( nTries==1 ){
5869 conchModTime = buf.st_mtimespec;
5870 usleep(500000); /* wait 0.5 sec and try the lock again*/
5871 continue;
5872 }
5873
5874 assert( nTries>1 );
5875 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5876 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5877 return SQLITE_BUSY;
5878 }
5879
5880 if( nTries==2 ){
5881 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005882 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005883 if( len<0 ){
5884 pFile->lastErrno = errno;
5885 return SQLITE_IOERR_LOCK;
5886 }
5887 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5888 /* don't break the lock if the host id doesn't match */
5889 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5890 return SQLITE_BUSY;
5891 }
5892 }else{
5893 /* don't break the lock on short read or a version mismatch */
5894 return SQLITE_BUSY;
5895 }
5896 usleep(10000000); /* wait 10 sec and try the lock again */
5897 continue;
5898 }
5899
5900 assert( nTries==3 );
5901 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5902 rc = SQLITE_OK;
5903 if( lockType==EXCLUSIVE_LOCK ){
5904 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5905 }
5906 if( !rc ){
5907 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5908 }
5909 }
5910 }
5911 } while( rc==SQLITE_BUSY && nTries<3 );
5912
5913 return rc;
5914}
5915
5916/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005917** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5918** lockPath means that the lockPath in the conch file will be used if the
5919** host IDs match, or a new lock path will be generated automatically
5920** and written to the conch file.
5921*/
5922static int proxyTakeConch(unixFile *pFile){
5923 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5924
drh7ed97b92010-01-20 13:07:21 +00005925 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005926 return SQLITE_OK;
5927 }else{
5928 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005929 uuid_t myHostID;
5930 int pError = 0;
5931 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005932 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005933 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005934 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005935 int createConch = 0;
5936 int hostIdMatch = 0;
5937 int readLen = 0;
5938 int tryOldLockPath = 0;
5939 int forceNewLockPath = 0;
5940
drh308c2a52010-05-14 11:30:18 +00005941 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5942 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005943
drh7ed97b92010-01-20 13:07:21 +00005944 rc = proxyGetHostID(myHostID, &pError);
5945 if( (rc&0xff)==SQLITE_IOERR ){
5946 pFile->lastErrno = pError;
5947 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005948 }
drh7ed97b92010-01-20 13:07:21 +00005949 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005950 if( rc!=SQLITE_OK ){
5951 goto end_takeconch;
5952 }
drh7ed97b92010-01-20 13:07:21 +00005953 /* read the existing conch file */
5954 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5955 if( readLen<0 ){
5956 /* I/O error: lastErrno set by seekAndRead */
5957 pFile->lastErrno = conchFile->lastErrno;
5958 rc = SQLITE_IOERR_READ;
5959 goto end_takeconch;
5960 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5961 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5962 /* a short read or version format mismatch means we need to create a new
5963 ** conch file.
5964 */
5965 createConch = 1;
5966 }
5967 /* if the host id matches and the lock path already exists in the conch
5968 ** we'll try to use the path there, if we can't open that path, we'll
5969 ** retry with a new auto-generated path
5970 */
5971 do { /* in case we need to try again for an :auto: named lock file */
5972
5973 if( !createConch && !forceNewLockPath ){
5974 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5975 PROXY_HOSTIDLEN);
5976 /* if the conch has data compare the contents */
5977 if( !pCtx->lockProxyPath ){
5978 /* for auto-named local lock file, just check the host ID and we'll
5979 ** use the local lock file path that's already in there
5980 */
5981 if( hostIdMatch ){
5982 size_t pathLen = (readLen - PROXY_PATHINDEX);
5983
5984 if( pathLen>=MAXPATHLEN ){
5985 pathLen=MAXPATHLEN-1;
5986 }
5987 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5988 lockPath[pathLen] = 0;
5989 tempLockPath = lockPath;
5990 tryOldLockPath = 1;
5991 /* create a copy of the lock path if the conch is taken */
5992 goto end_takeconch;
5993 }
5994 }else if( hostIdMatch
5995 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5996 readLen-PROXY_PATHINDEX)
5997 ){
5998 /* conch host and lock path match */
5999 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006000 }
drh7ed97b92010-01-20 13:07:21 +00006001 }
6002
6003 /* if the conch isn't writable and doesn't match, we can't take it */
6004 if( (conchFile->openFlags&O_RDWR) == 0 ){
6005 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006006 goto end_takeconch;
6007 }
drh7ed97b92010-01-20 13:07:21 +00006008
6009 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006010 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006011 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6012 tempLockPath = lockPath;
6013 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006014 }
drh7ed97b92010-01-20 13:07:21 +00006015
6016 /* update conch with host and path (this will fail if other process
6017 ** has a shared lock already), if the host id matches, use the big
6018 ** stick.
drh715ff302008-12-03 22:32:44 +00006019 */
drh7ed97b92010-01-20 13:07:21 +00006020 futimes(conchFile->h, NULL);
6021 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006022 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006023 /* We are trying for an exclusive lock but another thread in this
6024 ** same process is still holding a shared lock. */
6025 rc = SQLITE_BUSY;
6026 } else {
6027 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006028 }
drh715ff302008-12-03 22:32:44 +00006029 }else{
drh7ed97b92010-01-20 13:07:21 +00006030 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006031 }
drh7ed97b92010-01-20 13:07:21 +00006032 if( rc==SQLITE_OK ){
6033 char writeBuffer[PROXY_MAXCONCHLEN];
6034 int writeSize = 0;
6035
6036 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6037 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6038 if( pCtx->lockProxyPath!=NULL ){
6039 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6040 }else{
6041 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6042 }
6043 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006044 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006045 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6046 fsync(conchFile->h);
6047 /* If we created a new conch file (not just updated the contents of a
6048 ** valid conch file), try to match the permissions of the database
6049 */
6050 if( rc==SQLITE_OK && createConch ){
6051 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006052 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006053 if( err==0 ){
6054 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6055 S_IROTH|S_IWOTH);
6056 /* try to match the database file R/W permissions, ignore failure */
6057#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006058 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006059#else
drhff812312011-02-23 13:33:46 +00006060 do{
drhe562be52011-03-02 18:01:10 +00006061 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006062 }while( rc==(-1) && errno==EINTR );
6063 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006064 int code = errno;
6065 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6066 cmode, code, strerror(code));
6067 } else {
6068 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6069 }
6070 }else{
6071 int code = errno;
6072 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6073 err, code, strerror(code));
6074#endif
6075 }
drh715ff302008-12-03 22:32:44 +00006076 }
6077 }
drh7ed97b92010-01-20 13:07:21 +00006078 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6079
6080 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006081 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006082 if( rc==SQLITE_OK && pFile->openFlags ){
6083 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006084 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006085 }
6086 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006087 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006088 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006089 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006090 if( fd>=0 ){
6091 pFile->h = fd;
6092 }else{
drh9978c972010-02-23 17:36:32 +00006093 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006094 during locking */
6095 }
6096 }
6097 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6098 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6099 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6100 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6101 /* we couldn't create the proxy lock file with the old lock file path
6102 ** so try again via auto-naming
6103 */
6104 forceNewLockPath = 1;
6105 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006106 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006107 }
6108 }
6109 if( rc==SQLITE_OK ){
6110 /* Need to make a copy of path if we extracted the value
6111 ** from the conch file or the path was allocated on the stack
6112 */
6113 if( tempLockPath ){
6114 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6115 if( !pCtx->lockProxyPath ){
6116 rc = SQLITE_NOMEM;
6117 }
6118 }
6119 }
6120 if( rc==SQLITE_OK ){
6121 pCtx->conchHeld = 1;
6122
6123 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6124 afpLockingContext *afpCtx;
6125 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6126 afpCtx->dbPath = pCtx->lockProxyPath;
6127 }
6128 } else {
6129 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6130 }
drh308c2a52010-05-14 11:30:18 +00006131 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6132 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006133 return rc;
drh308c2a52010-05-14 11:30:18 +00006134 } while (1); /* in case we need to retry the :auto: lock file -
6135 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006136 }
6137}
6138
6139/*
6140** If pFile holds a lock on a conch file, then release that lock.
6141*/
6142static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006143 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006144 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6145 unixFile *conchFile; /* Name of the conch file */
6146
6147 pCtx = (proxyLockingContext *)pFile->lockingContext;
6148 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006149 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006150 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006151 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006152 if( pCtx->conchHeld>0 ){
6153 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6154 }
drh715ff302008-12-03 22:32:44 +00006155 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006156 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6157 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006158 return rc;
6159}
6160
6161/*
6162** Given the name of a database file, compute the name of its conch file.
6163** Store the conch filename in memory obtained from sqlite3_malloc().
6164** Make *pConchPath point to the new name. Return SQLITE_OK on success
6165** or SQLITE_NOMEM if unable to obtain memory.
6166**
6167** The caller is responsible for ensuring that the allocated memory
6168** space is eventually freed.
6169**
6170** *pConchPath is set to NULL if a memory allocation error occurs.
6171*/
6172static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6173 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006174 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006175 char *conchPath; /* buffer in which to construct conch name */
6176
6177 /* Allocate space for the conch filename and initialize the name to
6178 ** the name of the original database file. */
6179 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6180 if( conchPath==0 ){
6181 return SQLITE_NOMEM;
6182 }
6183 memcpy(conchPath, dbPath, len+1);
6184
6185 /* now insert a "." before the last / character */
6186 for( i=(len-1); i>=0; i-- ){
6187 if( conchPath[i]=='/' ){
6188 i++;
6189 break;
6190 }
6191 }
6192 conchPath[i]='.';
6193 while ( i<len ){
6194 conchPath[i+1]=dbPath[i];
6195 i++;
6196 }
6197
6198 /* append the "-conch" suffix to the file */
6199 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006200 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006201
6202 return SQLITE_OK;
6203}
6204
6205
6206/* Takes a fully configured proxy locking-style unix file and switches
6207** the local lock file path
6208*/
6209static int switchLockProxyPath(unixFile *pFile, const char *path) {
6210 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6211 char *oldPath = pCtx->lockProxyPath;
6212 int rc = SQLITE_OK;
6213
drh308c2a52010-05-14 11:30:18 +00006214 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006215 return SQLITE_BUSY;
6216 }
6217
6218 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6219 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6220 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6221 return SQLITE_OK;
6222 }else{
6223 unixFile *lockProxy = pCtx->lockProxy;
6224 pCtx->lockProxy=NULL;
6225 pCtx->conchHeld = 0;
6226 if( lockProxy!=NULL ){
6227 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6228 if( rc ) return rc;
6229 sqlite3_free(lockProxy);
6230 }
6231 sqlite3_free(oldPath);
6232 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6233 }
6234
6235 return rc;
6236}
6237
6238/*
6239** pFile is a file that has been opened by a prior xOpen call. dbPath
6240** is a string buffer at least MAXPATHLEN+1 characters in size.
6241**
6242** This routine find the filename associated with pFile and writes it
6243** int dbPath.
6244*/
6245static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006246#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006247 if( pFile->pMethod == &afpIoMethods ){
6248 /* afp style keeps a reference to the db path in the filePath field
6249 ** of the struct */
drhea678832008-12-10 19:26:22 +00006250 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006251 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6252 } else
drh715ff302008-12-03 22:32:44 +00006253#endif
6254 if( pFile->pMethod == &dotlockIoMethods ){
6255 /* dot lock style uses the locking context to store the dot lock
6256 ** file path */
6257 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6258 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6259 }else{
6260 /* all other styles use the locking context to store the db file path */
6261 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006262 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006263 }
6264 return SQLITE_OK;
6265}
6266
6267/*
6268** Takes an already filled in unix file and alters it so all file locking
6269** will be performed on the local proxy lock file. The following fields
6270** are preserved in the locking context so that they can be restored and
6271** the unix structure properly cleaned up at close time:
6272** ->lockingContext
6273** ->pMethod
6274*/
6275static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6276 proxyLockingContext *pCtx;
6277 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6278 char *lockPath=NULL;
6279 int rc = SQLITE_OK;
6280
drh308c2a52010-05-14 11:30:18 +00006281 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006282 return SQLITE_BUSY;
6283 }
6284 proxyGetDbPathForUnixFile(pFile, dbPath);
6285 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6286 lockPath=NULL;
6287 }else{
6288 lockPath=(char *)path;
6289 }
6290
drh308c2a52010-05-14 11:30:18 +00006291 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6292 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006293
6294 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6295 if( pCtx==0 ){
6296 return SQLITE_NOMEM;
6297 }
6298 memset(pCtx, 0, sizeof(*pCtx));
6299
6300 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6301 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006302 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6303 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6304 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6305 ** (c) the file system is read-only, then enable no-locking access.
6306 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6307 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6308 */
6309 struct statfs fsInfo;
6310 struct stat conchInfo;
6311 int goLockless = 0;
6312
drh99ab3b12011-03-02 15:09:07 +00006313 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006314 int err = errno;
6315 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6316 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6317 }
6318 }
6319 if( goLockless ){
6320 pCtx->conchHeld = -1; /* read only FS/ lockless */
6321 rc = SQLITE_OK;
6322 }
6323 }
drh715ff302008-12-03 22:32:44 +00006324 }
6325 if( rc==SQLITE_OK && lockPath ){
6326 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6327 }
6328
6329 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006330 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6331 if( pCtx->dbPath==NULL ){
6332 rc = SQLITE_NOMEM;
6333 }
6334 }
6335 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006336 /* all memory is allocated, proxys are created and assigned,
6337 ** switch the locking context and pMethod then return.
6338 */
drh715ff302008-12-03 22:32:44 +00006339 pCtx->oldLockingContext = pFile->lockingContext;
6340 pFile->lockingContext = pCtx;
6341 pCtx->pOldMethod = pFile->pMethod;
6342 pFile->pMethod = &proxyIoMethods;
6343 }else{
6344 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006345 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006346 sqlite3_free(pCtx->conchFile);
6347 }
drhd56b1212010-08-11 06:14:15 +00006348 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006349 sqlite3_free(pCtx->conchFilePath);
6350 sqlite3_free(pCtx);
6351 }
drh308c2a52010-05-14 11:30:18 +00006352 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6353 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006354 return rc;
6355}
6356
6357
6358/*
6359** This routine handles sqlite3_file_control() calls that are specific
6360** to proxy locking.
6361*/
6362static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6363 switch( op ){
6364 case SQLITE_GET_LOCKPROXYFILE: {
6365 unixFile *pFile = (unixFile*)id;
6366 if( pFile->pMethod == &proxyIoMethods ){
6367 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6368 proxyTakeConch(pFile);
6369 if( pCtx->lockProxyPath ){
6370 *(const char **)pArg = pCtx->lockProxyPath;
6371 }else{
6372 *(const char **)pArg = ":auto: (not held)";
6373 }
6374 } else {
6375 *(const char **)pArg = NULL;
6376 }
6377 return SQLITE_OK;
6378 }
6379 case SQLITE_SET_LOCKPROXYFILE: {
6380 unixFile *pFile = (unixFile*)id;
6381 int rc = SQLITE_OK;
6382 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6383 if( pArg==NULL || (const char *)pArg==0 ){
6384 if( isProxyStyle ){
6385 /* turn off proxy locking - not supported */
6386 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6387 }else{
6388 /* turn off proxy locking - already off - NOOP */
6389 rc = SQLITE_OK;
6390 }
6391 }else{
6392 const char *proxyPath = (const char *)pArg;
6393 if( isProxyStyle ){
6394 proxyLockingContext *pCtx =
6395 (proxyLockingContext*)pFile->lockingContext;
6396 if( !strcmp(pArg, ":auto:")
6397 || (pCtx->lockProxyPath &&
6398 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6399 ){
6400 rc = SQLITE_OK;
6401 }else{
6402 rc = switchLockProxyPath(pFile, proxyPath);
6403 }
6404 }else{
6405 /* turn on proxy file locking */
6406 rc = proxyTransformUnixFile(pFile, proxyPath);
6407 }
6408 }
6409 return rc;
6410 }
6411 default: {
6412 assert( 0 ); /* The call assures that only valid opcodes are sent */
6413 }
6414 }
6415 /*NOTREACHED*/
6416 return SQLITE_ERROR;
6417}
6418
6419/*
6420** Within this division (the proxying locking implementation) the procedures
6421** above this point are all utilities. The lock-related methods of the
6422** proxy-locking sqlite3_io_method object follow.
6423*/
6424
6425
6426/*
6427** This routine checks if there is a RESERVED lock held on the specified
6428** file by this or any other process. If such a lock is held, set *pResOut
6429** to a non-zero value otherwise *pResOut is set to zero. The return value
6430** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6431*/
6432static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6433 unixFile *pFile = (unixFile*)id;
6434 int rc = proxyTakeConch(pFile);
6435 if( rc==SQLITE_OK ){
6436 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006437 if( pCtx->conchHeld>0 ){
6438 unixFile *proxy = pCtx->lockProxy;
6439 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6440 }else{ /* conchHeld < 0 is lockless */
6441 pResOut=0;
6442 }
drh715ff302008-12-03 22:32:44 +00006443 }
6444 return rc;
6445}
6446
6447/*
drh308c2a52010-05-14 11:30:18 +00006448** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006449** of the following:
6450**
6451** (1) SHARED_LOCK
6452** (2) RESERVED_LOCK
6453** (3) PENDING_LOCK
6454** (4) EXCLUSIVE_LOCK
6455**
6456** Sometimes when requesting one lock state, additional lock states
6457** are inserted in between. The locking might fail on one of the later
6458** transitions leaving the lock state different from what it started but
6459** still short of its goal. The following chart shows the allowed
6460** transitions and the inserted intermediate states:
6461**
6462** UNLOCKED -> SHARED
6463** SHARED -> RESERVED
6464** SHARED -> (PENDING) -> EXCLUSIVE
6465** RESERVED -> (PENDING) -> EXCLUSIVE
6466** PENDING -> EXCLUSIVE
6467**
6468** This routine will only increase a lock. Use the sqlite3OsUnlock()
6469** routine to lower a locking level.
6470*/
drh308c2a52010-05-14 11:30:18 +00006471static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006472 unixFile *pFile = (unixFile*)id;
6473 int rc = proxyTakeConch(pFile);
6474 if( rc==SQLITE_OK ){
6475 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006476 if( pCtx->conchHeld>0 ){
6477 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006478 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6479 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006480 }else{
6481 /* conchHeld < 0 is lockless */
6482 }
drh715ff302008-12-03 22:32:44 +00006483 }
6484 return rc;
6485}
6486
6487
6488/*
drh308c2a52010-05-14 11:30:18 +00006489** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006490** must be either NO_LOCK or SHARED_LOCK.
6491**
6492** If the locking level of the file descriptor is already at or below
6493** the requested locking level, this routine is a no-op.
6494*/
drh308c2a52010-05-14 11:30:18 +00006495static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006496 unixFile *pFile = (unixFile*)id;
6497 int rc = proxyTakeConch(pFile);
6498 if( rc==SQLITE_OK ){
6499 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006500 if( pCtx->conchHeld>0 ){
6501 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006502 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6503 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006504 }else{
6505 /* conchHeld < 0 is lockless */
6506 }
drh715ff302008-12-03 22:32:44 +00006507 }
6508 return rc;
6509}
6510
6511/*
6512** Close a file that uses proxy locks.
6513*/
6514static int proxyClose(sqlite3_file *id) {
6515 if( id ){
6516 unixFile *pFile = (unixFile*)id;
6517 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6518 unixFile *lockProxy = pCtx->lockProxy;
6519 unixFile *conchFile = pCtx->conchFile;
6520 int rc = SQLITE_OK;
6521
6522 if( lockProxy ){
6523 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6524 if( rc ) return rc;
6525 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6526 if( rc ) return rc;
6527 sqlite3_free(lockProxy);
6528 pCtx->lockProxy = 0;
6529 }
6530 if( conchFile ){
6531 if( pCtx->conchHeld ){
6532 rc = proxyReleaseConch(pFile);
6533 if( rc ) return rc;
6534 }
6535 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6536 if( rc ) return rc;
6537 sqlite3_free(conchFile);
6538 }
drhd56b1212010-08-11 06:14:15 +00006539 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006540 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006541 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006542 /* restore the original locking context and pMethod then close it */
6543 pFile->lockingContext = pCtx->oldLockingContext;
6544 pFile->pMethod = pCtx->pOldMethod;
6545 sqlite3_free(pCtx);
6546 return pFile->pMethod->xClose(id);
6547 }
6548 return SQLITE_OK;
6549}
6550
6551
6552
drhd2cb50b2009-01-09 21:41:17 +00006553#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006554/*
6555** The proxy locking style is intended for use with AFP filesystems.
6556** And since AFP is only supported on MacOSX, the proxy locking is also
6557** restricted to MacOSX.
6558**
6559**
6560******************* End of the proxy lock implementation **********************
6561******************************************************************************/
6562
drh734c9862008-11-28 15:37:20 +00006563/*
danielk1977e339d652008-06-28 11:23:00 +00006564** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006565**
6566** This routine registers all VFS implementations for unix-like operating
6567** systems. This routine, and the sqlite3_os_end() routine that follows,
6568** should be the only routines in this file that are visible from other
6569** files.
drh6b9d6dd2008-12-03 19:34:47 +00006570**
6571** This routine is called once during SQLite initialization and by a
6572** single thread. The memory allocation and mutex subsystems have not
6573** necessarily been initialized when this routine is called, and so they
6574** should not be used.
drh153c62c2007-08-24 03:51:33 +00006575*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006576int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006577 /*
6578 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006579 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6580 ** to the "finder" function. (pAppData is a pointer to a pointer because
6581 ** silly C90 rules prohibit a void* from being cast to a function pointer
6582 ** and so we have to go through the intermediate pointer to avoid problems
6583 ** when compiling with -pedantic-errors on GCC.)
6584 **
6585 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006586 ** finder-function. The finder-function returns a pointer to the
6587 ** sqlite_io_methods object that implements the desired locking
6588 ** behaviors. See the division above that contains the IOMETHODS
6589 ** macro for addition information on finder-functions.
6590 **
6591 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6592 ** object. But the "autolockIoFinder" available on MacOSX does a little
6593 ** more than that; it looks at the filesystem type that hosts the
6594 ** database file and tries to choose an locking method appropriate for
6595 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006596 */
drh7708e972008-11-29 00:56:52 +00006597 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006598 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006599 sizeof(unixFile), /* szOsFile */ \
6600 MAX_PATHNAME, /* mxPathname */ \
6601 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006602 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006603 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006604 unixOpen, /* xOpen */ \
6605 unixDelete, /* xDelete */ \
6606 unixAccess, /* xAccess */ \
6607 unixFullPathname, /* xFullPathname */ \
6608 unixDlOpen, /* xDlOpen */ \
6609 unixDlError, /* xDlError */ \
6610 unixDlSym, /* xDlSym */ \
6611 unixDlClose, /* xDlClose */ \
6612 unixRandomness, /* xRandomness */ \
6613 unixSleep, /* xSleep */ \
6614 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006615 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006616 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006617 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006618 unixGetSystemCall, /* xGetSystemCall */ \
6619 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006620 }
6621
drh6b9d6dd2008-12-03 19:34:47 +00006622 /*
6623 ** All default VFSes for unix are contained in the following array.
6624 **
6625 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6626 ** by the SQLite core when the VFS is registered. So the following
6627 ** array cannot be const.
6628 */
danielk1977e339d652008-06-28 11:23:00 +00006629 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006630#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006631 UNIXVFS("unix", autolockIoFinder ),
6632#else
6633 UNIXVFS("unix", posixIoFinder ),
6634#endif
6635 UNIXVFS("unix-none", nolockIoFinder ),
6636 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006637 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006638#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006639 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006640#endif
6641#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006642 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006643#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006644 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006645#endif
chw78a13182009-04-07 05:35:03 +00006646#endif
drhd2cb50b2009-01-09 21:41:17 +00006647#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006648 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006649 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006650 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006651#endif
drh153c62c2007-08-24 03:51:33 +00006652 };
drh6b9d6dd2008-12-03 19:34:47 +00006653 unsigned int i; /* Loop counter */
6654
6655 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006656 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006657 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006658 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006659 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006660}
danielk1977e339d652008-06-28 11:23:00 +00006661
6662/*
drh6b9d6dd2008-12-03 19:34:47 +00006663** Shutdown the operating system interface.
6664**
6665** Some operating systems might need to do some cleanup in this routine,
6666** to release dynamically allocated objects. But not on unix.
6667** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006668*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006669int sqlite3_os_end(void){
6670 return SQLITE_OK;
6671}
drhdce8bdb2007-08-16 13:01:44 +00006672
danielk197729bafea2008-06-26 10:41:19 +00006673#endif /* SQLITE_OS_UNIX */