blob: d2263addc643f04933d476d387bb5b11d2cdc43d [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
209 int lastErrno; /* The unix errno from last I/O error */
210 void *lockingContext; /* Locking style specific state */
211 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
212 int fileFlags; /* Miscellanous flags */
213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drh0c2694b2009-09-03 16:23:44 +0000247** The following macros define bits in unixFile.fileFlags
248*/
249#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
250
251/*
drh198bf392006-01-06 21:52:49 +0000252** Include code that is common to all os_*.c files
253*/
254#include "os_common.h"
255
256/*
drh0ccebe72005-06-07 22:22:50 +0000257** Define various macros that are missing from some systems.
258*/
drhbbd42a62004-05-22 17:41:58 +0000259#ifndef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifdef SQLITE_DISABLE_LFS
263# undef O_LARGEFILE
264# define O_LARGEFILE 0
265#endif
266#ifndef O_NOFOLLOW
267# define O_NOFOLLOW 0
268#endif
269#ifndef O_BINARY
270# define O_BINARY 0
271#endif
272
273/*
drh2b4b5962005-06-15 17:47:55 +0000274** The threadid macro resolves to the thread-id or to 0. Used for
275** testing and debugging only.
276*/
drhd677b3d2007-08-20 22:48:41 +0000277#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000278#define threadid pthread_self()
279#else
280#define threadid 0
281#endif
282
drh99ab3b12011-03-02 15:09:07 +0000283/*
284** Many system calls are accessed through pointer-to-functions so that
285** they may be overridden at runtime to facilitate fault injection during
286** testing and sandboxing. The following array holds the names and pointers
287** to all overrideable system calls.
288*/
289static struct unix_syscall {
290 const char *zName; /* Name of the sytem call */
291 void *pCurrent; /* Current value of the system call */
292 void *pDefault; /* Default value */
293} aSyscall[] = {
294 { "open", (void*)open, 0 },
295#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
296
297 { "close", (void*)close, 0 },
298#define osClose ((int(*)(int))aSyscall[1].pCurrent)
299
300 { "access", (void*)access, 0 },
301#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
302
303 { "getcwd", (void*)getcwd, 0 },
304#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
305
306 { "stat", (void*)stat, 0 },
307#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
308
309/*
310** The DJGPP compiler environment looks mostly like Unix, but it
311** lacks the fcntl() system call. So redefine fcntl() to be something
312** that always succeeds. This means that locking does not occur under
313** DJGPP. But it is DOS - what did you expect?
314*/
315#ifdef __DJGPP__
316 { "fstat", 0, 0 },
317#define osFstat(a,b,c) 0
318#else
319 { "fstat", (void*)fstat, 0 },
320#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
321#endif
322
323 { "ftruncate", (void*)ftruncate, 0 },
324#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
325
326 { "fcntl", (void*)fcntl, 0 },
327#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
328};
329
330/*
331** This is the xSetSystemCall() method of sqlite3_vfs for all of the
332** "unix" VFSes.
333*/
334static int unixSetSystemCall(
335 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
336 const char *zName, /* Name of system call to override */
337 void *pNewFunc /* Pointer to new system call value */
338){
339 int i;
340 int rc = 0;
341 if( zName==0 ){
342 /* If no zName is given, restore all system calls to their default
343 ** settings and return NULL
344 */
345 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
346 if( aSyscall[i].pDefault ){
347 aSyscall[i].pCurrent = aSyscall[i].pDefault;
348 rc = 1;
349 }
350 }
351 }else{
352 /* If zName is specified, operate on only the one system call
353 ** specified.
354 */
355 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
356 if( strcmp(zName, aSyscall[i].zName)==0 ){
357 if( aSyscall[i].pDefault==0 ){
358 aSyscall[i].pDefault = aSyscall[i].pCurrent;
359 }
360 rc = 1;
361 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
362 aSyscall[i].pCurrent = pNewFunc;
363 break;
364 }
365 }
366 }
367 return rc;
368}
369
danielk197713adf8a2004-06-03 16:08:41 +0000370
drh107886a2008-11-21 22:21:50 +0000371/*
dan9359c7b2009-08-21 08:29:10 +0000372** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000373** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000374** vxworksFileId objects used by this file, all of which may be
375** shared by multiple threads.
376**
377** Function unixMutexHeld() is used to assert() that the global mutex
378** is held when required. This function is only used as part of assert()
379** statements. e.g.
380**
381** unixEnterMutex()
382** assert( unixMutexHeld() );
383** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000384*/
385static void unixEnterMutex(void){
386 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
387}
388static void unixLeaveMutex(void){
389 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
390}
dan9359c7b2009-08-21 08:29:10 +0000391#ifdef SQLITE_DEBUG
392static int unixMutexHeld(void) {
393 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
394}
395#endif
drh107886a2008-11-21 22:21:50 +0000396
drh734c9862008-11-28 15:37:20 +0000397
398#ifdef SQLITE_DEBUG
399/*
400** Helper function for printing out trace information from debugging
401** binaries. This returns the string represetation of the supplied
402** integer lock-type.
403*/
drh308c2a52010-05-14 11:30:18 +0000404static const char *azFileLock(int eFileLock){
405 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000406 case NO_LOCK: return "NONE";
407 case SHARED_LOCK: return "SHARED";
408 case RESERVED_LOCK: return "RESERVED";
409 case PENDING_LOCK: return "PENDING";
410 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000411 }
412 return "ERROR";
413}
414#endif
415
416#ifdef SQLITE_LOCK_TRACE
417/*
418** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000419**
drh734c9862008-11-28 15:37:20 +0000420** This routine is used for troubleshooting locks on multithreaded
421** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
422** command-line option on the compiler. This code is normally
423** turned off.
424*/
425static int lockTrace(int fd, int op, struct flock *p){
426 char *zOpName, *zType;
427 int s;
428 int savedErrno;
429 if( op==F_GETLK ){
430 zOpName = "GETLK";
431 }else if( op==F_SETLK ){
432 zOpName = "SETLK";
433 }else{
drh99ab3b12011-03-02 15:09:07 +0000434 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000435 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
436 return s;
437 }
438 if( p->l_type==F_RDLCK ){
439 zType = "RDLCK";
440 }else if( p->l_type==F_WRLCK ){
441 zType = "WRLCK";
442 }else if( p->l_type==F_UNLCK ){
443 zType = "UNLCK";
444 }else{
445 assert( 0 );
446 }
447 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000448 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000449 savedErrno = errno;
450 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
451 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
452 (int)p->l_pid, s);
453 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
454 struct flock l2;
455 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000456 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000457 if( l2.l_type==F_RDLCK ){
458 zType = "RDLCK";
459 }else if( l2.l_type==F_WRLCK ){
460 zType = "WRLCK";
461 }else if( l2.l_type==F_UNLCK ){
462 zType = "UNLCK";
463 }else{
464 assert( 0 );
465 }
466 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
467 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
468 }
469 errno = savedErrno;
470 return s;
471}
drh99ab3b12011-03-02 15:09:07 +0000472#undef osFcntl
473#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000474#endif /* SQLITE_LOCK_TRACE */
475
476
drhff812312011-02-23 13:33:46 +0000477/*
478** Retry ftruncate() calls that fail due to EINTR
479*/
480#ifdef EINTR
481static int robust_ftruncate(int h, sqlite3_int64 sz){
482 int rc;
drh99ab3b12011-03-02 15:09:07 +0000483 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000484 return rc;
485}
486#else
drh99ab3b12011-03-02 15:09:07 +0000487# define robust_ftruncate(a,b) osFtruncate(a,b)
drhff812312011-02-23 13:33:46 +0000488#endif
489
drh734c9862008-11-28 15:37:20 +0000490
491/*
492** This routine translates a standard POSIX errno code into something
493** useful to the clients of the sqlite3 functions. Specifically, it is
494** intended to translate a variety of "try again" errors into SQLITE_BUSY
495** and a variety of "please close the file descriptor NOW" errors into
496** SQLITE_IOERR
497**
498** Errors during initialization of locks, or file system support for locks,
499** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
500*/
501static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
502 switch (posixError) {
503 case 0:
504 return SQLITE_OK;
505
506 case EAGAIN:
507 case ETIMEDOUT:
508 case EBUSY:
509 case EINTR:
510 case ENOLCK:
511 /* random NFS retry error, unless during file system support
512 * introspection, in which it actually means what it says */
513 return SQLITE_BUSY;
514
515 case EACCES:
516 /* EACCES is like EAGAIN during locking operations, but not any other time*/
517 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
518 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
519 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
520 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
521 return SQLITE_BUSY;
522 }
523 /* else fall through */
524 case EPERM:
525 return SQLITE_PERM;
526
527 case EDEADLK:
528 return SQLITE_IOERR_BLOCKED;
529
530#if EOPNOTSUPP!=ENOTSUP
531 case EOPNOTSUPP:
532 /* something went terribly awry, unless during file system support
533 * introspection, in which it actually means what it says */
534#endif
535#ifdef ENOTSUP
536 case ENOTSUP:
537 /* invalid fd, unless during file system support introspection, in which
538 * it actually means what it says */
539#endif
540 case EIO:
541 case EBADF:
542 case EINVAL:
543 case ENOTCONN:
544 case ENODEV:
545 case ENXIO:
546 case ENOENT:
547 case ESTALE:
548 case ENOSYS:
549 /* these should force the client to close the file and reconnect */
550
551 default:
552 return sqliteIOErr;
553 }
554}
555
556
557
558/******************************************************************************
559****************** Begin Unique File ID Utility Used By VxWorks ***************
560**
561** On most versions of unix, we can get a unique ID for a file by concatenating
562** the device number and the inode number. But this does not work on VxWorks.
563** On VxWorks, a unique file id must be based on the canonical filename.
564**
565** A pointer to an instance of the following structure can be used as a
566** unique file ID in VxWorks. Each instance of this structure contains
567** a copy of the canonical filename. There is also a reference count.
568** The structure is reclaimed when the number of pointers to it drops to
569** zero.
570**
571** There are never very many files open at one time and lookups are not
572** a performance-critical path, so it is sufficient to put these
573** structures on a linked list.
574*/
575struct vxworksFileId {
576 struct vxworksFileId *pNext; /* Next in a list of them all */
577 int nRef; /* Number of references to this one */
578 int nName; /* Length of the zCanonicalName[] string */
579 char *zCanonicalName; /* Canonical filename */
580};
581
582#if OS_VXWORKS
583/*
drh9b35ea62008-11-29 02:20:26 +0000584** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000585** variable:
586*/
587static struct vxworksFileId *vxworksFileList = 0;
588
589/*
590** Simplify a filename into its canonical form
591** by making the following changes:
592**
593** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000594** * convert /./ into just /
595** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000596**
597** Changes are made in-place. Return the new name length.
598**
599** The original filename is in z[0..n-1]. Return the number of
600** characters in the simplified name.
601*/
602static int vxworksSimplifyName(char *z, int n){
603 int i, j;
604 while( n>1 && z[n-1]=='/' ){ n--; }
605 for(i=j=0; i<n; i++){
606 if( z[i]=='/' ){
607 if( z[i+1]=='/' ) continue;
608 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
609 i += 1;
610 continue;
611 }
612 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
613 while( j>0 && z[j-1]!='/' ){ j--; }
614 if( j>0 ){ j--; }
615 i += 2;
616 continue;
617 }
618 }
619 z[j++] = z[i];
620 }
621 z[j] = 0;
622 return j;
623}
624
625/*
626** Find a unique file ID for the given absolute pathname. Return
627** a pointer to the vxworksFileId object. This pointer is the unique
628** file ID.
629**
630** The nRef field of the vxworksFileId object is incremented before
631** the object is returned. A new vxworksFileId object is created
632** and added to the global list if necessary.
633**
634** If a memory allocation error occurs, return NULL.
635*/
636static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
637 struct vxworksFileId *pNew; /* search key and new file ID */
638 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
639 int n; /* Length of zAbsoluteName string */
640
641 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000642 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000643 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
644 if( pNew==0 ) return 0;
645 pNew->zCanonicalName = (char*)&pNew[1];
646 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
647 n = vxworksSimplifyName(pNew->zCanonicalName, n);
648
649 /* Search for an existing entry that matching the canonical name.
650 ** If found, increment the reference count and return a pointer to
651 ** the existing file ID.
652 */
653 unixEnterMutex();
654 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
655 if( pCandidate->nName==n
656 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
657 ){
658 sqlite3_free(pNew);
659 pCandidate->nRef++;
660 unixLeaveMutex();
661 return pCandidate;
662 }
663 }
664
665 /* No match was found. We will make a new file ID */
666 pNew->nRef = 1;
667 pNew->nName = n;
668 pNew->pNext = vxworksFileList;
669 vxworksFileList = pNew;
670 unixLeaveMutex();
671 return pNew;
672}
673
674/*
675** Decrement the reference count on a vxworksFileId object. Free
676** the object when the reference count reaches zero.
677*/
678static void vxworksReleaseFileId(struct vxworksFileId *pId){
679 unixEnterMutex();
680 assert( pId->nRef>0 );
681 pId->nRef--;
682 if( pId->nRef==0 ){
683 struct vxworksFileId **pp;
684 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
685 assert( *pp==pId );
686 *pp = pId->pNext;
687 sqlite3_free(pId);
688 }
689 unixLeaveMutex();
690}
691#endif /* OS_VXWORKS */
692/*************** End of Unique File ID Utility Used By VxWorks ****************
693******************************************************************************/
694
695
696/******************************************************************************
697*************************** Posix Advisory Locking ****************************
698**
drh9b35ea62008-11-29 02:20:26 +0000699** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000700** section 6.5.2.2 lines 483 through 490 specify that when a process
701** sets or clears a lock, that operation overrides any prior locks set
702** by the same process. It does not explicitly say so, but this implies
703** that it overrides locks set by the same process using a different
704** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000705**
706** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000707** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
708**
709** Suppose ./file1 and ./file2 are really the same file (because
710** one is a hard or symbolic link to the other) then if you set
711** an exclusive lock on fd1, then try to get an exclusive lock
712** on fd2, it works. I would have expected the second lock to
713** fail since there was already a lock on the file due to fd1.
714** But not so. Since both locks came from the same process, the
715** second overrides the first, even though they were on different
716** file descriptors opened on different file names.
717**
drh734c9862008-11-28 15:37:20 +0000718** This means that we cannot use POSIX locks to synchronize file access
719** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000720** to synchronize access for threads in separate processes, but not
721** threads within the same process.
722**
723** To work around the problem, SQLite has to manage file locks internally
724** on its own. Whenever a new database is opened, we have to find the
725** specific inode of the database file (the inode is determined by the
726** st_dev and st_ino fields of the stat structure that fstat() fills in)
727** and check for locks already existing on that inode. When locks are
728** created or removed, we have to look at our own internal record of the
729** locks to see if another thread has previously set a lock on that same
730** inode.
731**
drh9b35ea62008-11-29 02:20:26 +0000732** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
733** For VxWorks, we have to use the alternative unique ID system based on
734** canonical filename and implemented in the previous division.)
735**
danielk1977ad94b582007-08-20 06:44:22 +0000736** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000737** descriptor. It is now a structure that holds the integer file
738** descriptor and a pointer to a structure that describes the internal
739** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000740** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000741** point to the same locking structure. The locking structure keeps
742** a reference count (so we will know when to delete it) and a "cnt"
743** field that tells us its internal lock status. cnt==0 means the
744** file is unlocked. cnt==-1 means the file has an exclusive lock.
745** cnt>0 means there are cnt shared locks on the file.
746**
747** Any attempt to lock or unlock a file first checks the locking
748** structure. The fcntl() system call is only invoked to set a
749** POSIX lock if the internal lock structure transitions between
750** a locked and an unlocked state.
751**
drh734c9862008-11-28 15:37:20 +0000752** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000753**
754** If you close a file descriptor that points to a file that has locks,
755** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000756** released. To work around this problem, each unixInodeInfo object
757** maintains a count of the number of pending locks on tha inode.
758** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000759** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000760** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000761** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000762** be closed and that list is walked (and cleared) when the last lock
763** clears.
764**
drh9b35ea62008-11-29 02:20:26 +0000765** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000766**
drh9b35ea62008-11-29 02:20:26 +0000767** Many older versions of linux use the LinuxThreads library which is
768** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000769** A cannot be modified or overridden by a different thread B.
770** Only thread A can modify the lock. Locking behavior is correct
771** if the appliation uses the newer Native Posix Thread Library (NPTL)
772** on linux - with NPTL a lock created by thread A can override locks
773** in thread B. But there is no way to know at compile-time which
774** threading library is being used. So there is no way to know at
775** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000776** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000777** current process.
drh5fdae772004-06-29 03:29:00 +0000778**
drh8af6c222010-05-14 12:43:01 +0000779** SQLite used to support LinuxThreads. But support for LinuxThreads
780** was dropped beginning with version 3.7.0. SQLite will still work with
781** LinuxThreads provided that (1) there is no more than one connection
782** per database file in the same process and (2) database connections
783** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000784*/
785
786/*
787** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000788** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000789*/
790struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000791 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000792#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000793 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000794#else
drh107886a2008-11-21 22:21:50 +0000795 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000796#endif
797};
798
799/*
drhbbd42a62004-05-22 17:41:58 +0000800** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000801** inode. Or, on LinuxThreads, there is one of these structures for
802** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000803**
danielk1977ad94b582007-08-20 06:44:22 +0000804** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000805** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000806** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000807*/
drh8af6c222010-05-14 12:43:01 +0000808struct unixInodeInfo {
809 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000810 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000811 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000812 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000813 unixShmNode *pShmNode; /* Shared memory associated with this inode */
814 int nLock; /* Number of outstanding file locks */
815 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
816 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
817 unixInodeInfo *pPrev; /* .... doubly linked */
drh7ed97b92010-01-20 13:07:21 +0000818#if defined(SQLITE_ENABLE_LOCKING_STYLE)
819 unsigned long long sharedByte; /* for AFP simulated shared lock */
820#endif
drh6c7d5c52008-11-21 20:32:33 +0000821#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000822 sem_t *pSem; /* Named POSIX semaphore */
823 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000824#endif
drhbbd42a62004-05-22 17:41:58 +0000825};
826
drhda0e7682008-07-30 15:27:54 +0000827/*
drh8af6c222010-05-14 12:43:01 +0000828** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000829*/
drhd91c68f2010-05-14 14:52:25 +0000830static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000831
drh5fdae772004-06-29 03:29:00 +0000832/*
dane18d4952011-02-21 11:46:24 +0000833**
834** This function - unixLogError_x(), is only ever called via the macro
835** unixLogError().
836**
837** It is invoked after an error occurs in an OS function and errno has been
838** set. It logs a message using sqlite3_log() containing the current value of
839** errno and, if possible, the human-readable equivalent from strerror() or
840** strerror_r().
841**
842** The first argument passed to the macro should be the error code that
843** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
844** The two subsequent arguments should be the name of the OS function that
845** failed (e.g. "unlink", "open") and the the associated file-system path,
846** if any.
847*/
drh0e9365c2011-03-02 02:08:13 +0000848#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
849static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000850 int errcode, /* SQLite error code */
851 const char *zFunc, /* Name of OS function that failed */
852 const char *zPath, /* File path associated with error */
853 int iLine /* Source line number where error occurred */
854){
855 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000856 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000857
858 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
859 ** the strerror() function to obtain the human-readable error message
860 ** equivalent to errno. Otherwise, use strerror_r().
861 */
862#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
863 char aErr[80];
864 memset(aErr, 0, sizeof(aErr));
865 zErr = aErr;
866
867 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
868 ** assume that the system provides the the GNU version of strerror_r() that
869 ** returns a pointer to a buffer containing the error message. That pointer
870 ** may point to aErr[], or it may point to some static storage somewhere.
871 ** Otherwise, assume that the system provides the POSIX version of
872 ** strerror_r(), which always writes an error message into aErr[].
873 **
874 ** If the code incorrectly assumes that it is the POSIX version that is
875 ** available, the error message will often be an empty string. Not a
876 ** huge problem. Incorrectly concluding that the GNU version is available
877 ** could lead to a segfault though.
878 */
879#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
880 zErr =
881# endif
drh0e9365c2011-03-02 02:08:13 +0000882 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +0000883
884#elif SQLITE_THREADSAFE
885 /* This is a threadsafe build, but strerror_r() is not available. */
886 zErr = "";
887#else
888 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +0000889 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +0000890#endif
891
892 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +0000893 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +0000894 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +0000895 "os_unix.c:%d: (%d) %s(%s) - %s",
896 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +0000897 );
898
899 return errcode;
900}
901
drh0e9365c2011-03-02 02:08:13 +0000902/*
903** Close a file descriptor.
904**
905** We assume that close() almost always works, since it is only in a
906** very sick application or on a very sick platform that it might fail.
907** If it does fail, simply leak the file descriptor, but do log the
908** error.
909**
910** Note that it is not safe to retry close() after EINTR since the
911** file descriptor might have already been reused by another thread.
912** So we don't even try to recover from an EINTR. Just log the error
913** and move on.
914*/
915static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +0000916 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +0000917 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
918 pFile ? pFile->zPath : 0, lineno);
919 }
920}
dane18d4952011-02-21 11:46:24 +0000921
922/*
danb0ac3e32010-06-16 10:55:42 +0000923** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +0000924*/
drh0e9365c2011-03-02 02:08:13 +0000925static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +0000926 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +0000927 UnixUnusedFd *p;
928 UnixUnusedFd *pNext;
929 for(p=pInode->pUnused; p; p=pNext){
930 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +0000931 robust_close(pFile, p->fd, __LINE__);
932 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +0000933 }
drh0e9365c2011-03-02 02:08:13 +0000934 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +0000935}
936
937/*
drh8af6c222010-05-14 12:43:01 +0000938** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000939**
940** The mutex entered using the unixEnterMutex() function must be held
941** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000942*/
danb0ac3e32010-06-16 10:55:42 +0000943static void releaseInodeInfo(unixFile *pFile){
944 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +0000945 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000946 if( pInode ){
947 pInode->nRef--;
948 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +0000949 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +0000950 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +0000951 if( pInode->pPrev ){
952 assert( pInode->pPrev->pNext==pInode );
953 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000954 }else{
drh8af6c222010-05-14 12:43:01 +0000955 assert( inodeList==pInode );
956 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000957 }
drh8af6c222010-05-14 12:43:01 +0000958 if( pInode->pNext ){
959 assert( pInode->pNext->pPrev==pInode );
960 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000961 }
drh8af6c222010-05-14 12:43:01 +0000962 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000963 }
drhbbd42a62004-05-22 17:41:58 +0000964 }
965}
966
967/*
drh8af6c222010-05-14 12:43:01 +0000968** Given a file descriptor, locate the unixInodeInfo object that
969** describes that file descriptor. Create a new one if necessary. The
970** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000971**
dan9359c7b2009-08-21 08:29:10 +0000972** The mutex entered using the unixEnterMutex() function must be held
973** when this function is called.
974**
drh6c7d5c52008-11-21 20:32:33 +0000975** Return an appropriate error code.
976*/
drh8af6c222010-05-14 12:43:01 +0000977static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000978 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +0000979 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000980){
981 int rc; /* System call return code */
982 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +0000983 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
984 struct stat statbuf; /* Low-level file information */
985 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000986
dan9359c7b2009-08-21 08:29:10 +0000987 assert( unixMutexHeld() );
988
drh6c7d5c52008-11-21 20:32:33 +0000989 /* Get low-level information about the file that we can used to
990 ** create a unique name for the file.
991 */
992 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +0000993 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +0000994 if( rc!=0 ){
995 pFile->lastErrno = errno;
996#ifdef EOVERFLOW
997 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
998#endif
999 return SQLITE_IOERR;
1000 }
1001
drheb0d74f2009-02-03 15:27:02 +00001002#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001003 /* On OS X on an msdos filesystem, the inode number is reported
1004 ** incorrectly for zero-size files. See ticket #3260. To work
1005 ** around this problem (we consider it a bug in OS X, not SQLite)
1006 ** we always increase the file size to 1 by writing a single byte
1007 ** prior to accessing the inode number. The one byte written is
1008 ** an ASCII 'S' character which also happens to be the first byte
1009 ** in the header of every SQLite database. In this way, if there
1010 ** is a race condition such that another thread has already populated
1011 ** the first page of the database, no damage is done.
1012 */
drh7ed97b92010-01-20 13:07:21 +00001013 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhff812312011-02-23 13:33:46 +00001014 do{ rc = write(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001015 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001016 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001017 return SQLITE_IOERR;
1018 }
drh99ab3b12011-03-02 15:09:07 +00001019 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001020 if( rc!=0 ){
1021 pFile->lastErrno = errno;
1022 return SQLITE_IOERR;
1023 }
1024 }
drheb0d74f2009-02-03 15:27:02 +00001025#endif
drh6c7d5c52008-11-21 20:32:33 +00001026
drh8af6c222010-05-14 12:43:01 +00001027 memset(&fileId, 0, sizeof(fileId));
1028 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001029#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001030 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001031#else
drh8af6c222010-05-14 12:43:01 +00001032 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001033#endif
drh8af6c222010-05-14 12:43:01 +00001034 pInode = inodeList;
1035 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1036 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001037 }
drh8af6c222010-05-14 12:43:01 +00001038 if( pInode==0 ){
1039 pInode = sqlite3_malloc( sizeof(*pInode) );
1040 if( pInode==0 ){
1041 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001042 }
drh8af6c222010-05-14 12:43:01 +00001043 memset(pInode, 0, sizeof(*pInode));
1044 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1045 pInode->nRef = 1;
1046 pInode->pNext = inodeList;
1047 pInode->pPrev = 0;
1048 if( inodeList ) inodeList->pPrev = pInode;
1049 inodeList = pInode;
1050 }else{
1051 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001052 }
drh8af6c222010-05-14 12:43:01 +00001053 *ppInode = pInode;
1054 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001055}
drh6c7d5c52008-11-21 20:32:33 +00001056
aswift5b1a2562008-08-22 00:22:35 +00001057
1058/*
danielk197713adf8a2004-06-03 16:08:41 +00001059** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001060** file by this or any other process. If such a lock is held, set *pResOut
1061** to a non-zero value otherwise *pResOut is set to zero. The return value
1062** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001063*/
danielk1977861f7452008-06-05 11:39:11 +00001064static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001065 int rc = SQLITE_OK;
1066 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001067 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001068
danielk1977861f7452008-06-05 11:39:11 +00001069 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1070
drh054889e2005-11-30 03:20:31 +00001071 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001072 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001073
1074 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001075 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001076 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001077 }
1078
drh2ac3ee92004-06-07 16:27:46 +00001079 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001080 */
danielk197709480a92009-02-09 05:32:32 +00001081#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001082 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001083 struct flock lock;
1084 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001085 lock.l_start = RESERVED_BYTE;
1086 lock.l_len = 1;
1087 lock.l_type = F_WRLCK;
drh99ab3b12011-03-02 15:09:07 +00001088 if (-1 == osFcntl(pFile->h, F_GETLK, &lock)) {
aswift5b1a2562008-08-22 00:22:35 +00001089 int tErrno = errno;
1090 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1091 pFile->lastErrno = tErrno;
1092 } else if( lock.l_type!=F_UNLCK ){
1093 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001094 }
1095 }
danielk197709480a92009-02-09 05:32:32 +00001096#endif
danielk197713adf8a2004-06-03 16:08:41 +00001097
drh6c7d5c52008-11-21 20:32:33 +00001098 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001099 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001100
aswift5b1a2562008-08-22 00:22:35 +00001101 *pResOut = reserved;
1102 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001103}
1104
1105/*
drh308c2a52010-05-14 11:30:18 +00001106** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001107** of the following:
1108**
drh2ac3ee92004-06-07 16:27:46 +00001109** (1) SHARED_LOCK
1110** (2) RESERVED_LOCK
1111** (3) PENDING_LOCK
1112** (4) EXCLUSIVE_LOCK
1113**
drhb3e04342004-06-08 00:47:47 +00001114** Sometimes when requesting one lock state, additional lock states
1115** are inserted in between. The locking might fail on one of the later
1116** transitions leaving the lock state different from what it started but
1117** still short of its goal. The following chart shows the allowed
1118** transitions and the inserted intermediate states:
1119**
1120** UNLOCKED -> SHARED
1121** SHARED -> RESERVED
1122** SHARED -> (PENDING) -> EXCLUSIVE
1123** RESERVED -> (PENDING) -> EXCLUSIVE
1124** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001125**
drha6abd042004-06-09 17:37:22 +00001126** This routine will only increase a lock. Use the sqlite3OsUnlock()
1127** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001128*/
drh308c2a52010-05-14 11:30:18 +00001129static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001130 /* The following describes the implementation of the various locks and
1131 ** lock transitions in terms of the POSIX advisory shared and exclusive
1132 ** lock primitives (called read-locks and write-locks below, to avoid
1133 ** confusion with SQLite lock names). The algorithms are complicated
1134 ** slightly in order to be compatible with windows systems simultaneously
1135 ** accessing the same database file, in case that is ever required.
1136 **
1137 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1138 ** byte', each single bytes at well known offsets, and the 'shared byte
1139 ** range', a range of 510 bytes at a well known offset.
1140 **
1141 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1142 ** byte'. If this is successful, a random byte from the 'shared byte
1143 ** range' is read-locked and the lock on the 'pending byte' released.
1144 **
danielk197790ba3bd2004-06-25 08:32:25 +00001145 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1146 ** A RESERVED lock is implemented by grabbing a write-lock on the
1147 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001148 **
1149 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001150 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1151 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1152 ** obtained, but existing SHARED locks are allowed to persist. A process
1153 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1154 ** This property is used by the algorithm for rolling back a journal file
1155 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001156 **
danielk197790ba3bd2004-06-25 08:32:25 +00001157 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1158 ** implemented by obtaining a write-lock on the entire 'shared byte
1159 ** range'. Since all other locks require a read-lock on one of the bytes
1160 ** within this range, this ensures that no other locks are held on the
1161 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001162 **
1163 ** The reason a single byte cannot be used instead of the 'shared byte
1164 ** range' is that some versions of windows do not support read-locks. By
1165 ** locking a random byte from a range, concurrent SHARED locks may exist
1166 ** even if the locking primitive used is always a write-lock.
1167 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001168 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001169 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001170 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001171 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001172 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001173 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001174
drh054889e2005-11-30 03:20:31 +00001175 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001176 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1177 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001178 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001179
1180 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001181 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001182 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001183 */
drh308c2a52010-05-14 11:30:18 +00001184 if( pFile->eFileLock>=eFileLock ){
1185 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1186 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001187 return SQLITE_OK;
1188 }
1189
drh0c2694b2009-09-03 16:23:44 +00001190 /* Make sure the locking sequence is correct.
1191 ** (1) We never move from unlocked to anything higher than shared lock.
1192 ** (2) SQLite never explicitly requests a pendig lock.
1193 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001194 */
drh308c2a52010-05-14 11:30:18 +00001195 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1196 assert( eFileLock!=PENDING_LOCK );
1197 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001198
drh8af6c222010-05-14 12:43:01 +00001199 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001200 */
drh6c7d5c52008-11-21 20:32:33 +00001201 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001202 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001203
danielk1977ad94b582007-08-20 06:44:22 +00001204 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001205 ** handle that precludes the requested lock, return BUSY.
1206 */
drh8af6c222010-05-14 12:43:01 +00001207 if( (pFile->eFileLock!=pInode->eFileLock &&
1208 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001209 ){
1210 rc = SQLITE_BUSY;
1211 goto end_lock;
1212 }
1213
1214 /* If a SHARED lock is requested, and some thread using this PID already
1215 ** has a SHARED or RESERVED lock, then increment reference counts and
1216 ** return SQLITE_OK.
1217 */
drh308c2a52010-05-14 11:30:18 +00001218 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001219 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001220 assert( eFileLock==SHARED_LOCK );
1221 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001222 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001223 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001224 pInode->nShared++;
1225 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001226 goto end_lock;
1227 }
1228
danielk19779a1d0ab2004-06-01 14:09:28 +00001229
drh3cde3bb2004-06-12 02:17:14 +00001230 /* A PENDING lock is needed before acquiring a SHARED lock and before
1231 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1232 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001233 */
drh0c2694b2009-09-03 16:23:44 +00001234 lock.l_len = 1L;
1235 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001236 if( eFileLock==SHARED_LOCK
1237 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001238 ){
drh308c2a52010-05-14 11:30:18 +00001239 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001240 lock.l_start = PENDING_BYTE;
drh99ab3b12011-03-02 15:09:07 +00001241 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001242 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001243 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001244 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1245 if( IS_LOCK_ERROR(rc) ){
1246 pFile->lastErrno = tErrno;
1247 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001248 goto end_lock;
1249 }
drh3cde3bb2004-06-12 02:17:14 +00001250 }
1251
1252
1253 /* If control gets to this point, then actually go ahead and make
1254 ** operating system calls for the specified lock.
1255 */
drh308c2a52010-05-14 11:30:18 +00001256 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001257 assert( pInode->nShared==0 );
1258 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001259
drh2ac3ee92004-06-07 16:27:46 +00001260 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001261 lock.l_start = SHARED_FIRST;
1262 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001263 if( (s = osFcntl(pFile->h, F_SETLK, &lock))==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001264 tErrno = errno;
1265 }
drh2ac3ee92004-06-07 16:27:46 +00001266 /* Drop the temporary PENDING lock */
1267 lock.l_start = PENDING_BYTE;
1268 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001269 lock.l_type = F_UNLCK;
drh99ab3b12011-03-02 15:09:07 +00001270 if( osFcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001271 if( s != -1 ){
1272 /* This could happen with a network mount */
1273 tErrno = errno;
1274 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1275 if( IS_LOCK_ERROR(rc) ){
1276 pFile->lastErrno = tErrno;
1277 }
1278 goto end_lock;
1279 }
drh2b4b5962005-06-15 17:47:55 +00001280 }
drhe2396a12007-03-29 20:19:58 +00001281 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001282 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1283 if( IS_LOCK_ERROR(rc) ){
1284 pFile->lastErrno = tErrno;
1285 }
drhbbd42a62004-05-22 17:41:58 +00001286 }else{
drh308c2a52010-05-14 11:30:18 +00001287 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001288 pInode->nLock++;
1289 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001290 }
drh8af6c222010-05-14 12:43:01 +00001291 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001292 /* We are trying for an exclusive lock but another thread in this
1293 ** same process is still holding a shared lock. */
1294 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001295 }else{
drh3cde3bb2004-06-12 02:17:14 +00001296 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001297 ** assumed that there is a SHARED or greater lock on the file
1298 ** already.
1299 */
drh308c2a52010-05-14 11:30:18 +00001300 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001301 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001302 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001303 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001304 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001305 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001306 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001307 lock.l_start = SHARED_FIRST;
1308 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001309 break;
1310 default:
1311 assert(0);
1312 }
drh99ab3b12011-03-02 15:09:07 +00001313 s = osFcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001314 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001315 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001316 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1317 if( IS_LOCK_ERROR(rc) ){
1318 pFile->lastErrno = tErrno;
1319 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001320 }
drhbbd42a62004-05-22 17:41:58 +00001321 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001322
drh8f941bc2009-01-14 23:03:40 +00001323
1324#ifndef NDEBUG
1325 /* Set up the transaction-counter change checking flags when
1326 ** transitioning from a SHARED to a RESERVED lock. The change
1327 ** from SHARED to RESERVED marks the beginning of a normal
1328 ** write operation (not a hot journal rollback).
1329 */
1330 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001331 && pFile->eFileLock<=SHARED_LOCK
1332 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001333 ){
1334 pFile->transCntrChng = 0;
1335 pFile->dbUpdate = 0;
1336 pFile->inNormalWrite = 1;
1337 }
1338#endif
1339
1340
danielk1977ecb2a962004-06-02 06:30:16 +00001341 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001342 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001343 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001344 }else if( eFileLock==EXCLUSIVE_LOCK ){
1345 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001346 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001347 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001348
1349end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001350 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001351 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1352 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001353 return rc;
1354}
1355
1356/*
dan08da86a2009-08-21 17:18:03 +00001357** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001358** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001359*/
1360static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001361 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001362 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001363 p->pNext = pInode->pUnused;
1364 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001365 pFile->h = -1;
1366 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001367}
1368
1369/*
drh308c2a52010-05-14 11:30:18 +00001370** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001371** must be either NO_LOCK or SHARED_LOCK.
1372**
1373** If the locking level of the file descriptor is already at or below
1374** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001375**
1376** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1377** the byte range is divided into 2 parts and the first part is unlocked then
1378** set to a read lock, then the other part is simply unlocked. This works
1379** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1380** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001381*/
drh308c2a52010-05-14 11:30:18 +00001382static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001383 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001384 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001385 struct flock lock;
1386 int rc = SQLITE_OK;
1387 int h;
drh0c2694b2009-09-03 16:23:44 +00001388 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001389
drh054889e2005-11-30 03:20:31 +00001390 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001391 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001392 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001393 getpid()));
drha6abd042004-06-09 17:37:22 +00001394
drh308c2a52010-05-14 11:30:18 +00001395 assert( eFileLock<=SHARED_LOCK );
1396 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001397 return SQLITE_OK;
1398 }
drh6c7d5c52008-11-21 20:32:33 +00001399 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001400 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001401 pInode = pFile->pInode;
1402 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001403 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001404 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001405 SimulateIOErrorBenign(1);
1406 SimulateIOError( h=(-1) )
1407 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001408
1409#ifndef NDEBUG
1410 /* When reducing a lock such that other processes can start
1411 ** reading the database file again, make sure that the
1412 ** transaction counter was updated if any part of the database
1413 ** file changed. If the transaction counter is not updated,
1414 ** other connections to the same file might not realize that
1415 ** the file has changed and hence might not know to flush their
1416 ** cache. The use of a stale cache can lead to database corruption.
1417 */
dan7c246102010-04-12 19:00:29 +00001418#if 0
drh8f941bc2009-01-14 23:03:40 +00001419 assert( pFile->inNormalWrite==0
1420 || pFile->dbUpdate==0
1421 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001422#endif
drh8f941bc2009-01-14 23:03:40 +00001423 pFile->inNormalWrite = 0;
1424#endif
1425
drh7ed97b92010-01-20 13:07:21 +00001426 /* downgrading to a shared lock on NFS involves clearing the write lock
1427 ** before establishing the readlock - to avoid a race condition we downgrade
1428 ** the lock in 2 blocks, so that part of the range will be covered by a
1429 ** write lock until the rest is covered by a read lock:
1430 ** 1: [WWWWW]
1431 ** 2: [....W]
1432 ** 3: [RRRRW]
1433 ** 4: [RRRR.]
1434 */
drh308c2a52010-05-14 11:30:18 +00001435 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001436
1437#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
1438 assert( handleNFSUnlock==0 );
1439#endif
1440#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001441 if( handleNFSUnlock ){
1442 off_t divSize = SHARED_SIZE - 1;
1443
1444 lock.l_type = F_UNLCK;
1445 lock.l_whence = SEEK_SET;
1446 lock.l_start = SHARED_FIRST;
1447 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001448 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001449 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001450 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1451 if( IS_LOCK_ERROR(rc) ){
1452 pFile->lastErrno = tErrno;
1453 }
1454 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001455 }
drh7ed97b92010-01-20 13:07:21 +00001456 lock.l_type = F_RDLCK;
1457 lock.l_whence = SEEK_SET;
1458 lock.l_start = SHARED_FIRST;
1459 lock.l_len = divSize;
drh99ab3b12011-03-02 15:09:07 +00001460 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001461 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001462 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1463 if( IS_LOCK_ERROR(rc) ){
1464 pFile->lastErrno = tErrno;
1465 }
1466 goto end_unlock;
1467 }
1468 lock.l_type = F_UNLCK;
1469 lock.l_whence = SEEK_SET;
1470 lock.l_start = SHARED_FIRST+divSize;
1471 lock.l_len = SHARED_SIZE-divSize;
drh99ab3b12011-03-02 15:09:07 +00001472 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001473 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001474 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1475 if( IS_LOCK_ERROR(rc) ){
1476 pFile->lastErrno = tErrno;
1477 }
1478 goto end_unlock;
1479 }
drh30f776f2011-02-25 03:25:07 +00001480 }else
1481#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1482 {
drh7ed97b92010-01-20 13:07:21 +00001483 lock.l_type = F_RDLCK;
1484 lock.l_whence = SEEK_SET;
1485 lock.l_start = SHARED_FIRST;
1486 lock.l_len = SHARED_SIZE;
drh99ab3b12011-03-02 15:09:07 +00001487 if( osFcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001488 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001489 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1490 if( IS_LOCK_ERROR(rc) ){
1491 pFile->lastErrno = tErrno;
1492 }
1493 goto end_unlock;
1494 }
drh9c105bb2004-10-02 20:38:28 +00001495 }
1496 }
drhbbd42a62004-05-22 17:41:58 +00001497 lock.l_type = F_UNLCK;
1498 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001499 lock.l_start = PENDING_BYTE;
1500 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh99ab3b12011-03-02 15:09:07 +00001501 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001502 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001503 }else{
drh0c2694b2009-09-03 16:23:44 +00001504 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001505 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1506 if( IS_LOCK_ERROR(rc) ){
1507 pFile->lastErrno = tErrno;
1508 }
drhcd731cf2009-03-28 23:23:02 +00001509 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001510 }
drhbbd42a62004-05-22 17:41:58 +00001511 }
drh308c2a52010-05-14 11:30:18 +00001512 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001513 /* Decrement the shared lock counter. Release the lock using an
1514 ** OS call only when all threads in this same process have released
1515 ** the lock.
1516 */
drh8af6c222010-05-14 12:43:01 +00001517 pInode->nShared--;
1518 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001519 lock.l_type = F_UNLCK;
1520 lock.l_whence = SEEK_SET;
1521 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001522 SimulateIOErrorBenign(1);
1523 SimulateIOError( h=(-1) )
1524 SimulateIOErrorBenign(0);
drh99ab3b12011-03-02 15:09:07 +00001525 if( osFcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001526 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001527 }else{
drh0c2694b2009-09-03 16:23:44 +00001528 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001529 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001530 if( IS_LOCK_ERROR(rc) ){
1531 pFile->lastErrno = tErrno;
1532 }
drh8af6c222010-05-14 12:43:01 +00001533 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001534 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001535 }
drha6abd042004-06-09 17:37:22 +00001536 }
1537
drhbbd42a62004-05-22 17:41:58 +00001538 /* Decrement the count of locks against this same file. When the
1539 ** count reaches zero, close any other file descriptors whose close
1540 ** was deferred because of outstanding locks.
1541 */
drh8af6c222010-05-14 12:43:01 +00001542 pInode->nLock--;
1543 assert( pInode->nLock>=0 );
1544 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001545 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001546 }
1547 }
aswift5b1a2562008-08-22 00:22:35 +00001548
1549end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001550 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001551 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001552 return rc;
drhbbd42a62004-05-22 17:41:58 +00001553}
1554
1555/*
drh308c2a52010-05-14 11:30:18 +00001556** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001557** must be either NO_LOCK or SHARED_LOCK.
1558**
1559** If the locking level of the file descriptor is already at or below
1560** the requested locking level, this routine is a no-op.
1561*/
drh308c2a52010-05-14 11:30:18 +00001562static int unixUnlock(sqlite3_file *id, int eFileLock){
1563 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001564}
1565
1566/*
danielk1977e339d652008-06-28 11:23:00 +00001567** This function performs the parts of the "close file" operation
1568** common to all locking schemes. It closes the directory and file
1569** handles, if they are valid, and sets all fields of the unixFile
1570** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001571**
1572** It is *not* necessary to hold the mutex when this routine is called,
1573** even on VxWorks. A mutex will be acquired on VxWorks by the
1574** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001575*/
1576static int closeUnixFile(sqlite3_file *id){
1577 unixFile *pFile = (unixFile*)id;
1578 if( pFile ){
1579 if( pFile->dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001580 robust_close(pFile, pFile->dirfd, __LINE__);
1581 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001582 }
1583 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00001584 robust_close(pFile, pFile->h, __LINE__);
1585 pFile->h = -1;
danielk1977e339d652008-06-28 11:23:00 +00001586 }
drh6c7d5c52008-11-21 20:32:33 +00001587#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001588 if( pFile->pId ){
1589 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001590 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001591 }
drh107886a2008-11-21 22:21:50 +00001592 vxworksReleaseFileId(pFile->pId);
1593 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001594 }
1595#endif
drhff59a112010-05-14 20:15:51 +00001596 OSTRACE(("CLOSE %-3d\n", pFile->h));
danielk1977e339d652008-06-28 11:23:00 +00001597 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001598 sqlite3_free(pFile->pUnused);
drhff59a112010-05-14 20:15:51 +00001599 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001600 }
1601 return SQLITE_OK;
1602}
1603
1604/*
danielk1977e3026632004-06-22 11:29:02 +00001605** Close a file.
1606*/
danielk197762079062007-08-15 17:08:46 +00001607static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001608 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001609 if( id ){
1610 unixFile *pFile = (unixFile *)id;
1611 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001612 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001613 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001614 /* If there are outstanding locks, do not actually close the file just
1615 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001616 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001617 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001618 */
dan08da86a2009-08-21 17:18:03 +00001619 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001620 }
danb0ac3e32010-06-16 10:55:42 +00001621 releaseInodeInfo(pFile);
aswiftaebf4132008-11-21 00:10:35 +00001622 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001623 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001624 }
aswiftaebf4132008-11-21 00:10:35 +00001625 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001626}
1627
drh734c9862008-11-28 15:37:20 +00001628/************** End of the posix advisory lock implementation *****************
1629******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001630
drh734c9862008-11-28 15:37:20 +00001631/******************************************************************************
1632****************************** No-op Locking **********************************
1633**
1634** Of the various locking implementations available, this is by far the
1635** simplest: locking is ignored. No attempt is made to lock the database
1636** file for reading or writing.
1637**
1638** This locking mode is appropriate for use on read-only databases
1639** (ex: databases that are burned into CD-ROM, for example.) It can
1640** also be used if the application employs some external mechanism to
1641** prevent simultaneous access of the same database by two or more
1642** database connections. But there is a serious risk of database
1643** corruption if this locking mode is used in situations where multiple
1644** database connections are accessing the same database file at the same
1645** time and one or more of those connections are writing.
1646*/
drhbfe66312006-10-03 17:40:40 +00001647
drh734c9862008-11-28 15:37:20 +00001648static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1649 UNUSED_PARAMETER(NotUsed);
1650 *pResOut = 0;
1651 return SQLITE_OK;
1652}
drh734c9862008-11-28 15:37:20 +00001653static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1654 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1655 return SQLITE_OK;
1656}
drh734c9862008-11-28 15:37:20 +00001657static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1658 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1659 return SQLITE_OK;
1660}
1661
1662/*
drh9b35ea62008-11-29 02:20:26 +00001663** Close the file.
drh734c9862008-11-28 15:37:20 +00001664*/
1665static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001666 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001667}
1668
1669/******************* End of the no-op lock implementation *********************
1670******************************************************************************/
1671
1672/******************************************************************************
1673************************* Begin dot-file Locking ******************************
1674**
drh0c2694b2009-09-03 16:23:44 +00001675** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001676** files in order to control access to the database. This works on just
1677** about every filesystem imaginable. But there are serious downsides:
1678**
1679** (1) There is zero concurrency. A single reader blocks all other
1680** connections from reading or writing the database.
1681**
1682** (2) An application crash or power loss can leave stale lock files
1683** sitting around that need to be cleared manually.
1684**
1685** Nevertheless, a dotlock is an appropriate locking mode for use if no
1686** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001687**
1688** Dotfile locking works by creating a file in the same directory as the
1689** database and with the same name but with a ".lock" extension added.
1690** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1691** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001692*/
1693
1694/*
1695** The file suffix added to the data base filename in order to create the
1696** lock file.
1697*/
1698#define DOTLOCK_SUFFIX ".lock"
1699
drh7708e972008-11-29 00:56:52 +00001700/*
1701** This routine checks if there is a RESERVED lock held on the specified
1702** file by this or any other process. If such a lock is held, set *pResOut
1703** to a non-zero value otherwise *pResOut is set to zero. The return value
1704** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1705**
1706** In dotfile locking, either a lock exists or it does not. So in this
1707** variation of CheckReservedLock(), *pResOut is set to true if any lock
1708** is held on the file and false if the file is unlocked.
1709*/
drh734c9862008-11-28 15:37:20 +00001710static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1711 int rc = SQLITE_OK;
1712 int reserved = 0;
1713 unixFile *pFile = (unixFile*)id;
1714
1715 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1716
1717 assert( pFile );
1718
1719 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001720 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001721 /* Either this connection or some other connection in the same process
1722 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001723 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001724 }else{
1725 /* The lock is held if and only if the lockfile exists */
1726 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001727 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001728 }
drh308c2a52010-05-14 11:30:18 +00001729 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001730 *pResOut = reserved;
1731 return rc;
1732}
1733
drh7708e972008-11-29 00:56:52 +00001734/*
drh308c2a52010-05-14 11:30:18 +00001735** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001736** of the following:
1737**
1738** (1) SHARED_LOCK
1739** (2) RESERVED_LOCK
1740** (3) PENDING_LOCK
1741** (4) EXCLUSIVE_LOCK
1742**
1743** Sometimes when requesting one lock state, additional lock states
1744** are inserted in between. The locking might fail on one of the later
1745** transitions leaving the lock state different from what it started but
1746** still short of its goal. The following chart shows the allowed
1747** transitions and the inserted intermediate states:
1748**
1749** UNLOCKED -> SHARED
1750** SHARED -> RESERVED
1751** SHARED -> (PENDING) -> EXCLUSIVE
1752** RESERVED -> (PENDING) -> EXCLUSIVE
1753** PENDING -> EXCLUSIVE
1754**
1755** This routine will only increase a lock. Use the sqlite3OsUnlock()
1756** routine to lower a locking level.
1757**
1758** With dotfile locking, we really only support state (4): EXCLUSIVE.
1759** But we track the other locking levels internally.
1760*/
drh308c2a52010-05-14 11:30:18 +00001761static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001762 unixFile *pFile = (unixFile*)id;
1763 int fd;
1764 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001765 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001766
drh7708e972008-11-29 00:56:52 +00001767
1768 /* If we have any lock, then the lock file already exists. All we have
1769 ** to do is adjust our internal record of the lock level.
1770 */
drh308c2a52010-05-14 11:30:18 +00001771 if( pFile->eFileLock > NO_LOCK ){
1772 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001773#if !OS_VXWORKS
1774 /* Always update the timestamp on the old file */
1775 utimes(zLockFile, NULL);
1776#endif
drh7708e972008-11-29 00:56:52 +00001777 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001778 }
1779
1780 /* grab an exclusive lock */
drh99ab3b12011-03-02 15:09:07 +00001781 fd = osOpen(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001782 if( fd<0 ){
1783 /* failed to open/create the file, someone else may have stolen the lock */
1784 int tErrno = errno;
1785 if( EEXIST == tErrno ){
1786 rc = SQLITE_BUSY;
1787 } else {
1788 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1789 if( IS_LOCK_ERROR(rc) ){
1790 pFile->lastErrno = tErrno;
1791 }
1792 }
drh7708e972008-11-29 00:56:52 +00001793 return rc;
drh734c9862008-11-28 15:37:20 +00001794 }
drh0e9365c2011-03-02 02:08:13 +00001795 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001796
1797 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001798 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001799 return rc;
1800}
1801
drh7708e972008-11-29 00:56:52 +00001802/*
drh308c2a52010-05-14 11:30:18 +00001803** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001804** must be either NO_LOCK or SHARED_LOCK.
1805**
1806** If the locking level of the file descriptor is already at or below
1807** the requested locking level, this routine is a no-op.
1808**
1809** When the locking level reaches NO_LOCK, delete the lock file.
1810*/
drh308c2a52010-05-14 11:30:18 +00001811static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001812 unixFile *pFile = (unixFile*)id;
1813 char *zLockFile = (char *)pFile->lockingContext;
1814
1815 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001816 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1817 pFile->eFileLock, getpid()));
1818 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001819
1820 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001821 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001822 return SQLITE_OK;
1823 }
drh7708e972008-11-29 00:56:52 +00001824
1825 /* To downgrade to shared, simply update our internal notion of the
1826 ** lock state. No need to mess with the file on disk.
1827 */
drh308c2a52010-05-14 11:30:18 +00001828 if( eFileLock==SHARED_LOCK ){
1829 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001830 return SQLITE_OK;
1831 }
1832
drh7708e972008-11-29 00:56:52 +00001833 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001834 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001835 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001836 int rc = 0;
1837 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001838 if( ENOENT != tErrno ){
1839 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1840 }
1841 if( IS_LOCK_ERROR(rc) ){
1842 pFile->lastErrno = tErrno;
1843 }
1844 return rc;
1845 }
drh308c2a52010-05-14 11:30:18 +00001846 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001847 return SQLITE_OK;
1848}
1849
1850/*
drh9b35ea62008-11-29 02:20:26 +00001851** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001852*/
1853static int dotlockClose(sqlite3_file *id) {
1854 int rc;
1855 if( id ){
1856 unixFile *pFile = (unixFile*)id;
1857 dotlockUnlock(id, NO_LOCK);
1858 sqlite3_free(pFile->lockingContext);
1859 }
drh734c9862008-11-28 15:37:20 +00001860 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001861 return rc;
1862}
1863/****************** End of the dot-file lock implementation *******************
1864******************************************************************************/
1865
1866/******************************************************************************
1867************************** Begin flock Locking ********************************
1868**
1869** Use the flock() system call to do file locking.
1870**
drh6b9d6dd2008-12-03 19:34:47 +00001871** flock() locking is like dot-file locking in that the various
1872** fine-grain locking levels supported by SQLite are collapsed into
1873** a single exclusive lock. In other words, SHARED, RESERVED, and
1874** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1875** still works when you do this, but concurrency is reduced since
1876** only a single process can be reading the database at a time.
1877**
drh734c9862008-11-28 15:37:20 +00001878** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1879** compiling for VXWORKS.
1880*/
1881#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001882
drh6b9d6dd2008-12-03 19:34:47 +00001883/*
drhff812312011-02-23 13:33:46 +00001884** Retry flock() calls that fail with EINTR
1885*/
1886#ifdef EINTR
1887static int robust_flock(int fd, int op){
1888 int rc;
1889 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
1890 return rc;
1891}
1892#else
drh5c819272011-02-23 14:00:12 +00001893# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00001894#endif
1895
1896
1897/*
drh6b9d6dd2008-12-03 19:34:47 +00001898** This routine checks if there is a RESERVED lock held on the specified
1899** file by this or any other process. If such a lock is held, set *pResOut
1900** to a non-zero value otherwise *pResOut is set to zero. The return value
1901** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1902*/
drh734c9862008-11-28 15:37:20 +00001903static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1904 int rc = SQLITE_OK;
1905 int reserved = 0;
1906 unixFile *pFile = (unixFile*)id;
1907
1908 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1909
1910 assert( pFile );
1911
1912 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001913 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001914 reserved = 1;
1915 }
1916
1917 /* Otherwise see if some other process holds it. */
1918 if( !reserved ){
1919 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00001920 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00001921 if( !lrc ){
1922 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00001923 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00001924 if ( lrc ) {
1925 int tErrno = errno;
1926 /* unlock failed with an error */
1927 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1928 if( IS_LOCK_ERROR(lrc) ){
1929 pFile->lastErrno = tErrno;
1930 rc = lrc;
1931 }
1932 }
1933 } else {
1934 int tErrno = errno;
1935 reserved = 1;
1936 /* someone else might have it reserved */
1937 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1938 if( IS_LOCK_ERROR(lrc) ){
1939 pFile->lastErrno = tErrno;
1940 rc = lrc;
1941 }
1942 }
1943 }
drh308c2a52010-05-14 11:30:18 +00001944 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001945
1946#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1947 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1948 rc = SQLITE_OK;
1949 reserved=1;
1950 }
1951#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1952 *pResOut = reserved;
1953 return rc;
1954}
1955
drh6b9d6dd2008-12-03 19:34:47 +00001956/*
drh308c2a52010-05-14 11:30:18 +00001957** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001958** of the following:
1959**
1960** (1) SHARED_LOCK
1961** (2) RESERVED_LOCK
1962** (3) PENDING_LOCK
1963** (4) EXCLUSIVE_LOCK
1964**
1965** Sometimes when requesting one lock state, additional lock states
1966** are inserted in between. The locking might fail on one of the later
1967** transitions leaving the lock state different from what it started but
1968** still short of its goal. The following chart shows the allowed
1969** transitions and the inserted intermediate states:
1970**
1971** UNLOCKED -> SHARED
1972** SHARED -> RESERVED
1973** SHARED -> (PENDING) -> EXCLUSIVE
1974** RESERVED -> (PENDING) -> EXCLUSIVE
1975** PENDING -> EXCLUSIVE
1976**
1977** flock() only really support EXCLUSIVE locks. We track intermediate
1978** lock states in the sqlite3_file structure, but all locks SHARED or
1979** above are really EXCLUSIVE locks and exclude all other processes from
1980** access the file.
1981**
1982** This routine will only increase a lock. Use the sqlite3OsUnlock()
1983** routine to lower a locking level.
1984*/
drh308c2a52010-05-14 11:30:18 +00001985static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001986 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001987 unixFile *pFile = (unixFile*)id;
1988
1989 assert( pFile );
1990
1991 /* if we already have a lock, it is exclusive.
1992 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001993 if (pFile->eFileLock > NO_LOCK) {
1994 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001995 return SQLITE_OK;
1996 }
1997
1998 /* grab an exclusive lock */
1999
drhff812312011-02-23 13:33:46 +00002000 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002001 int tErrno = errno;
2002 /* didn't get, must be busy */
2003 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2004 if( IS_LOCK_ERROR(rc) ){
2005 pFile->lastErrno = tErrno;
2006 }
2007 } else {
2008 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002009 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002010 }
drh308c2a52010-05-14 11:30:18 +00002011 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2012 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002013#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2014 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2015 rc = SQLITE_BUSY;
2016 }
2017#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2018 return rc;
2019}
2020
drh6b9d6dd2008-12-03 19:34:47 +00002021
2022/*
drh308c2a52010-05-14 11:30:18 +00002023** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002024** must be either NO_LOCK or SHARED_LOCK.
2025**
2026** If the locking level of the file descriptor is already at or below
2027** the requested locking level, this routine is a no-op.
2028*/
drh308c2a52010-05-14 11:30:18 +00002029static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002030 unixFile *pFile = (unixFile*)id;
2031
2032 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002033 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2034 pFile->eFileLock, getpid()));
2035 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002036
2037 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002038 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002039 return SQLITE_OK;
2040 }
2041
2042 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002043 if (eFileLock==SHARED_LOCK) {
2044 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002045 return SQLITE_OK;
2046 }
2047
2048 /* no, really, unlock. */
drhff812312011-02-23 13:33:46 +00002049 int rc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002050 if (rc) {
2051 int r, tErrno = errno;
2052 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2053 if( IS_LOCK_ERROR(r) ){
2054 pFile->lastErrno = tErrno;
2055 }
2056#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2057 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2058 r = SQLITE_BUSY;
2059 }
2060#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2061
2062 return r;
2063 } else {
drh308c2a52010-05-14 11:30:18 +00002064 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002065 return SQLITE_OK;
2066 }
2067}
2068
2069/*
2070** Close a file.
2071*/
2072static int flockClose(sqlite3_file *id) {
2073 if( id ){
2074 flockUnlock(id, NO_LOCK);
2075 }
2076 return closeUnixFile(id);
2077}
2078
2079#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2080
2081/******************* End of the flock lock implementation *********************
2082******************************************************************************/
2083
2084/******************************************************************************
2085************************ Begin Named Semaphore Locking ************************
2086**
2087** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002088**
2089** Semaphore locking is like dot-lock and flock in that it really only
2090** supports EXCLUSIVE locking. Only a single process can read or write
2091** the database file at a time. This reduces potential concurrency, but
2092** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002093*/
2094#if OS_VXWORKS
2095
drh6b9d6dd2008-12-03 19:34:47 +00002096/*
2097** This routine checks if there is a RESERVED lock held on the specified
2098** file by this or any other process. If such a lock is held, set *pResOut
2099** to a non-zero value otherwise *pResOut is set to zero. The return value
2100** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2101*/
drh734c9862008-11-28 15:37:20 +00002102static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2103 int rc = SQLITE_OK;
2104 int reserved = 0;
2105 unixFile *pFile = (unixFile*)id;
2106
2107 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2108
2109 assert( pFile );
2110
2111 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002112 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002113 reserved = 1;
2114 }
2115
2116 /* Otherwise see if some other process holds it. */
2117 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002118 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002119 struct stat statBuf;
2120
2121 if( sem_trywait(pSem)==-1 ){
2122 int tErrno = errno;
2123 if( EAGAIN != tErrno ){
2124 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2125 pFile->lastErrno = tErrno;
2126 } else {
2127 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002128 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002129 }
2130 }else{
2131 /* we could have it if we want it */
2132 sem_post(pSem);
2133 }
2134 }
drh308c2a52010-05-14 11:30:18 +00002135 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002136
2137 *pResOut = reserved;
2138 return rc;
2139}
2140
drh6b9d6dd2008-12-03 19:34:47 +00002141/*
drh308c2a52010-05-14 11:30:18 +00002142** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002143** of the following:
2144**
2145** (1) SHARED_LOCK
2146** (2) RESERVED_LOCK
2147** (3) PENDING_LOCK
2148** (4) EXCLUSIVE_LOCK
2149**
2150** Sometimes when requesting one lock state, additional lock states
2151** are inserted in between. The locking might fail on one of the later
2152** transitions leaving the lock state different from what it started but
2153** still short of its goal. The following chart shows the allowed
2154** transitions and the inserted intermediate states:
2155**
2156** UNLOCKED -> SHARED
2157** SHARED -> RESERVED
2158** SHARED -> (PENDING) -> EXCLUSIVE
2159** RESERVED -> (PENDING) -> EXCLUSIVE
2160** PENDING -> EXCLUSIVE
2161**
2162** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2163** lock states in the sqlite3_file structure, but all locks SHARED or
2164** above are really EXCLUSIVE locks and exclude all other processes from
2165** access the file.
2166**
2167** This routine will only increase a lock. Use the sqlite3OsUnlock()
2168** routine to lower a locking level.
2169*/
drh308c2a52010-05-14 11:30:18 +00002170static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002171 unixFile *pFile = (unixFile*)id;
2172 int fd;
drh8af6c222010-05-14 12:43:01 +00002173 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002174 int rc = SQLITE_OK;
2175
2176 /* if we already have a lock, it is exclusive.
2177 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002178 if (pFile->eFileLock > NO_LOCK) {
2179 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002180 rc = SQLITE_OK;
2181 goto sem_end_lock;
2182 }
2183
2184 /* lock semaphore now but bail out when already locked. */
2185 if( sem_trywait(pSem)==-1 ){
2186 rc = SQLITE_BUSY;
2187 goto sem_end_lock;
2188 }
2189
2190 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002191 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002192
2193 sem_end_lock:
2194 return rc;
2195}
2196
drh6b9d6dd2008-12-03 19:34:47 +00002197/*
drh308c2a52010-05-14 11:30:18 +00002198** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002199** must be either NO_LOCK or SHARED_LOCK.
2200**
2201** If the locking level of the file descriptor is already at or below
2202** the requested locking level, this routine is a no-op.
2203*/
drh308c2a52010-05-14 11:30:18 +00002204static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002205 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002206 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002207
2208 assert( pFile );
2209 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002210 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2211 pFile->eFileLock, getpid()));
2212 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002213
2214 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002215 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002216 return SQLITE_OK;
2217 }
2218
2219 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002220 if (eFileLock==SHARED_LOCK) {
2221 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
2225 /* no, really unlock. */
2226 if ( sem_post(pSem)==-1 ) {
2227 int rc, tErrno = errno;
2228 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2229 if( IS_LOCK_ERROR(rc) ){
2230 pFile->lastErrno = tErrno;
2231 }
2232 return rc;
2233 }
drh308c2a52010-05-14 11:30:18 +00002234 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002235 return SQLITE_OK;
2236}
2237
2238/*
2239 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002240 */
drh734c9862008-11-28 15:37:20 +00002241static int semClose(sqlite3_file *id) {
2242 if( id ){
2243 unixFile *pFile = (unixFile*)id;
2244 semUnlock(id, NO_LOCK);
2245 assert( pFile );
2246 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002247 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002248 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002249 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002250 }
2251 return SQLITE_OK;
2252}
2253
2254#endif /* OS_VXWORKS */
2255/*
2256** Named semaphore locking is only available on VxWorks.
2257**
2258*************** End of the named semaphore lock implementation ****************
2259******************************************************************************/
2260
2261
2262/******************************************************************************
2263*************************** Begin AFP Locking *********************************
2264**
2265** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2266** on Apple Macintosh computers - both OS9 and OSX.
2267**
2268** Third-party implementations of AFP are available. But this code here
2269** only works on OSX.
2270*/
2271
drhd2cb50b2009-01-09 21:41:17 +00002272#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002273/*
2274** The afpLockingContext structure contains all afp lock specific state
2275*/
drhbfe66312006-10-03 17:40:40 +00002276typedef struct afpLockingContext afpLockingContext;
2277struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002278 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002279 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002280};
2281
2282struct ByteRangeLockPB2
2283{
2284 unsigned long long offset; /* offset to first byte to lock */
2285 unsigned long long length; /* nbr of bytes to lock */
2286 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2287 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2288 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2289 int fd; /* file desc to assoc this lock with */
2290};
2291
drhfd131da2007-08-07 17:13:03 +00002292#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002293
drh6b9d6dd2008-12-03 19:34:47 +00002294/*
2295** This is a utility for setting or clearing a bit-range lock on an
2296** AFP filesystem.
2297**
2298** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2299*/
2300static int afpSetLock(
2301 const char *path, /* Name of the file to be locked or unlocked */
2302 unixFile *pFile, /* Open file descriptor on path */
2303 unsigned long long offset, /* First byte to be locked */
2304 unsigned long long length, /* Number of bytes to lock */
2305 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002306){
drh6b9d6dd2008-12-03 19:34:47 +00002307 struct ByteRangeLockPB2 pb;
2308 int err;
drhbfe66312006-10-03 17:40:40 +00002309
2310 pb.unLockFlag = setLockFlag ? 0 : 1;
2311 pb.startEndFlag = 0;
2312 pb.offset = offset;
2313 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002314 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002315
drh308c2a52010-05-14 11:30:18 +00002316 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002317 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002318 offset, length));
drhbfe66312006-10-03 17:40:40 +00002319 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2320 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002321 int rc;
2322 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002323 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2324 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002325#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2326 rc = SQLITE_BUSY;
2327#else
drh734c9862008-11-28 15:37:20 +00002328 rc = sqliteErrorFromPosixError(tErrno,
2329 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002330#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002331 if( IS_LOCK_ERROR(rc) ){
2332 pFile->lastErrno = tErrno;
2333 }
2334 return rc;
drhbfe66312006-10-03 17:40:40 +00002335 } else {
aswift5b1a2562008-08-22 00:22:35 +00002336 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002337 }
2338}
2339
drh6b9d6dd2008-12-03 19:34:47 +00002340/*
2341** This routine checks if there is a RESERVED lock held on the specified
2342** file by this or any other process. If such a lock is held, set *pResOut
2343** to a non-zero value otherwise *pResOut is set to zero. The return value
2344** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2345*/
danielk1977e339d652008-06-28 11:23:00 +00002346static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002347 int rc = SQLITE_OK;
2348 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002349 unixFile *pFile = (unixFile*)id;
2350
aswift5b1a2562008-08-22 00:22:35 +00002351 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2352
2353 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002354 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002355 if( context->reserved ){
2356 *pResOut = 1;
2357 return SQLITE_OK;
2358 }
drh8af6c222010-05-14 12:43:01 +00002359 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002360
2361 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002362 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002363 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002364 }
2365
2366 /* Otherwise see if some other process holds it.
2367 */
aswift5b1a2562008-08-22 00:22:35 +00002368 if( !reserved ){
2369 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002370 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002371 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002372 /* if we succeeded in taking the reserved lock, unlock it to restore
2373 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002374 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002375 } else {
2376 /* if we failed to get the lock then someone else must have it */
2377 reserved = 1;
2378 }
2379 if( IS_LOCK_ERROR(lrc) ){
2380 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002381 }
2382 }
drhbfe66312006-10-03 17:40:40 +00002383
drh7ed97b92010-01-20 13:07:21 +00002384 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002385 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002386
2387 *pResOut = reserved;
2388 return rc;
drhbfe66312006-10-03 17:40:40 +00002389}
2390
drh6b9d6dd2008-12-03 19:34:47 +00002391/*
drh308c2a52010-05-14 11:30:18 +00002392** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002393** of the following:
2394**
2395** (1) SHARED_LOCK
2396** (2) RESERVED_LOCK
2397** (3) PENDING_LOCK
2398** (4) EXCLUSIVE_LOCK
2399**
2400** Sometimes when requesting one lock state, additional lock states
2401** are inserted in between. The locking might fail on one of the later
2402** transitions leaving the lock state different from what it started but
2403** still short of its goal. The following chart shows the allowed
2404** transitions and the inserted intermediate states:
2405**
2406** UNLOCKED -> SHARED
2407** SHARED -> RESERVED
2408** SHARED -> (PENDING) -> EXCLUSIVE
2409** RESERVED -> (PENDING) -> EXCLUSIVE
2410** PENDING -> EXCLUSIVE
2411**
2412** This routine will only increase a lock. Use the sqlite3OsUnlock()
2413** routine to lower a locking level.
2414*/
drh308c2a52010-05-14 11:30:18 +00002415static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002416 int rc = SQLITE_OK;
2417 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002418 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002419 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002420
2421 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002422 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2423 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002424 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002425
drhbfe66312006-10-03 17:40:40 +00002426 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002427 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002428 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002429 */
drh308c2a52010-05-14 11:30:18 +00002430 if( pFile->eFileLock>=eFileLock ){
2431 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2432 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002433 return SQLITE_OK;
2434 }
2435
2436 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002437 ** (1) We never move from unlocked to anything higher than shared lock.
2438 ** (2) SQLite never explicitly requests a pendig lock.
2439 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002440 */
drh308c2a52010-05-14 11:30:18 +00002441 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2442 assert( eFileLock!=PENDING_LOCK );
2443 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002444
drh8af6c222010-05-14 12:43:01 +00002445 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002446 */
drh6c7d5c52008-11-21 20:32:33 +00002447 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002448 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002449
2450 /* If some thread using this PID has a lock via a different unixFile*
2451 ** handle that precludes the requested lock, return BUSY.
2452 */
drh8af6c222010-05-14 12:43:01 +00002453 if( (pFile->eFileLock!=pInode->eFileLock &&
2454 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002455 ){
2456 rc = SQLITE_BUSY;
2457 goto afp_end_lock;
2458 }
2459
2460 /* If a SHARED lock is requested, and some thread using this PID already
2461 ** has a SHARED or RESERVED lock, then increment reference counts and
2462 ** return SQLITE_OK.
2463 */
drh308c2a52010-05-14 11:30:18 +00002464 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002465 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002466 assert( eFileLock==SHARED_LOCK );
2467 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002468 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002469 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002470 pInode->nShared++;
2471 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002472 goto afp_end_lock;
2473 }
drhbfe66312006-10-03 17:40:40 +00002474
2475 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002476 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2477 ** be released.
2478 */
drh308c2a52010-05-14 11:30:18 +00002479 if( eFileLock==SHARED_LOCK
2480 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002481 ){
2482 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002483 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002484 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002485 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002486 goto afp_end_lock;
2487 }
2488 }
2489
2490 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002491 ** operating system calls for the specified lock.
2492 */
drh308c2a52010-05-14 11:30:18 +00002493 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002494 int lrc1, lrc2, lrc1Errno;
2495 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002496
drh8af6c222010-05-14 12:43:01 +00002497 assert( pInode->nShared==0 );
2498 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002499
2500 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002501 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002502 /* note that the quality of the randomness doesn't matter that much */
2503 lk = random();
drh8af6c222010-05-14 12:43:01 +00002504 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002505 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002506 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002507 if( IS_LOCK_ERROR(lrc1) ){
2508 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002509 }
aswift5b1a2562008-08-22 00:22:35 +00002510 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002511 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002512
aswift5b1a2562008-08-22 00:22:35 +00002513 if( IS_LOCK_ERROR(lrc1) ) {
2514 pFile->lastErrno = lrc1Errno;
2515 rc = lrc1;
2516 goto afp_end_lock;
2517 } else if( IS_LOCK_ERROR(lrc2) ){
2518 rc = lrc2;
2519 goto afp_end_lock;
2520 } else if( lrc1 != SQLITE_OK ) {
2521 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002522 } else {
drh308c2a52010-05-14 11:30:18 +00002523 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002524 pInode->nLock++;
2525 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002526 }
drh8af6c222010-05-14 12:43:01 +00002527 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002528 /* We are trying for an exclusive lock but another thread in this
2529 ** same process is still holding a shared lock. */
2530 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002531 }else{
2532 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2533 ** assumed that there is a SHARED or greater lock on the file
2534 ** already.
2535 */
2536 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002537 assert( 0!=pFile->eFileLock );
2538 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002539 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002540 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002541 if( !failed ){
2542 context->reserved = 1;
2543 }
drhbfe66312006-10-03 17:40:40 +00002544 }
drh308c2a52010-05-14 11:30:18 +00002545 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002546 /* Acquire an EXCLUSIVE lock */
2547
2548 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002549 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002550 */
drh6b9d6dd2008-12-03 19:34:47 +00002551 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002552 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002553 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002554 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002555 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002556 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002557 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002558 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002559 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2560 ** a critical I/O error
2561 */
2562 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2563 SQLITE_IOERR_LOCK;
2564 goto afp_end_lock;
2565 }
2566 }else{
aswift5b1a2562008-08-22 00:22:35 +00002567 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002568 }
2569 }
aswift5b1a2562008-08-22 00:22:35 +00002570 if( failed ){
2571 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002572 }
2573 }
2574
2575 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002576 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002577 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002578 }else if( eFileLock==EXCLUSIVE_LOCK ){
2579 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002580 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002581 }
2582
2583afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002584 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002585 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2586 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002587 return rc;
2588}
2589
2590/*
drh308c2a52010-05-14 11:30:18 +00002591** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002592** must be either NO_LOCK or SHARED_LOCK.
2593**
2594** If the locking level of the file descriptor is already at or below
2595** the requested locking level, this routine is a no-op.
2596*/
drh308c2a52010-05-14 11:30:18 +00002597static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002598 int rc = SQLITE_OK;
2599 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002600 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002601 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2602 int skipShared = 0;
2603#ifdef SQLITE_TEST
2604 int h = pFile->h;
2605#endif
drhbfe66312006-10-03 17:40:40 +00002606
2607 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002608 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002609 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002610 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002611
drh308c2a52010-05-14 11:30:18 +00002612 assert( eFileLock<=SHARED_LOCK );
2613 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002614 return SQLITE_OK;
2615 }
drh6c7d5c52008-11-21 20:32:33 +00002616 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002617 pInode = pFile->pInode;
2618 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002619 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002620 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002621 SimulateIOErrorBenign(1);
2622 SimulateIOError( h=(-1) )
2623 SimulateIOErrorBenign(0);
2624
2625#ifndef NDEBUG
2626 /* When reducing a lock such that other processes can start
2627 ** reading the database file again, make sure that the
2628 ** transaction counter was updated if any part of the database
2629 ** file changed. If the transaction counter is not updated,
2630 ** other connections to the same file might not realize that
2631 ** the file has changed and hence might not know to flush their
2632 ** cache. The use of a stale cache can lead to database corruption.
2633 */
2634 assert( pFile->inNormalWrite==0
2635 || pFile->dbUpdate==0
2636 || pFile->transCntrChng==1 );
2637 pFile->inNormalWrite = 0;
2638#endif
aswiftaebf4132008-11-21 00:10:35 +00002639
drh308c2a52010-05-14 11:30:18 +00002640 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002641 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002642 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002643 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002644 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002645 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2646 } else {
2647 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002648 }
2649 }
drh308c2a52010-05-14 11:30:18 +00002650 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002651 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002652 }
drh308c2a52010-05-14 11:30:18 +00002653 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002654 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2655 if( !rc ){
2656 context->reserved = 0;
2657 }
aswiftaebf4132008-11-21 00:10:35 +00002658 }
drh8af6c222010-05-14 12:43:01 +00002659 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2660 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002661 }
aswiftaebf4132008-11-21 00:10:35 +00002662 }
drh308c2a52010-05-14 11:30:18 +00002663 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002664
drh7ed97b92010-01-20 13:07:21 +00002665 /* Decrement the shared lock counter. Release the lock using an
2666 ** OS call only when all threads in this same process have released
2667 ** the lock.
2668 */
drh8af6c222010-05-14 12:43:01 +00002669 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2670 pInode->nShared--;
2671 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002672 SimulateIOErrorBenign(1);
2673 SimulateIOError( h=(-1) )
2674 SimulateIOErrorBenign(0);
2675 if( !skipShared ){
2676 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2677 }
2678 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002679 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002680 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002681 }
2682 }
2683 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002684 pInode->nLock--;
2685 assert( pInode->nLock>=0 );
2686 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002687 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002688 }
2689 }
drhbfe66312006-10-03 17:40:40 +00002690 }
drh7ed97b92010-01-20 13:07:21 +00002691
drh6c7d5c52008-11-21 20:32:33 +00002692 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002693 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002694 return rc;
2695}
2696
2697/*
drh339eb0b2008-03-07 15:34:11 +00002698** Close a file & cleanup AFP specific locking context
2699*/
danielk1977e339d652008-06-28 11:23:00 +00002700static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002701 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002702 if( id ){
2703 unixFile *pFile = (unixFile*)id;
2704 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002705 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002706 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002707 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002708 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002709 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002710 ** the last lock is cleared.
2711 */
dan08da86a2009-08-21 17:18:03 +00002712 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002713 }
danb0ac3e32010-06-16 10:55:42 +00002714 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002715 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002716 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002717 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002718 }
drh7ed97b92010-01-20 13:07:21 +00002719 return rc;
drhbfe66312006-10-03 17:40:40 +00002720}
2721
drhd2cb50b2009-01-09 21:41:17 +00002722#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002723/*
2724** The code above is the AFP lock implementation. The code is specific
2725** to MacOSX and does not work on other unix platforms. No alternative
2726** is available. If you don't compile for a mac, then the "unix-afp"
2727** VFS is not available.
2728**
2729********************* End of the AFP lock implementation **********************
2730******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002731
drh7ed97b92010-01-20 13:07:21 +00002732/******************************************************************************
2733*************************** Begin NFS Locking ********************************/
2734
2735#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2736/*
drh308c2a52010-05-14 11:30:18 +00002737 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002738 ** must be either NO_LOCK or SHARED_LOCK.
2739 **
2740 ** If the locking level of the file descriptor is already at or below
2741 ** the requested locking level, this routine is a no-op.
2742 */
drh308c2a52010-05-14 11:30:18 +00002743static int nfsUnlock(sqlite3_file *id, int eFileLock){
2744 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002745}
2746
2747#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2748/*
2749** The code above is the NFS lock implementation. The code is specific
2750** to MacOSX and does not work on other unix platforms. No alternative
2751** is available.
2752**
2753********************* End of the NFS lock implementation **********************
2754******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002755
2756/******************************************************************************
2757**************** Non-locking sqlite3_file methods *****************************
2758**
2759** The next division contains implementations for all methods of the
2760** sqlite3_file object other than the locking methods. The locking
2761** methods were defined in divisions above (one locking method per
2762** division). Those methods that are common to all locking modes
2763** are gather together into this division.
2764*/
drhbfe66312006-10-03 17:40:40 +00002765
2766/*
drh734c9862008-11-28 15:37:20 +00002767** Seek to the offset passed as the second argument, then read cnt
2768** bytes into pBuf. Return the number of bytes actually read.
2769**
2770** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2771** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2772** one system to another. Since SQLite does not define USE_PREAD
2773** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2774** See tickets #2741 and #2681.
2775**
2776** To avoid stomping the errno value on a failed read the lastErrno value
2777** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002778*/
drh734c9862008-11-28 15:37:20 +00002779static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2780 int got;
drh7ed97b92010-01-20 13:07:21 +00002781#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002782 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002783#endif
drh734c9862008-11-28 15:37:20 +00002784 TIMER_START;
2785#if defined(USE_PREAD)
drhff812312011-02-23 13:33:46 +00002786 do{ got = pread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002787 SimulateIOError( got = -1 );
2788#elif defined(USE_PREAD64)
drhff812312011-02-23 13:33:46 +00002789 do{ got = pread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002790 SimulateIOError( got = -1 );
2791#else
2792 newOffset = lseek(id->h, offset, SEEK_SET);
2793 SimulateIOError( newOffset-- );
2794 if( newOffset!=offset ){
2795 if( newOffset == -1 ){
2796 ((unixFile*)id)->lastErrno = errno;
2797 }else{
2798 ((unixFile*)id)->lastErrno = 0;
2799 }
2800 return -1;
2801 }
drhff812312011-02-23 13:33:46 +00002802 do{ got = read(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002803#endif
2804 TIMER_END;
2805 if( got<0 ){
2806 ((unixFile*)id)->lastErrno = errno;
2807 }
drh308c2a52010-05-14 11:30:18 +00002808 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002809 return got;
drhbfe66312006-10-03 17:40:40 +00002810}
2811
2812/*
drh734c9862008-11-28 15:37:20 +00002813** Read data from a file into a buffer. Return SQLITE_OK if all
2814** bytes were read successfully and SQLITE_IOERR if anything goes
2815** wrong.
drh339eb0b2008-03-07 15:34:11 +00002816*/
drh734c9862008-11-28 15:37:20 +00002817static int unixRead(
2818 sqlite3_file *id,
2819 void *pBuf,
2820 int amt,
2821 sqlite3_int64 offset
2822){
dan08da86a2009-08-21 17:18:03 +00002823 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002824 int got;
2825 assert( id );
drh08c6d442009-02-09 17:34:07 +00002826
dan08da86a2009-08-21 17:18:03 +00002827 /* If this is a database file (not a journal, master-journal or temp
2828 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002829#if 0
dane946c392009-08-22 11:39:46 +00002830 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002831 || offset>=PENDING_BYTE+512
2832 || offset+amt<=PENDING_BYTE
2833 );
dan7c246102010-04-12 19:00:29 +00002834#endif
drh08c6d442009-02-09 17:34:07 +00002835
dan08da86a2009-08-21 17:18:03 +00002836 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002837 if( got==amt ){
2838 return SQLITE_OK;
2839 }else if( got<0 ){
2840 /* lastErrno set by seekAndRead */
2841 return SQLITE_IOERR_READ;
2842 }else{
dan08da86a2009-08-21 17:18:03 +00002843 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002844 /* Unread parts of the buffer must be zero-filled */
2845 memset(&((char*)pBuf)[got], 0, amt-got);
2846 return SQLITE_IOERR_SHORT_READ;
2847 }
2848}
2849
2850/*
2851** Seek to the offset in id->offset then read cnt bytes into pBuf.
2852** Return the number of bytes actually read. Update the offset.
2853**
2854** To avoid stomping the errno value on a failed write the lastErrno value
2855** is set before returning.
2856*/
2857static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2858 int got;
drh7ed97b92010-01-20 13:07:21 +00002859#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002860 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002861#endif
drh734c9862008-11-28 15:37:20 +00002862 TIMER_START;
2863#if defined(USE_PREAD)
drhff812312011-02-23 13:33:46 +00002864 do{ got = pwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002865#elif defined(USE_PREAD64)
drhff812312011-02-23 13:33:46 +00002866 do{ got = pwrite64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002867#else
2868 newOffset = lseek(id->h, offset, SEEK_SET);
2869 if( newOffset!=offset ){
2870 if( newOffset == -1 ){
2871 ((unixFile*)id)->lastErrno = errno;
2872 }else{
2873 ((unixFile*)id)->lastErrno = 0;
2874 }
2875 return -1;
2876 }
drhff812312011-02-23 13:33:46 +00002877 do{ got = write(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002878#endif
2879 TIMER_END;
2880 if( got<0 ){
2881 ((unixFile*)id)->lastErrno = errno;
2882 }
2883
drh308c2a52010-05-14 11:30:18 +00002884 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002885 return got;
2886}
2887
2888
2889/*
2890** Write data from a buffer into a file. Return SQLITE_OK on success
2891** or some other error code on failure.
2892*/
2893static int unixWrite(
2894 sqlite3_file *id,
2895 const void *pBuf,
2896 int amt,
2897 sqlite3_int64 offset
2898){
dan08da86a2009-08-21 17:18:03 +00002899 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002900 int wrote = 0;
2901 assert( id );
2902 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002903
dan08da86a2009-08-21 17:18:03 +00002904 /* If this is a database file (not a journal, master-journal or temp
2905 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002906#if 0
dane946c392009-08-22 11:39:46 +00002907 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002908 || offset>=PENDING_BYTE+512
2909 || offset+amt<=PENDING_BYTE
2910 );
dan7c246102010-04-12 19:00:29 +00002911#endif
drh08c6d442009-02-09 17:34:07 +00002912
drh8f941bc2009-01-14 23:03:40 +00002913#ifndef NDEBUG
2914 /* If we are doing a normal write to a database file (as opposed to
2915 ** doing a hot-journal rollback or a write to some file other than a
2916 ** normal database file) then record the fact that the database
2917 ** has changed. If the transaction counter is modified, record that
2918 ** fact too.
2919 */
dan08da86a2009-08-21 17:18:03 +00002920 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002921 pFile->dbUpdate = 1; /* The database has been modified */
2922 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002923 int rc;
drh8f941bc2009-01-14 23:03:40 +00002924 char oldCntr[4];
2925 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002926 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002927 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002928 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002929 pFile->transCntrChng = 1; /* The transaction counter has changed */
2930 }
2931 }
2932 }
2933#endif
2934
dan08da86a2009-08-21 17:18:03 +00002935 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002936 amt -= wrote;
2937 offset += wrote;
2938 pBuf = &((char*)pBuf)[wrote];
2939 }
2940 SimulateIOError(( wrote=(-1), amt=1 ));
2941 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00002942
drh734c9862008-11-28 15:37:20 +00002943 if( amt>0 ){
2944 if( wrote<0 ){
2945 /* lastErrno set by seekAndWrite */
2946 return SQLITE_IOERR_WRITE;
2947 }else{
dan08da86a2009-08-21 17:18:03 +00002948 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002949 return SQLITE_FULL;
2950 }
2951 }
dan6e09d692010-07-27 18:34:15 +00002952
drh734c9862008-11-28 15:37:20 +00002953 return SQLITE_OK;
2954}
2955
2956#ifdef SQLITE_TEST
2957/*
2958** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002959** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002960*/
2961int sqlite3_sync_count = 0;
2962int sqlite3_fullsync_count = 0;
2963#endif
2964
2965/*
drh89240432009-03-25 01:06:01 +00002966** We do not trust systems to provide a working fdatasync(). Some do.
2967** Others do no. To be safe, we will stick with the (slower) fsync().
2968** If you know that your system does support fdatasync() correctly,
2969** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002970*/
drh89240432009-03-25 01:06:01 +00002971#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002972# define fdatasync fsync
2973#endif
2974
2975/*
2976** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2977** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2978** only available on Mac OS X. But that could change.
2979*/
2980#ifdef F_FULLFSYNC
2981# define HAVE_FULLFSYNC 1
2982#else
2983# define HAVE_FULLFSYNC 0
2984#endif
2985
2986
2987/*
2988** The fsync() system call does not work as advertised on many
2989** unix systems. The following procedure is an attempt to make
2990** it work better.
2991**
2992** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2993** for testing when we want to run through the test suite quickly.
2994** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2995** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2996** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002997**
2998** SQLite sets the dataOnly flag if the size of the file is unchanged.
2999** The idea behind dataOnly is that it should only write the file content
3000** to disk, not the inode. We only set dataOnly if the file size is
3001** unchanged since the file size is part of the inode. However,
3002** Ted Ts'o tells us that fdatasync() will also write the inode if the
3003** file size has changed. The only real difference between fdatasync()
3004** and fsync(), Ted tells us, is that fdatasync() will not flush the
3005** inode if the mtime or owner or other inode attributes have changed.
3006** We only care about the file size, not the other file attributes, so
3007** as far as SQLite is concerned, an fdatasync() is always adequate.
3008** So, we always use fdatasync() if it is available, regardless of
3009** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003010*/
3011static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003012 int rc;
drh734c9862008-11-28 15:37:20 +00003013
3014 /* The following "ifdef/elif/else/" block has the same structure as
3015 ** the one below. It is replicated here solely to avoid cluttering
3016 ** up the real code with the UNUSED_PARAMETER() macros.
3017 */
3018#ifdef SQLITE_NO_SYNC
3019 UNUSED_PARAMETER(fd);
3020 UNUSED_PARAMETER(fullSync);
3021 UNUSED_PARAMETER(dataOnly);
3022#elif HAVE_FULLFSYNC
3023 UNUSED_PARAMETER(dataOnly);
3024#else
3025 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003026 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003027#endif
3028
3029 /* Record the number of times that we do a normal fsync() and
3030 ** FULLSYNC. This is used during testing to verify that this procedure
3031 ** gets called with the correct arguments.
3032 */
3033#ifdef SQLITE_TEST
3034 if( fullSync ) sqlite3_fullsync_count++;
3035 sqlite3_sync_count++;
3036#endif
3037
3038 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3039 ** no-op
3040 */
3041#ifdef SQLITE_NO_SYNC
3042 rc = SQLITE_OK;
3043#elif HAVE_FULLFSYNC
3044 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003045 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003046 }else{
3047 rc = 1;
3048 }
3049 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003050 ** It shouldn't be possible for fullfsync to fail on the local
3051 ** file system (on OSX), so failure indicates that FULLFSYNC
3052 ** isn't supported for this file system. So, attempt an fsync
3053 ** and (for now) ignore the overhead of a superfluous fcntl call.
3054 ** It'd be better to detect fullfsync support once and avoid
3055 ** the fcntl call every time sync is called.
3056 */
drh734c9862008-11-28 15:37:20 +00003057 if( rc ) rc = fsync(fd);
3058
drh7ed97b92010-01-20 13:07:21 +00003059#elif defined(__APPLE__)
3060 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3061 ** so currently we default to the macro that redefines fdatasync to fsync
3062 */
3063 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003064#else
drh0b647ff2009-03-21 14:41:04 +00003065 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003066#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003067 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003068 rc = fsync(fd);
3069 }
drh0b647ff2009-03-21 14:41:04 +00003070#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003071#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3072
3073 if( OS_VXWORKS && rc!= -1 ){
3074 rc = 0;
3075 }
chw97185482008-11-17 08:05:31 +00003076 return rc;
drhbfe66312006-10-03 17:40:40 +00003077}
3078
drh734c9862008-11-28 15:37:20 +00003079/*
3080** Make sure all writes to a particular file are committed to disk.
3081**
3082** If dataOnly==0 then both the file itself and its metadata (file
3083** size, access time, etc) are synced. If dataOnly!=0 then only the
3084** file data is synced.
3085**
3086** Under Unix, also make sure that the directory entry for the file
3087** has been created by fsync-ing the directory that contains the file.
3088** If we do not do this and we encounter a power failure, the directory
3089** entry for the journal might not exist after we reboot. The next
3090** SQLite to access the file will not know that the journal exists (because
3091** the directory entry for the journal was never created) and the transaction
3092** will not roll back - possibly leading to database corruption.
3093*/
3094static int unixSync(sqlite3_file *id, int flags){
3095 int rc;
3096 unixFile *pFile = (unixFile*)id;
3097
3098 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3099 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3100
3101 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3102 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3103 || (flags&0x0F)==SQLITE_SYNC_FULL
3104 );
3105
3106 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3107 ** line is to test that doing so does not cause any problems.
3108 */
3109 SimulateDiskfullError( return SQLITE_FULL );
3110
3111 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003112 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003113 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3114 SimulateIOError( rc=1 );
3115 if( rc ){
3116 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003117 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003118 }
3119 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003120 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3121 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003122#ifndef SQLITE_DISABLE_DIRSYNC
3123 /* The directory sync is only attempted if full_fsync is
3124 ** turned off or unavailable. If a full_fsync occurred above,
3125 ** then the directory sync is superfluous.
3126 */
3127 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3128 /*
3129 ** We have received multiple reports of fsync() returning
3130 ** errors when applied to directories on certain file systems.
3131 ** A failed directory sync is not a big deal. So it seems
3132 ** better to ignore the error. Ticket #1657
3133 */
3134 /* pFile->lastErrno = errno; */
3135 /* return SQLITE_IOERR; */
3136 }
3137#endif
drh0e9365c2011-03-02 02:08:13 +00003138 /* Only need to sync once, so close the directory when we are done */
3139 robust_close(pFile, pFile->dirfd, __LINE__);
3140 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003141 }
3142 return rc;
3143}
3144
3145/*
3146** Truncate an open file to a specified size
3147*/
3148static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003149 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003150 int rc;
dan6e09d692010-07-27 18:34:15 +00003151 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003152 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003153
3154 /* If the user has configured a chunk-size for this file, truncate the
3155 ** file so that it consists of an integer number of chunks (i.e. the
3156 ** actual file size after the operation may be larger than the requested
3157 ** size).
3158 */
3159 if( pFile->szChunk ){
3160 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3161 }
3162
drhff812312011-02-23 13:33:46 +00003163 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003164 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003165 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003166 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003167 }else{
drh3313b142009-11-06 04:13:18 +00003168#ifndef NDEBUG
3169 /* If we are doing a normal write to a database file (as opposed to
3170 ** doing a hot-journal rollback or a write to some file other than a
3171 ** normal database file) and we truncate the file to zero length,
3172 ** that effectively updates the change counter. This might happen
3173 ** when restoring a database using the backup API from a zero-length
3174 ** source.
3175 */
dan6e09d692010-07-27 18:34:15 +00003176 if( pFile->inNormalWrite && nByte==0 ){
3177 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003178 }
3179#endif
3180
drh734c9862008-11-28 15:37:20 +00003181 return SQLITE_OK;
3182 }
3183}
3184
3185/*
3186** Determine the current size of a file in bytes
3187*/
3188static int unixFileSize(sqlite3_file *id, i64 *pSize){
3189 int rc;
3190 struct stat buf;
3191 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003192 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003193 SimulateIOError( rc=1 );
3194 if( rc!=0 ){
3195 ((unixFile*)id)->lastErrno = errno;
3196 return SQLITE_IOERR_FSTAT;
3197 }
3198 *pSize = buf.st_size;
3199
drh8af6c222010-05-14 12:43:01 +00003200 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003201 ** writes a single byte into that file in order to work around a bug
3202 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3203 ** layers, we need to report this file size as zero even though it is
3204 ** really 1. Ticket #3260.
3205 */
3206 if( *pSize==1 ) *pSize = 0;
3207
3208
3209 return SQLITE_OK;
3210}
3211
drhd2cb50b2009-01-09 21:41:17 +00003212#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003213/*
3214** Handler for proxy-locking file-control verbs. Defined below in the
3215** proxying locking division.
3216*/
3217static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003218#endif
drh715ff302008-12-03 22:32:44 +00003219
dan502019c2010-07-28 14:26:17 +00003220/*
3221** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3222** file-control operation.
3223**
3224** If the user has configured a chunk-size for this file, it could be
3225** that the file needs to be extended at this point. Otherwise, the
3226** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3227*/
3228static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3229 if( pFile->szChunk ){
3230 i64 nSize; /* Required file size */
3231 struct stat buf; /* Used to hold return values of fstat() */
3232
drh99ab3b12011-03-02 15:09:07 +00003233 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003234
3235 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3236 if( nSize>(i64)buf.st_size ){
3237#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drhff812312011-02-23 13:33:46 +00003238 int rc;
3239 do{
3240 rc = posix_fallocate(pFile-.h, buf.st_size, nSize-buf.st_size;
3241 }while( rc<0 && errno=EINTR );
3242 if( rc ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003243#else
3244 /* If the OS does not have posix_fallocate(), fake it. First use
3245 ** ftruncate() to set the file size, then write a single byte to
3246 ** the last byte in each block within the extended region. This
3247 ** is the same technique used by glibc to implement posix_fallocate()
3248 ** on systems that do not have a real fallocate() system call.
3249 */
3250 int nBlk = buf.st_blksize; /* File-system block size */
3251 i64 iWrite; /* Next offset to write to */
3252 int nWrite; /* Return value from seekAndWrite() */
3253
drhff812312011-02-23 13:33:46 +00003254 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003255 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003256 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003257 }
3258 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3259 do {
3260 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3261 iWrite += nBlk;
3262 } while( nWrite==1 && iWrite<nSize );
3263 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3264#endif
3265 }
3266 }
3267
3268 return SQLITE_OK;
3269}
danielk1977ad94b582007-08-20 06:44:22 +00003270
danielk1977e3026632004-06-22 11:29:02 +00003271/*
drh9e33c2c2007-08-31 18:34:59 +00003272** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003273*/
drhcc6bb3e2007-08-31 16:11:35 +00003274static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003275 switch( op ){
3276 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003277 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003278 return SQLITE_OK;
3279 }
drh7708e972008-11-29 00:56:52 +00003280 case SQLITE_LAST_ERRNO: {
3281 *(int*)pArg = ((unixFile*)id)->lastErrno;
3282 return SQLITE_OK;
3283 }
dan6e09d692010-07-27 18:34:15 +00003284 case SQLITE_FCNTL_CHUNK_SIZE: {
3285 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003286 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003287 }
drh9ff27ec2010-05-19 19:26:05 +00003288 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003289 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003290 }
drh8f941bc2009-01-14 23:03:40 +00003291#ifndef NDEBUG
3292 /* The pager calls this method to signal that it has done
3293 ** a rollback and that the database is therefore unchanged and
3294 ** it hence it is OK for the transaction change counter to be
3295 ** unchanged.
3296 */
3297 case SQLITE_FCNTL_DB_UNCHANGED: {
3298 ((unixFile*)id)->dbUpdate = 0;
3299 return SQLITE_OK;
3300 }
3301#endif
drhd2cb50b2009-01-09 21:41:17 +00003302#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003303 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003304 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003305 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003306 }
drhd2cb50b2009-01-09 21:41:17 +00003307#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003308 case SQLITE_FCNTL_SYNC_OMITTED: {
3309 return SQLITE_OK; /* A no-op */
3310 }
drh9e33c2c2007-08-31 18:34:59 +00003311 }
drh0b52b7d2011-01-26 19:46:22 +00003312 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003313}
3314
3315/*
danielk1977a3d4c882007-03-23 10:08:38 +00003316** Return the sector size in bytes of the underlying block device for
3317** the specified file. This is almost always 512 bytes, but may be
3318** larger for some devices.
3319**
3320** SQLite code assumes this function cannot fail. It also assumes that
3321** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003322** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003323** same for both.
3324*/
danielk1977397d65f2008-11-19 11:35:39 +00003325static int unixSectorSize(sqlite3_file *NotUsed){
3326 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003327 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003328}
3329
danielk197790949c22007-08-17 16:50:38 +00003330/*
danielk1977397d65f2008-11-19 11:35:39 +00003331** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003332*/
danielk1977397d65f2008-11-19 11:35:39 +00003333static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3334 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003335 return 0;
3336}
3337
drhd9e5c4f2010-05-12 18:01:39 +00003338#ifndef SQLITE_OMIT_WAL
3339
3340
3341/*
drhd91c68f2010-05-14 14:52:25 +00003342** Object used to represent an shared memory buffer.
3343**
3344** When multiple threads all reference the same wal-index, each thread
3345** has its own unixShm object, but they all point to a single instance
3346** of this unixShmNode object. In other words, each wal-index is opened
3347** only once per process.
3348**
3349** Each unixShmNode object is connected to a single unixInodeInfo object.
3350** We could coalesce this object into unixInodeInfo, but that would mean
3351** every open file that does not use shared memory (in other words, most
3352** open files) would have to carry around this extra information. So
3353** the unixInodeInfo object contains a pointer to this unixShmNode object
3354** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003355**
3356** unixMutexHeld() must be true when creating or destroying
3357** this object or while reading or writing the following fields:
3358**
3359** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003360**
3361** The following fields are read-only after the object is created:
3362**
3363** fid
3364** zFilename
3365**
drhd91c68f2010-05-14 14:52:25 +00003366** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003367** unixMutexHeld() is true when reading or writing any other field
3368** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003369*/
drhd91c68f2010-05-14 14:52:25 +00003370struct unixShmNode {
3371 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003372 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003373 char *zFilename; /* Name of the mmapped file */
3374 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003375 int szRegion; /* Size of shared-memory regions */
3376 int nRegion; /* Size of array apRegion */
3377 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003378 int nRef; /* Number of unixShm objects pointing to this */
3379 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003380#ifdef SQLITE_DEBUG
3381 u8 exclMask; /* Mask of exclusive locks held */
3382 u8 sharedMask; /* Mask of shared locks held */
3383 u8 nextShmId; /* Next available unixShm.id value */
3384#endif
3385};
3386
3387/*
drhd9e5c4f2010-05-12 18:01:39 +00003388** Structure used internally by this VFS to record the state of an
3389** open shared memory connection.
3390**
drhd91c68f2010-05-14 14:52:25 +00003391** The following fields are initialized when this object is created and
3392** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003393**
drhd91c68f2010-05-14 14:52:25 +00003394** unixShm.pFile
3395** unixShm.id
3396**
3397** All other fields are read/write. The unixShm.pFile->mutex must be held
3398** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003399*/
3400struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003401 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3402 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003403 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003404 u16 sharedMask; /* Mask of shared locks held */
3405 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003406#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003407 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003408#endif
3409};
3410
3411/*
drhd9e5c4f2010-05-12 18:01:39 +00003412** Constants used for locking
3413*/
drhbd9676c2010-06-23 17:58:38 +00003414#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003415#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003416
drhd9e5c4f2010-05-12 18:01:39 +00003417/*
drh73b64e42010-05-30 19:55:15 +00003418** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003419**
3420** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3421** otherwise.
3422*/
3423static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003424 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3425 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003426 int ofst, /* First byte of the locking range */
3427 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003428){
3429 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003430 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003431
drhd91c68f2010-05-14 14:52:25 +00003432 /* Access to the unixShmNode object is serialized by the caller */
3433 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003434
drh73b64e42010-05-30 19:55:15 +00003435 /* Shared locks never span more than one byte */
3436 assert( n==1 || lockType!=F_RDLCK );
3437
3438 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003439 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003440
drhd9e5c4f2010-05-12 18:01:39 +00003441 /* Initialize the locking parameters */
3442 memset(&f, 0, sizeof(f));
3443 f.l_type = lockType;
3444 f.l_whence = SEEK_SET;
drhc99597c2010-05-31 01:41:15 +00003445 f.l_start = ofst;
drh73b64e42010-05-30 19:55:15 +00003446 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003447
drh99ab3b12011-03-02 15:09:07 +00003448 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drhd9e5c4f2010-05-12 18:01:39 +00003449 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3450
3451 /* Update the global lock state and do debug tracing */
3452#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003453 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003454 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003455 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003456 if( rc==SQLITE_OK ){
3457 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003458 OSTRACE(("unlock %d ok", ofst));
3459 pShmNode->exclMask &= ~mask;
3460 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003461 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003462 OSTRACE(("read-lock %d ok", ofst));
3463 pShmNode->exclMask &= ~mask;
3464 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003465 }else{
3466 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003467 OSTRACE(("write-lock %d ok", ofst));
3468 pShmNode->exclMask |= mask;
3469 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003470 }
3471 }else{
3472 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003473 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003474 }else if( lockType==F_RDLCK ){
3475 OSTRACE(("read-lock failed"));
3476 }else{
3477 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003478 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003479 }
3480 }
drh20e1f082010-05-31 16:10:12 +00003481 OSTRACE((" - afterwards %03x,%03x\n",
3482 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003483 }
drhd9e5c4f2010-05-12 18:01:39 +00003484#endif
3485
3486 return rc;
3487}
3488
drhd9e5c4f2010-05-12 18:01:39 +00003489
3490/*
drhd91c68f2010-05-14 14:52:25 +00003491** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003492**
3493** This is not a VFS shared-memory method; it is a utility function called
3494** by VFS shared-memory methods.
3495*/
drhd91c68f2010-05-14 14:52:25 +00003496static void unixShmPurge(unixFile *pFd){
3497 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003498 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003499 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003500 int i;
drhd91c68f2010-05-14 14:52:25 +00003501 assert( p->pInode==pFd->pInode );
3502 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003503 for(i=0; i<p->nRegion; i++){
3504 munmap(p->apRegion[i], p->szRegion);
dan13a3cb82010-06-11 19:04:21 +00003505 }
dan18801912010-06-14 14:07:50 +00003506 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003507 if( p->h>=0 ){
3508 robust_close(pFd, p->h, __LINE__);
3509 p->h = -1;
3510 }
drhd91c68f2010-05-14 14:52:25 +00003511 p->pInode->pShmNode = 0;
3512 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003513 }
3514}
3515
3516/*
danda9fe0c2010-07-13 18:44:03 +00003517** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003518** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003519**
drh7234c6d2010-06-19 15:10:09 +00003520** The file used to implement shared-memory is in the same directory
3521** as the open database file and has the same name as the open database
3522** file with the "-shm" suffix added. For example, if the database file
3523** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003524** for shared memory will be called "/home/user1/config.db-shm".
3525**
3526** Another approach to is to use files in /dev/shm or /dev/tmp or an
3527** some other tmpfs mount. But if a file in a different directory
3528** from the database file is used, then differing access permissions
3529** or a chroot() might cause two different processes on the same
3530** database to end up using different files for shared memory -
3531** meaning that their memory would not really be shared - resulting
3532** in database corruption. Nevertheless, this tmpfs file usage
3533** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3534** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3535** option results in an incompatible build of SQLite; builds of SQLite
3536** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3537** same database file at the same time, database corruption will likely
3538** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3539** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003540**
3541** When opening a new shared-memory file, if no other instances of that
3542** file are currently open, in this process or in other processes, then
3543** the file must be truncated to zero length or have its header cleared.
3544*/
danda9fe0c2010-07-13 18:44:03 +00003545static int unixOpenSharedMemory(unixFile *pDbFd){
3546 struct unixShm *p = 0; /* The connection to be opened */
3547 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3548 int rc; /* Result code */
3549 unixInodeInfo *pInode; /* The inode of fd */
3550 char *zShmFilename; /* Name of the file used for SHM */
3551 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003552
danda9fe0c2010-07-13 18:44:03 +00003553 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003554 p = sqlite3_malloc( sizeof(*p) );
3555 if( p==0 ) return SQLITE_NOMEM;
3556 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003557 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003558
danda9fe0c2010-07-13 18:44:03 +00003559 /* Check to see if a unixShmNode object already exists. Reuse an existing
3560 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003561 */
3562 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003563 pInode = pDbFd->pInode;
3564 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003565 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003566 struct stat sStat; /* fstat() info for database file */
3567
3568 /* Call fstat() to figure out the permissions on the database file. If
3569 ** a new *-shm file is created, an attempt will be made to create it
3570 ** with the same permissions. The actual permissions the file is created
3571 ** with are subject to the current umask setting.
3572 */
drh99ab3b12011-03-02 15:09:07 +00003573 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00003574 rc = SQLITE_IOERR_FSTAT;
3575 goto shm_open_err;
3576 }
3577
drha4ced192010-07-15 18:32:40 +00003578#ifdef SQLITE_SHM_DIRECTORY
3579 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3580#else
drh7234c6d2010-06-19 15:10:09 +00003581 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003582#endif
drh7234c6d2010-06-19 15:10:09 +00003583 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003584 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003585 rc = SQLITE_NOMEM;
3586 goto shm_open_err;
3587 }
drhd91c68f2010-05-14 14:52:25 +00003588 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003589 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003590#ifdef SQLITE_SHM_DIRECTORY
3591 sqlite3_snprintf(nShmFilename, zShmFilename,
3592 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3593 (u32)sStat.st_ino, (u32)sStat.st_dev);
3594#else
drh7234c6d2010-06-19 15:10:09 +00003595 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003596#endif
drhd91c68f2010-05-14 14:52:25 +00003597 pShmNode->h = -1;
3598 pDbFd->pInode->pShmNode = pShmNode;
3599 pShmNode->pInode = pDbFd->pInode;
3600 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3601 if( pShmNode->mutex==0 ){
3602 rc = SQLITE_NOMEM;
3603 goto shm_open_err;
3604 }
drhd9e5c4f2010-05-12 18:01:39 +00003605
drh99ab3b12011-03-02 15:09:07 +00003606 pShmNode->h = osOpen(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
drhd91c68f2010-05-14 14:52:25 +00003607 if( pShmNode->h<0 ){
dane18d4952011-02-21 11:46:24 +00003608 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003609 goto shm_open_err;
3610 }
3611
drhd9e5c4f2010-05-12 18:01:39 +00003612 /* Check to see if another process is holding the dead-man switch.
3613 ** If not, truncate the file to zero length.
3614 */
drhd91c68f2010-05-14 14:52:25 +00003615 rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00003616 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drhff812312011-02-23 13:33:46 +00003617 if( robust_ftruncate(pShmNode->h, 0) ){
dane18d4952011-02-21 11:46:24 +00003618 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drhd9e5c4f2010-05-12 18:01:39 +00003619 }
3620 }
3621 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00003622 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
drhd9e5c4f2010-05-12 18:01:39 +00003623 }
3624 if( rc ) goto shm_open_err;
3625 }
3626
drhd91c68f2010-05-14 14:52:25 +00003627 /* Make the new connection a child of the unixShmNode */
3628 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003629#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003630 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003631#endif
drhd91c68f2010-05-14 14:52:25 +00003632 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003633 pDbFd->pShm = p;
3634 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003635
3636 /* The reference count on pShmNode has already been incremented under
3637 ** the cover of the unixEnterMutex() mutex and the pointer from the
3638 ** new (struct unixShm) object to the pShmNode has been set. All that is
3639 ** left to do is to link the new object into the linked list starting
3640 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3641 ** mutex.
3642 */
3643 sqlite3_mutex_enter(pShmNode->mutex);
3644 p->pNext = pShmNode->pFirst;
3645 pShmNode->pFirst = p;
3646 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003647 return SQLITE_OK;
3648
3649 /* Jump here on any error */
3650shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003651 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003652 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003653 unixLeaveMutex();
3654 return rc;
3655}
3656
3657/*
danda9fe0c2010-07-13 18:44:03 +00003658** This function is called to obtain a pointer to region iRegion of the
3659** shared-memory associated with the database file fd. Shared-memory regions
3660** are numbered starting from zero. Each shared-memory region is szRegion
3661** bytes in size.
3662**
3663** If an error occurs, an error code is returned and *pp is set to NULL.
3664**
3665** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3666** region has not been allocated (by any client, including one running in a
3667** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3668** bExtend is non-zero and the requested shared-memory region has not yet
3669** been allocated, it is allocated by this function.
3670**
3671** If the shared-memory region has already been allocated or is allocated by
3672** this call as described above, then it is mapped into this processes
3673** address space (if it is not already), *pp is set to point to the mapped
3674** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003675*/
danda9fe0c2010-07-13 18:44:03 +00003676static int unixShmMap(
3677 sqlite3_file *fd, /* Handle open on database file */
3678 int iRegion, /* Region to retrieve */
3679 int szRegion, /* Size of regions */
3680 int bExtend, /* True to extend file if necessary */
3681 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003682){
danda9fe0c2010-07-13 18:44:03 +00003683 unixFile *pDbFd = (unixFile*)fd;
3684 unixShm *p;
3685 unixShmNode *pShmNode;
3686 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003687
danda9fe0c2010-07-13 18:44:03 +00003688 /* If the shared-memory file has not yet been opened, open it now. */
3689 if( pDbFd->pShm==0 ){
3690 rc = unixOpenSharedMemory(pDbFd);
3691 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003692 }
drhd9e5c4f2010-05-12 18:01:39 +00003693
danda9fe0c2010-07-13 18:44:03 +00003694 p = pDbFd->pShm;
3695 pShmNode = p->pShmNode;
3696 sqlite3_mutex_enter(pShmNode->mutex);
3697 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3698
3699 if( pShmNode->nRegion<=iRegion ){
3700 char **apNew; /* New apRegion[] array */
3701 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3702 struct stat sStat; /* Used by fstat() */
3703
3704 pShmNode->szRegion = szRegion;
3705
3706 /* The requested region is not mapped into this processes address space.
3707 ** Check to see if it has been allocated (i.e. if the wal-index file is
3708 ** large enough to contain the requested region).
3709 */
drh99ab3b12011-03-02 15:09:07 +00003710 if( osFstat(pShmNode->h, &sStat) ){
danda9fe0c2010-07-13 18:44:03 +00003711 rc = SQLITE_IOERR_SHMSIZE;
3712 goto shmpage_out;
3713 }
3714
3715 if( sStat.st_size<nByte ){
3716 /* The requested memory region does not exist. If bExtend is set to
3717 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3718 **
3719 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3720 ** the requested memory region.
3721 */
3722 if( !bExtend ) goto shmpage_out;
drhff812312011-02-23 13:33:46 +00003723 if( robust_ftruncate(pShmNode->h, nByte) ){
dane18d4952011-02-21 11:46:24 +00003724 rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00003725 goto shmpage_out;
3726 }
3727 }
3728
3729 /* Map the requested memory region into this processes address space. */
3730 apNew = (char **)sqlite3_realloc(
3731 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3732 );
3733 if( !apNew ){
3734 rc = SQLITE_IOERR_NOMEM;
3735 goto shmpage_out;
3736 }
3737 pShmNode->apRegion = apNew;
3738 while(pShmNode->nRegion<=iRegion){
3739 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
drh37e8b5b2010-09-02 14:00:19 +00003740 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
danda9fe0c2010-07-13 18:44:03 +00003741 );
3742 if( pMem==MAP_FAILED ){
3743 rc = SQLITE_IOERR;
3744 goto shmpage_out;
3745 }
3746 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3747 pShmNode->nRegion++;
3748 }
3749 }
3750
3751shmpage_out:
3752 if( pShmNode->nRegion>iRegion ){
3753 *pp = pShmNode->apRegion[iRegion];
3754 }else{
3755 *pp = 0;
3756 }
3757 sqlite3_mutex_leave(pShmNode->mutex);
3758 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003759}
3760
3761/*
drhd9e5c4f2010-05-12 18:01:39 +00003762** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003763**
3764** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3765** different here than in posix. In xShmLock(), one can go from unlocked
3766** to shared and back or from unlocked to exclusive and back. But one may
3767** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003768*/
3769static int unixShmLock(
3770 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003771 int ofst, /* First lock to acquire or release */
3772 int n, /* Number of locks to acquire or release */
3773 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003774){
drh73b64e42010-05-30 19:55:15 +00003775 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3776 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3777 unixShm *pX; /* For looping over all siblings */
3778 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3779 int rc = SQLITE_OK; /* Result code */
3780 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003781
drhd91c68f2010-05-14 14:52:25 +00003782 assert( pShmNode==pDbFd->pInode->pShmNode );
3783 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003784 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003785 assert( n>=1 );
3786 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3787 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3788 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3789 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3790 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drhd91c68f2010-05-14 14:52:25 +00003791
drhc99597c2010-05-31 01:41:15 +00003792 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003793 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003794 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003795 if( flags & SQLITE_SHM_UNLOCK ){
3796 u16 allMask = 0; /* Mask of locks held by siblings */
3797
3798 /* See if any siblings hold this same lock */
3799 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3800 if( pX==p ) continue;
3801 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3802 allMask |= pX->sharedMask;
3803 }
3804
3805 /* Unlock the system-level locks */
3806 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003807 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00003808 }else{
drhd9e5c4f2010-05-12 18:01:39 +00003809 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003810 }
drh73b64e42010-05-30 19:55:15 +00003811
3812 /* Undo the local locks */
3813 if( rc==SQLITE_OK ){
3814 p->exclMask &= ~mask;
3815 p->sharedMask &= ~mask;
3816 }
3817 }else if( flags & SQLITE_SHM_SHARED ){
3818 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3819
3820 /* Find out which shared locks are already held by sibling connections.
3821 ** If any sibling already holds an exclusive lock, go ahead and return
3822 ** SQLITE_BUSY.
3823 */
3824 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003825 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003826 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00003827 break;
3828 }
3829 allShared |= pX->sharedMask;
3830 }
3831
3832 /* Get shared locks at the system level, if necessary */
3833 if( rc==SQLITE_OK ){
3834 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00003835 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003836 }else{
drh73b64e42010-05-30 19:55:15 +00003837 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003838 }
drhd9e5c4f2010-05-12 18:01:39 +00003839 }
drh73b64e42010-05-30 19:55:15 +00003840
3841 /* Get the local shared locks */
3842 if( rc==SQLITE_OK ){
3843 p->sharedMask |= mask;
3844 }
3845 }else{
3846 /* Make sure no sibling connections hold locks that will block this
3847 ** lock. If any do, return SQLITE_BUSY right away.
3848 */
3849 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00003850 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3851 rc = SQLITE_BUSY;
3852 break;
3853 }
3854 }
3855
3856 /* Get the exclusive locks at the system level. Then if successful
3857 ** also mark the local connection as being locked.
3858 */
3859 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00003860 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00003861 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00003862 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00003863 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003864 }
drhd9e5c4f2010-05-12 18:01:39 +00003865 }
3866 }
drhd91c68f2010-05-14 14:52:25 +00003867 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00003868 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3869 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00003870 return rc;
3871}
3872
drh286a2882010-05-20 23:51:06 +00003873/*
3874** Implement a memory barrier or memory fence on shared memory.
3875**
3876** All loads and stores begun before the barrier must complete before
3877** any load or store begun after the barrier.
3878*/
3879static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00003880 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00003881){
drhff828942010-06-26 21:34:06 +00003882 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00003883 unixEnterMutex();
3884 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00003885}
3886
dan18801912010-06-14 14:07:50 +00003887/*
danda9fe0c2010-07-13 18:44:03 +00003888** Close a connection to shared-memory. Delete the underlying
3889** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00003890**
3891** If there is no shared memory associated with the connection then this
3892** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00003893*/
danda9fe0c2010-07-13 18:44:03 +00003894static int unixShmUnmap(
3895 sqlite3_file *fd, /* The underlying database file */
3896 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00003897){
danda9fe0c2010-07-13 18:44:03 +00003898 unixShm *p; /* The connection to be closed */
3899 unixShmNode *pShmNode; /* The underlying shared-memory file */
3900 unixShm **pp; /* For looping over sibling connections */
3901 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00003902
danda9fe0c2010-07-13 18:44:03 +00003903 pDbFd = (unixFile*)fd;
3904 p = pDbFd->pShm;
3905 if( p==0 ) return SQLITE_OK;
3906 pShmNode = p->pShmNode;
3907
3908 assert( pShmNode==pDbFd->pInode->pShmNode );
3909 assert( pShmNode->pInode==pDbFd->pInode );
3910
3911 /* Remove connection p from the set of connections associated
3912 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00003913 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003914 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3915 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00003916
danda9fe0c2010-07-13 18:44:03 +00003917 /* Free the connection p */
3918 sqlite3_free(p);
3919 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00003920 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00003921
3922 /* If pShmNode->nRef has reached 0, then close the underlying
3923 ** shared-memory file, too */
3924 unixEnterMutex();
3925 assert( pShmNode->nRef>0 );
3926 pShmNode->nRef--;
3927 if( pShmNode->nRef==0 ){
3928 if( deleteFlag ) unlink(pShmNode->zFilename);
3929 unixShmPurge(pDbFd);
3930 }
3931 unixLeaveMutex();
3932
3933 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00003934}
drh286a2882010-05-20 23:51:06 +00003935
danda9fe0c2010-07-13 18:44:03 +00003936
drhd9e5c4f2010-05-12 18:01:39 +00003937#else
drh6b017cc2010-06-14 18:01:46 +00003938# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00003939# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00003940# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00003941# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00003942#endif /* #ifndef SQLITE_OMIT_WAL */
3943
drh734c9862008-11-28 15:37:20 +00003944/*
3945** Here ends the implementation of all sqlite3_file methods.
3946**
3947********************** End sqlite3_file Methods *******************************
3948******************************************************************************/
3949
3950/*
drh6b9d6dd2008-12-03 19:34:47 +00003951** This division contains definitions of sqlite3_io_methods objects that
3952** implement various file locking strategies. It also contains definitions
3953** of "finder" functions. A finder-function is used to locate the appropriate
3954** sqlite3_io_methods object for a particular database file. The pAppData
3955** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3956** the correct finder-function for that VFS.
3957**
3958** Most finder functions return a pointer to a fixed sqlite3_io_methods
3959** object. The only interesting finder-function is autolockIoFinder, which
3960** looks at the filesystem type and tries to guess the best locking
3961** strategy from that.
3962**
drh1875f7a2008-12-08 18:19:17 +00003963** For finder-funtion F, two objects are created:
3964**
3965** (1) The real finder-function named "FImpt()".
3966**
dane946c392009-08-22 11:39:46 +00003967** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003968**
3969**
3970** A pointer to the F pointer is used as the pAppData value for VFS
3971** objects. We have to do this instead of letting pAppData point
3972** directly at the finder-function since C90 rules prevent a void*
3973** from be cast into a function pointer.
3974**
drh6b9d6dd2008-12-03 19:34:47 +00003975**
drh7708e972008-11-29 00:56:52 +00003976** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003977**
drh7708e972008-11-29 00:56:52 +00003978** * A constant sqlite3_io_methods object call METHOD that has locking
3979** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3980**
3981** * An I/O method finder function called FINDER that returns a pointer
3982** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003983*/
drhd9e5c4f2010-05-12 18:01:39 +00003984#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003985static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003986 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003987 CLOSE, /* xClose */ \
3988 unixRead, /* xRead */ \
3989 unixWrite, /* xWrite */ \
3990 unixTruncate, /* xTruncate */ \
3991 unixSync, /* xSync */ \
3992 unixFileSize, /* xFileSize */ \
3993 LOCK, /* xLock */ \
3994 UNLOCK, /* xUnlock */ \
3995 CKLOCK, /* xCheckReservedLock */ \
3996 unixFileControl, /* xFileControl */ \
3997 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003998 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00003999 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004000 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004001 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004002 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004003}; \
drh0c2694b2009-09-03 16:23:44 +00004004static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4005 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004006 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004007} \
drh0c2694b2009-09-03 16:23:44 +00004008static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004009 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004010
4011/*
4012** Here are all of the sqlite3_io_methods objects for each of the
4013** locking strategies. Functions that return pointers to these methods
4014** are also created.
4015*/
4016IOMETHODS(
4017 posixIoFinder, /* Finder function name */
4018 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004019 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004020 unixClose, /* xClose method */
4021 unixLock, /* xLock method */
4022 unixUnlock, /* xUnlock method */
4023 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004024)
drh7708e972008-11-29 00:56:52 +00004025IOMETHODS(
4026 nolockIoFinder, /* Finder function name */
4027 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004028 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004029 nolockClose, /* xClose method */
4030 nolockLock, /* xLock method */
4031 nolockUnlock, /* xUnlock method */
4032 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004033)
drh7708e972008-11-29 00:56:52 +00004034IOMETHODS(
4035 dotlockIoFinder, /* Finder function name */
4036 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004037 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004038 dotlockClose, /* xClose method */
4039 dotlockLock, /* xLock method */
4040 dotlockUnlock, /* xUnlock method */
4041 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004042)
drh7708e972008-11-29 00:56:52 +00004043
chw78a13182009-04-07 05:35:03 +00004044#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004045IOMETHODS(
4046 flockIoFinder, /* Finder function name */
4047 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004048 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004049 flockClose, /* xClose method */
4050 flockLock, /* xLock method */
4051 flockUnlock, /* xUnlock method */
4052 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004053)
drh7708e972008-11-29 00:56:52 +00004054#endif
4055
drh6c7d5c52008-11-21 20:32:33 +00004056#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004057IOMETHODS(
4058 semIoFinder, /* Finder function name */
4059 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004060 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004061 semClose, /* xClose method */
4062 semLock, /* xLock method */
4063 semUnlock, /* xUnlock method */
4064 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004065)
aswiftaebf4132008-11-21 00:10:35 +00004066#endif
drh7708e972008-11-29 00:56:52 +00004067
drhd2cb50b2009-01-09 21:41:17 +00004068#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004069IOMETHODS(
4070 afpIoFinder, /* Finder function name */
4071 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004072 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004073 afpClose, /* xClose method */
4074 afpLock, /* xLock method */
4075 afpUnlock, /* xUnlock method */
4076 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004077)
drh715ff302008-12-03 22:32:44 +00004078#endif
4079
4080/*
4081** The proxy locking method is a "super-method" in the sense that it
4082** opens secondary file descriptors for the conch and lock files and
4083** it uses proxy, dot-file, AFP, and flock() locking methods on those
4084** secondary files. For this reason, the division that implements
4085** proxy locking is located much further down in the file. But we need
4086** to go ahead and define the sqlite3_io_methods and finder function
4087** for proxy locking here. So we forward declare the I/O methods.
4088*/
drhd2cb50b2009-01-09 21:41:17 +00004089#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004090static int proxyClose(sqlite3_file*);
4091static int proxyLock(sqlite3_file*, int);
4092static int proxyUnlock(sqlite3_file*, int);
4093static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004094IOMETHODS(
4095 proxyIoFinder, /* Finder function name */
4096 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004097 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004098 proxyClose, /* xClose method */
4099 proxyLock, /* xLock method */
4100 proxyUnlock, /* xUnlock method */
4101 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004102)
aswiftaebf4132008-11-21 00:10:35 +00004103#endif
drh7708e972008-11-29 00:56:52 +00004104
drh7ed97b92010-01-20 13:07:21 +00004105/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4106#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4107IOMETHODS(
4108 nfsIoFinder, /* Finder function name */
4109 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004110 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004111 unixClose, /* xClose method */
4112 unixLock, /* xLock method */
4113 nfsUnlock, /* xUnlock method */
4114 unixCheckReservedLock /* xCheckReservedLock method */
4115)
4116#endif
drh7708e972008-11-29 00:56:52 +00004117
drhd2cb50b2009-01-09 21:41:17 +00004118#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004119/*
drh6b9d6dd2008-12-03 19:34:47 +00004120** This "finder" function attempts to determine the best locking strategy
4121** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004122** object that implements that strategy.
4123**
4124** This is for MacOSX only.
4125*/
drh1875f7a2008-12-08 18:19:17 +00004126static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004127 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004128 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004129){
4130 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004131 const char *zFilesystem; /* Filesystem type name */
4132 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004133 } aMap[] = {
4134 { "hfs", &posixIoMethods },
4135 { "ufs", &posixIoMethods },
4136 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004137 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004138 { "webdav", &nolockIoMethods },
4139 { 0, 0 }
4140 };
4141 int i;
4142 struct statfs fsInfo;
4143 struct flock lockInfo;
4144
4145 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004146 /* If filePath==NULL that means we are dealing with a transient file
4147 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004148 return &nolockIoMethods;
4149 }
4150 if( statfs(filePath, &fsInfo) != -1 ){
4151 if( fsInfo.f_flags & MNT_RDONLY ){
4152 return &nolockIoMethods;
4153 }
4154 for(i=0; aMap[i].zFilesystem; i++){
4155 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4156 return aMap[i].pMethods;
4157 }
4158 }
4159 }
4160
4161 /* Default case. Handles, amongst others, "nfs".
4162 ** Test byte-range lock using fcntl(). If the call succeeds,
4163 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004164 */
drh7708e972008-11-29 00:56:52 +00004165 lockInfo.l_len = 1;
4166 lockInfo.l_start = 0;
4167 lockInfo.l_whence = SEEK_SET;
4168 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004169 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004170 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4171 return &nfsIoMethods;
4172 } else {
4173 return &posixIoMethods;
4174 }
drh7708e972008-11-29 00:56:52 +00004175 }else{
4176 return &dotlockIoMethods;
4177 }
4178}
drh0c2694b2009-09-03 16:23:44 +00004179static const sqlite3_io_methods
4180 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004181
drhd2cb50b2009-01-09 21:41:17 +00004182#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004183
chw78a13182009-04-07 05:35:03 +00004184#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4185/*
4186** This "finder" function attempts to determine the best locking strategy
4187** for the database file "filePath". It then returns the sqlite3_io_methods
4188** object that implements that strategy.
4189**
4190** This is for VXWorks only.
4191*/
4192static const sqlite3_io_methods *autolockIoFinderImpl(
4193 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004194 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004195){
4196 struct flock lockInfo;
4197
4198 if( !filePath ){
4199 /* If filePath==NULL that means we are dealing with a transient file
4200 ** that does not need to be locked. */
4201 return &nolockIoMethods;
4202 }
4203
4204 /* Test if fcntl() is supported and use POSIX style locks.
4205 ** Otherwise fall back to the named semaphore method.
4206 */
4207 lockInfo.l_len = 1;
4208 lockInfo.l_start = 0;
4209 lockInfo.l_whence = SEEK_SET;
4210 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004211 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004212 return &posixIoMethods;
4213 }else{
4214 return &semIoMethods;
4215 }
4216}
drh0c2694b2009-09-03 16:23:44 +00004217static const sqlite3_io_methods
4218 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004219
4220#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4221
drh7708e972008-11-29 00:56:52 +00004222/*
4223** An abstract type for a pointer to a IO method finder function:
4224*/
drh0c2694b2009-09-03 16:23:44 +00004225typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004226
aswiftaebf4132008-11-21 00:10:35 +00004227
drh734c9862008-11-28 15:37:20 +00004228/****************************************************************************
4229**************************** sqlite3_vfs methods ****************************
4230**
4231** This division contains the implementation of methods on the
4232** sqlite3_vfs object.
4233*/
4234
danielk1977a3d4c882007-03-23 10:08:38 +00004235/*
danielk1977e339d652008-06-28 11:23:00 +00004236** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004237*/
4238static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004239 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004240 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004241 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004242 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004243 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004244 int noLock, /* Omit locking if true */
4245 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004246){
drh7708e972008-11-29 00:56:52 +00004247 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004248 unixFile *pNew = (unixFile *)pId;
4249 int rc = SQLITE_OK;
4250
drh8af6c222010-05-14 12:43:01 +00004251 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004252
dane946c392009-08-22 11:39:46 +00004253 /* Parameter isDelete is only used on vxworks. Express this explicitly
4254 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004255 */
drh7708e972008-11-29 00:56:52 +00004256 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004257
dan00157392010-10-05 11:33:15 +00004258 /* Usually the path zFilename should not be a relative pathname. The
4259 ** exception is when opening the proxy "conch" file in builds that
4260 ** include the special Apple locking styles.
4261 */
dan00157392010-10-05 11:33:15 +00004262#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004263 assert( zFilename==0 || zFilename[0]=='/'
4264 || pVfs->pAppData==(void*)&autolockIoFinder );
4265#else
4266 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004267#endif
dan00157392010-10-05 11:33:15 +00004268
drh308c2a52010-05-14 11:30:18 +00004269 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004270 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004271 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004272 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004273 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004274
drh6c7d5c52008-11-21 20:32:33 +00004275#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004276 pNew->pId = vxworksFindFileId(zFilename);
4277 if( pNew->pId==0 ){
4278 noLock = 1;
4279 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004280 }
4281#endif
4282
drhda0e7682008-07-30 15:27:54 +00004283 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004284 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004285 }else{
drh0c2694b2009-09-03 16:23:44 +00004286 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004287#if SQLITE_ENABLE_LOCKING_STYLE
4288 /* Cache zFilename in the locking context (AFP and dotlock override) for
4289 ** proxyLock activation is possible (remote proxy is based on db name)
4290 ** zFilename remains valid until file is closed, to support */
4291 pNew->lockingContext = (void*)zFilename;
4292#endif
drhda0e7682008-07-30 15:27:54 +00004293 }
danielk1977e339d652008-06-28 11:23:00 +00004294
drh7ed97b92010-01-20 13:07:21 +00004295 if( pLockingStyle == &posixIoMethods
4296#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4297 || pLockingStyle == &nfsIoMethods
4298#endif
4299 ){
drh7708e972008-11-29 00:56:52 +00004300 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004301 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004302 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004303 /* If an error occured in findInodeInfo(), close the file descriptor
4304 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004305 ** in two scenarios:
4306 **
4307 ** (a) A call to fstat() failed.
4308 ** (b) A malloc failed.
4309 **
4310 ** Scenario (b) may only occur if the process is holding no other
4311 ** file descriptors open on the same file. If there were other file
4312 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004313 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004314 ** handle h - as it is guaranteed that no posix locks will be released
4315 ** by doing so.
4316 **
4317 ** If scenario (a) caused the error then things are not so safe. The
4318 ** implicit assumption here is that if fstat() fails, things are in
4319 ** such bad shape that dropping a lock or two doesn't matter much.
4320 */
drh0e9365c2011-03-02 02:08:13 +00004321 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004322 h = -1;
4323 }
drh7708e972008-11-29 00:56:52 +00004324 unixLeaveMutex();
4325 }
danielk1977e339d652008-06-28 11:23:00 +00004326
drhd2cb50b2009-01-09 21:41:17 +00004327#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004328 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004329 /* AFP locking uses the file path so it needs to be included in
4330 ** the afpLockingContext.
4331 */
4332 afpLockingContext *pCtx;
4333 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4334 if( pCtx==0 ){
4335 rc = SQLITE_NOMEM;
4336 }else{
4337 /* NB: zFilename exists and remains valid until the file is closed
4338 ** according to requirement F11141. So we do not need to make a
4339 ** copy of the filename. */
4340 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004341 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004342 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004343 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004344 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004345 if( rc!=SQLITE_OK ){
4346 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004347 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004348 h = -1;
4349 }
drh7708e972008-11-29 00:56:52 +00004350 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004351 }
drh7708e972008-11-29 00:56:52 +00004352 }
4353#endif
danielk1977e339d652008-06-28 11:23:00 +00004354
drh7708e972008-11-29 00:56:52 +00004355 else if( pLockingStyle == &dotlockIoMethods ){
4356 /* Dotfile locking uses the file path so it needs to be included in
4357 ** the dotlockLockingContext
4358 */
4359 char *zLockFile;
4360 int nFilename;
drhea678832008-12-10 19:26:22 +00004361 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004362 zLockFile = (char *)sqlite3_malloc(nFilename);
4363 if( zLockFile==0 ){
4364 rc = SQLITE_NOMEM;
4365 }else{
4366 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004367 }
drh7708e972008-11-29 00:56:52 +00004368 pNew->lockingContext = zLockFile;
4369 }
danielk1977e339d652008-06-28 11:23:00 +00004370
drh6c7d5c52008-11-21 20:32:33 +00004371#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004372 else if( pLockingStyle == &semIoMethods ){
4373 /* Named semaphore locking uses the file path so it needs to be
4374 ** included in the semLockingContext
4375 */
4376 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004377 rc = findInodeInfo(pNew, &pNew->pInode);
4378 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4379 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004380 int n;
drh2238dcc2009-08-27 17:56:20 +00004381 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004382 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004383 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004384 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004385 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4386 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004387 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004388 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004389 }
chw97185482008-11-17 08:05:31 +00004390 }
drh7708e972008-11-29 00:56:52 +00004391 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004392 }
drh7708e972008-11-29 00:56:52 +00004393#endif
aswift5b1a2562008-08-22 00:22:35 +00004394
4395 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004396#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004397 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004398 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004399 h = -1;
chw97185482008-11-17 08:05:31 +00004400 unlink(zFilename);
4401 isDelete = 0;
4402 }
4403 pNew->isDelete = isDelete;
4404#endif
danielk1977e339d652008-06-28 11:23:00 +00004405 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004406 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4407 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004408 }else{
drh7708e972008-11-29 00:56:52 +00004409 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004410 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004411 }
danielk1977e339d652008-06-28 11:23:00 +00004412 return rc;
drh054889e2005-11-30 03:20:31 +00004413}
drh9c06c952005-11-26 00:25:00 +00004414
danielk1977ad94b582007-08-20 06:44:22 +00004415/*
4416** Open a file descriptor to the directory containing file zFilename.
4417** If successful, *pFd is set to the opened file descriptor and
4418** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4419** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4420** value.
4421**
4422** If SQLITE_OK is returned, the caller is responsible for closing
4423** the file descriptor *pFd using close().
4424*/
danielk1977fee2d252007-08-18 10:59:19 +00004425static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004426 int ii;
drh777b17a2007-09-20 10:02:54 +00004427 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004428 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004429
drh153c62c2007-08-24 03:51:33 +00004430 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004431 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004432 if( ii>0 ){
4433 zDirname[ii] = '\0';
drh99ab3b12011-03-02 15:09:07 +00004434 fd = osOpen(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004435 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004436#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004437 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004438#endif
drh308c2a52010-05-14 11:30:18 +00004439 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004440 }
4441 }
danielk1977fee2d252007-08-18 10:59:19 +00004442 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004443 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004444}
4445
danielk1977b4b47412007-08-17 15:53:36 +00004446/*
drh8b3cf822010-06-01 21:02:51 +00004447** Return the name of a directory in which to put temporary files.
4448** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004449*/
drh7234c6d2010-06-19 15:10:09 +00004450static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004451 static const char *azDirs[] = {
4452 0,
aswiftaebf4132008-11-21 00:10:35 +00004453 0,
danielk197717b90b52008-06-06 11:11:25 +00004454 "/var/tmp",
4455 "/usr/tmp",
4456 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004457 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004458 };
drh8b3cf822010-06-01 21:02:51 +00004459 unsigned int i;
4460 struct stat buf;
4461 const char *zDir = 0;
4462
4463 azDirs[0] = sqlite3_temp_directory;
4464 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004465 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004466 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004467 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004468 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004469 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004470 break;
4471 }
4472 return zDir;
4473}
4474
4475/*
4476** Create a temporary file name in zBuf. zBuf must be allocated
4477** by the calling process and must be big enough to hold at least
4478** pVfs->mxPathname bytes.
4479*/
4480static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004481 static const unsigned char zChars[] =
4482 "abcdefghijklmnopqrstuvwxyz"
4483 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4484 "0123456789";
drh41022642008-11-21 00:24:42 +00004485 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004486 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004487
4488 /* It's odd to simulate an io-error here, but really this is just
4489 ** using the io-error infrastructure to test that SQLite handles this
4490 ** function failing.
4491 */
4492 SimulateIOError( return SQLITE_IOERR );
4493
drh7234c6d2010-06-19 15:10:09 +00004494 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004495 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004496
4497 /* Check that the output buffer is large enough for the temporary file
4498 ** name. If it is not, return SQLITE_ERROR.
4499 */
danielk197700e13612008-11-17 19:18:54 +00004500 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004501 return SQLITE_ERROR;
4502 }
4503
4504 do{
4505 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004506 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004507 sqlite3_randomness(15, &zBuf[j]);
4508 for(i=0; i<15; i++, j++){
4509 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4510 }
4511 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004512 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004513 return SQLITE_OK;
4514}
4515
drhd2cb50b2009-01-09 21:41:17 +00004516#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004517/*
4518** Routine to transform a unixFile into a proxy-locking unixFile.
4519** Implementation in the proxy-lock division, but used by unixOpen()
4520** if SQLITE_PREFER_PROXY_LOCKING is defined.
4521*/
4522static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004523#endif
drhc66d5b62008-12-03 22:48:32 +00004524
dan08da86a2009-08-21 17:18:03 +00004525/*
4526** Search for an unused file descriptor that was opened on the database
4527** file (not a journal or master-journal file) identified by pathname
4528** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4529** argument to this function.
4530**
4531** Such a file descriptor may exist if a database connection was closed
4532** but the associated file descriptor could not be closed because some
4533** other file descriptor open on the same file is holding a file-lock.
4534** Refer to comments in the unixClose() function and the lengthy comment
4535** describing "Posix Advisory Locking" at the start of this file for
4536** further details. Also, ticket #4018.
4537**
4538** If a suitable file descriptor is found, then it is returned. If no
4539** such file descriptor is located, -1 is returned.
4540*/
dane946c392009-08-22 11:39:46 +00004541static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4542 UnixUnusedFd *pUnused = 0;
4543
4544 /* Do not search for an unused file descriptor on vxworks. Not because
4545 ** vxworks would not benefit from the change (it might, we're not sure),
4546 ** but because no way to test it is currently available. It is better
4547 ** not to risk breaking vxworks support for the sake of such an obscure
4548 ** feature. */
4549#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004550 struct stat sStat; /* Results of stat() call */
4551
4552 /* A stat() call may fail for various reasons. If this happens, it is
4553 ** almost certain that an open() call on the same path will also fail.
4554 ** For this reason, if an error occurs in the stat() call here, it is
4555 ** ignored and -1 is returned. The caller will try to open a new file
4556 ** descriptor on the same path, fail, and return an error to SQLite.
4557 **
4558 ** Even if a subsequent open() call does succeed, the consequences of
4559 ** not searching for a resusable file descriptor are not dire. */
4560 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004561 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004562
4563 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004564 pInode = inodeList;
4565 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4566 || pInode->fileId.ino!=sStat.st_ino) ){
4567 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004568 }
drh8af6c222010-05-14 12:43:01 +00004569 if( pInode ){
dane946c392009-08-22 11:39:46 +00004570 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004571 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004572 pUnused = *pp;
4573 if( pUnused ){
4574 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004575 }
4576 }
4577 unixLeaveMutex();
4578 }
dane946c392009-08-22 11:39:46 +00004579#endif /* if !OS_VXWORKS */
4580 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004581}
danielk197717b90b52008-06-06 11:11:25 +00004582
4583/*
danddb0ac42010-07-14 14:48:58 +00004584** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004585** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004586** and a value suitable for passing as the third argument to open(2) is
4587** written to *pMode. If an IO error occurs, an SQLite error code is
4588** returned and the value of *pMode is not modified.
4589**
4590** If the file being opened is a temporary file, it is always created with
4591** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004592** is a database or master journal file, it is created with the permissions
4593** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004594**
drh8ab58662010-07-15 18:38:39 +00004595** Finally, if the file being opened is a WAL or regular journal file, then
4596** this function queries the file-system for the permissions on the
4597** corresponding database file and sets *pMode to this value. Whenever
4598** possible, WAL and journal files are created using the same permissions
4599** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004600*/
4601static int findCreateFileMode(
4602 const char *zPath, /* Path of file (possibly) being created */
4603 int flags, /* Flags passed as 4th argument to xOpen() */
4604 mode_t *pMode /* OUT: Permissions to open file with */
4605){
4606 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004607 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004608 char zDb[MAX_PATHNAME+1]; /* Database file path */
4609 int nDb; /* Number of valid bytes in zDb */
4610 struct stat sStat; /* Output of stat() on database file */
4611
dana0c989d2010-11-05 18:07:37 +00004612 /* zPath is a path to a WAL or journal file. The following block derives
4613 ** the path to the associated database file from zPath. This block handles
4614 ** the following naming conventions:
4615 **
4616 ** "<path to db>-journal"
4617 ** "<path to db>-wal"
4618 ** "<path to db>-journal-NNNN"
4619 ** "<path to db>-wal-NNNN"
4620 **
4621 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4622 ** used by the test_multiplex.c module.
4623 */
4624 nDb = sqlite3Strlen30(zPath) - 1;
4625 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4626 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004627 memcpy(zDb, zPath, nDb);
4628 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004629
danddb0ac42010-07-14 14:48:58 +00004630 if( 0==stat(zDb, &sStat) ){
4631 *pMode = sStat.st_mode & 0777;
4632 }else{
4633 rc = SQLITE_IOERR_FSTAT;
4634 }
4635 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4636 *pMode = 0600;
4637 }else{
4638 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4639 }
4640 return rc;
4641}
4642
4643/*
danielk1977ad94b582007-08-20 06:44:22 +00004644** Open the file zPath.
4645**
danielk1977b4b47412007-08-17 15:53:36 +00004646** Previously, the SQLite OS layer used three functions in place of this
4647** one:
4648**
4649** sqlite3OsOpenReadWrite();
4650** sqlite3OsOpenReadOnly();
4651** sqlite3OsOpenExclusive();
4652**
4653** These calls correspond to the following combinations of flags:
4654**
4655** ReadWrite() -> (READWRITE | CREATE)
4656** ReadOnly() -> (READONLY)
4657** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4658**
4659** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4660** true, the file was configured to be automatically deleted when the
4661** file handle closed. To achieve the same effect using this new
4662** interface, add the DELETEONCLOSE flag to those specified above for
4663** OpenExclusive().
4664*/
4665static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004666 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4667 const char *zPath, /* Pathname of file to be opened */
4668 sqlite3_file *pFile, /* The file descriptor to be filled in */
4669 int flags, /* Input flags to control the opening */
4670 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004671){
dan08da86a2009-08-21 17:18:03 +00004672 unixFile *p = (unixFile *)pFile;
4673 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004674 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004675 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004676 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004677 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004678 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004679
4680 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4681 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4682 int isCreate = (flags & SQLITE_OPEN_CREATE);
4683 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4684 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004685#if SQLITE_ENABLE_LOCKING_STYLE
4686 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4687#endif
danielk1977b4b47412007-08-17 15:53:36 +00004688
danielk1977fee2d252007-08-18 10:59:19 +00004689 /* If creating a master or main-file journal, this function will open
4690 ** a file-descriptor on the directory too. The first time unixSync()
4691 ** is called the directory file descriptor will be fsync()ed and close()d.
4692 */
danddb0ac42010-07-14 14:48:58 +00004693 int isOpenDirectory = (isCreate && (
4694 eType==SQLITE_OPEN_MASTER_JOURNAL
4695 || eType==SQLITE_OPEN_MAIN_JOURNAL
4696 || eType==SQLITE_OPEN_WAL
4697 ));
danielk1977fee2d252007-08-18 10:59:19 +00004698
danielk197717b90b52008-06-06 11:11:25 +00004699 /* If argument zPath is a NULL pointer, this function is required to open
4700 ** a temporary file. Use this buffer to store the file name in.
4701 */
4702 char zTmpname[MAX_PATHNAME+1];
4703 const char *zName = zPath;
4704
danielk1977fee2d252007-08-18 10:59:19 +00004705 /* Check the following statements are true:
4706 **
4707 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4708 ** (b) if CREATE is set, then READWRITE must also be set, and
4709 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004710 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004711 */
danielk1977b4b47412007-08-17 15:53:36 +00004712 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004713 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004714 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004715 assert(isDelete==0 || isCreate);
4716
danddb0ac42010-07-14 14:48:58 +00004717 /* The main DB, main journal, WAL file and master journal are never
4718 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004719 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4720 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4721 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004722 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004723
danielk1977fee2d252007-08-18 10:59:19 +00004724 /* Assert that the upper layer has set one of the "file-type" flags. */
4725 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4726 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4727 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004728 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004729 );
4730
dan08da86a2009-08-21 17:18:03 +00004731 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004732
dan08da86a2009-08-21 17:18:03 +00004733 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004734 UnixUnusedFd *pUnused;
4735 pUnused = findReusableFd(zName, flags);
4736 if( pUnused ){
4737 fd = pUnused->fd;
4738 }else{
dan6aa657f2009-08-24 18:57:58 +00004739 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004740 if( !pUnused ){
4741 return SQLITE_NOMEM;
4742 }
4743 }
4744 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004745 }else if( !zName ){
4746 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004747 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004748 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004749 if( rc!=SQLITE_OK ){
4750 return rc;
4751 }
4752 zName = zTmpname;
4753 }
4754
dan08da86a2009-08-21 17:18:03 +00004755 /* Determine the value of the flags parameter passed to POSIX function
4756 ** open(). These must be calculated even if open() is not called, as
4757 ** they may be stored as part of the file handle and used by the
4758 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004759 if( isReadonly ) openFlags |= O_RDONLY;
4760 if( isReadWrite ) openFlags |= O_RDWR;
4761 if( isCreate ) openFlags |= O_CREAT;
4762 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4763 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004764
danielk1977b4b47412007-08-17 15:53:36 +00004765 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004766 mode_t openMode; /* Permissions to create file with */
4767 rc = findCreateFileMode(zName, flags, &openMode);
4768 if( rc!=SQLITE_OK ){
4769 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004770 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004771 return rc;
4772 }
drh99ab3b12011-03-02 15:09:07 +00004773 fd = osOpen(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004774 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004775 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4776 /* Failed to open the file for read/write access. Try read-only. */
4777 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004778 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004779 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004780 openFlags |= O_RDONLY;
drh99ab3b12011-03-02 15:09:07 +00004781 fd = osOpen(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004782 }
4783 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004784 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004785 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004786 }
danielk1977b4b47412007-08-17 15:53:36 +00004787 }
dan08da86a2009-08-21 17:18:03 +00004788 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004789 if( pOutFlags ){
4790 *pOutFlags = flags;
4791 }
4792
dane946c392009-08-22 11:39:46 +00004793 if( p->pUnused ){
4794 p->pUnused->fd = fd;
4795 p->pUnused->flags = flags;
4796 }
4797
danielk1977b4b47412007-08-17 15:53:36 +00004798 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004799#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004800 zPath = zName;
4801#else
danielk197717b90b52008-06-06 11:11:25 +00004802 unlink(zName);
chw97185482008-11-17 08:05:31 +00004803#endif
danielk1977b4b47412007-08-17 15:53:36 +00004804 }
drh41022642008-11-21 00:24:42 +00004805#if SQLITE_ENABLE_LOCKING_STYLE
4806 else{
dan08da86a2009-08-21 17:18:03 +00004807 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004808 }
4809#endif
4810
danielk1977fee2d252007-08-18 10:59:19 +00004811 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004812 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004813 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004814 /* It is safe to close fd at this point, because it is guaranteed not
4815 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004816 ** it would not be safe to close as this would release any locks held
4817 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004818 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00004819 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004820 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004821 }
4822 }
danielk1977e339d652008-06-28 11:23:00 +00004823
4824#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004825 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00004826#endif
4827
drhda0e7682008-07-30 15:27:54 +00004828 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004829
drh7ed97b92010-01-20 13:07:21 +00004830
4831#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4832 struct statfs fsInfo;
4833 if( fstatfs(fd, &fsInfo) == -1 ){
4834 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00004835 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
4836 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004837 return SQLITE_IOERR_ACCESS;
4838 }
4839 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4840 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4841 }
4842#endif
4843
4844#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004845#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004846 isAutoProxy = 1;
4847#endif
4848 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004849 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4850 int useProxy = 0;
4851
dan08da86a2009-08-21 17:18:03 +00004852 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4853 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004854 if( envforce!=NULL ){
4855 useProxy = atoi(envforce)>0;
4856 }else{
4857 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004858 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004859 /* In theory, the close(fd) call is sub-optimal. If the file opened
4860 ** with fd is a database file, and there are other connections open
4861 ** on that file that are currently holding advisory locks on it,
4862 ** then the call to close() will cancel those locks. In practice,
4863 ** we're assuming that statfs() doesn't fail very often. At least
4864 ** not while other file descriptors opened by the same process on
4865 ** the same file are working. */
4866 p->lastErrno = errno;
4867 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00004868 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00004869 }
drh0e9365c2011-03-02 02:08:13 +00004870 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00004871 rc = SQLITE_IOERR_ACCESS;
4872 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004873 }
4874 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4875 }
4876 if( useProxy ){
4877 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4878 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004879 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004880 if( rc!=SQLITE_OK ){
4881 /* Use unixClose to clean up the resources added in fillInUnixFile
4882 ** and clear all the structure's references. Specifically,
4883 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4884 */
4885 unixClose(pFile);
4886 return rc;
4887 }
aswiftaebf4132008-11-21 00:10:35 +00004888 }
dane946c392009-08-22 11:39:46 +00004889 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004890 }
4891 }
4892#endif
4893
dane946c392009-08-22 11:39:46 +00004894 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4895open_finished:
4896 if( rc!=SQLITE_OK ){
4897 sqlite3_free(p->pUnused);
4898 }
4899 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004900}
4901
dane946c392009-08-22 11:39:46 +00004902
danielk1977b4b47412007-08-17 15:53:36 +00004903/*
danielk1977fee2d252007-08-18 10:59:19 +00004904** Delete the file at zPath. If the dirSync argument is true, fsync()
4905** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004906*/
drh6b9d6dd2008-12-03 19:34:47 +00004907static int unixDelete(
4908 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4909 const char *zPath, /* Name of file to be deleted */
4910 int dirSync /* If true, fsync() directory after deleting file */
4911){
danielk1977fee2d252007-08-18 10:59:19 +00004912 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004913 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004914 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00004915 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00004916 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00004917 }
danielk1977d39fa702008-10-16 13:27:40 +00004918#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004919 if( dirSync ){
4920 int fd;
4921 rc = openDirectory(zPath, &fd);
4922 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004923#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004924 if( fsync(fd)==-1 )
4925#else
4926 if( fsync(fd) )
4927#endif
4928 {
dane18d4952011-02-21 11:46:24 +00004929 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00004930 }
drh0e9365c2011-03-02 02:08:13 +00004931 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00004932 }
4933 }
danielk1977d138dd82008-10-15 16:02:48 +00004934#endif
danielk1977fee2d252007-08-18 10:59:19 +00004935 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004936}
4937
danielk197790949c22007-08-17 16:50:38 +00004938/*
4939** Test the existance of or access permissions of file zPath. The
4940** test performed depends on the value of flags:
4941**
4942** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4943** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4944** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4945**
4946** Otherwise return 0.
4947*/
danielk1977861f7452008-06-05 11:39:11 +00004948static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004949 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4950 const char *zPath, /* Path of the file to examine */
4951 int flags, /* What do we want to learn about the zPath file? */
4952 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004953){
rse25c0d1a2007-09-20 08:38:14 +00004954 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004955 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004956 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004957 switch( flags ){
4958 case SQLITE_ACCESS_EXISTS:
4959 amode = F_OK;
4960 break;
4961 case SQLITE_ACCESS_READWRITE:
4962 amode = W_OK|R_OK;
4963 break;
drh50d3f902007-08-27 21:10:36 +00004964 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004965 amode = R_OK;
4966 break;
4967
4968 default:
4969 assert(!"Invalid flags argument");
4970 }
drh99ab3b12011-03-02 15:09:07 +00004971 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00004972 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4973 struct stat buf;
4974 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4975 *pResOut = 0;
4976 }
4977 }
danielk1977861f7452008-06-05 11:39:11 +00004978 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004979}
4980
danielk1977b4b47412007-08-17 15:53:36 +00004981
4982/*
4983** Turn a relative pathname into a full pathname. The relative path
4984** is stored as a nul-terminated string in the buffer pointed to by
4985** zPath.
4986**
4987** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4988** (in this case, MAX_PATHNAME bytes). The full-path is written to
4989** this buffer before returning.
4990*/
danielk1977adfb9b02007-09-17 07:02:56 +00004991static int unixFullPathname(
4992 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4993 const char *zPath, /* Possibly relative input path */
4994 int nOut, /* Size of output buffer in bytes */
4995 char *zOut /* Output buffer */
4996){
danielk1977843e65f2007-09-01 16:16:15 +00004997
4998 /* It's odd to simulate an io-error here, but really this is just
4999 ** using the io-error infrastructure to test that SQLite handles this
5000 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005001 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005002 */
5003 SimulateIOError( return SQLITE_ERROR );
5004
drh153c62c2007-08-24 03:51:33 +00005005 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005006 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005007
drh3c7f2dc2007-12-06 13:26:20 +00005008 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005009 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005010 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005011 }else{
5012 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005013 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005014 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005015 }
drhea678832008-12-10 19:26:22 +00005016 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005017 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005018 }
5019 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005020}
5021
drh0ccebe72005-06-07 22:22:50 +00005022
drh761df872006-12-21 01:29:22 +00005023#ifndef SQLITE_OMIT_LOAD_EXTENSION
5024/*
5025** Interfaces for opening a shared library, finding entry points
5026** within the shared library, and closing the shared library.
5027*/
5028#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005029static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5030 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005031 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5032}
danielk197795c8a542007-09-01 06:51:27 +00005033
5034/*
5035** SQLite calls this function immediately after a call to unixDlSym() or
5036** unixDlOpen() fails (returns a null pointer). If a more detailed error
5037** message is available, it is written to zBufOut. If no error message
5038** is available, zBufOut is left unmodified and SQLite uses a default
5039** error message.
5040*/
danielk1977397d65f2008-11-19 11:35:39 +00005041static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005042 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005043 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005044 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005045 zErr = dlerror();
5046 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005047 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005048 }
drh6c7d5c52008-11-21 20:32:33 +00005049 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005050}
drh1875f7a2008-12-08 18:19:17 +00005051static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5052 /*
5053 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5054 ** cast into a pointer to a function. And yet the library dlsym() routine
5055 ** returns a void* which is really a pointer to a function. So how do we
5056 ** use dlsym() with -pedantic-errors?
5057 **
5058 ** Variable x below is defined to be a pointer to a function taking
5059 ** parameters void* and const char* and returning a pointer to a function.
5060 ** We initialize x by assigning it a pointer to the dlsym() function.
5061 ** (That assignment requires a cast.) Then we call the function that
5062 ** x points to.
5063 **
5064 ** This work-around is unlikely to work correctly on any system where
5065 ** you really cannot cast a function pointer into void*. But then, on the
5066 ** other hand, dlsym() will not work on such a system either, so we have
5067 ** not really lost anything.
5068 */
5069 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005070 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005071 x = (void(*(*)(void*,const char*))(void))dlsym;
5072 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005073}
danielk1977397d65f2008-11-19 11:35:39 +00005074static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5075 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005076 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005077}
danielk1977b4b47412007-08-17 15:53:36 +00005078#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5079 #define unixDlOpen 0
5080 #define unixDlError 0
5081 #define unixDlSym 0
5082 #define unixDlClose 0
5083#endif
5084
5085/*
danielk197790949c22007-08-17 16:50:38 +00005086** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005087*/
danielk1977397d65f2008-11-19 11:35:39 +00005088static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5089 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005090 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005091
drhbbd42a62004-05-22 17:41:58 +00005092 /* We have to initialize zBuf to prevent valgrind from reporting
5093 ** errors. The reports issued by valgrind are incorrect - we would
5094 ** prefer that the randomness be increased by making use of the
5095 ** uninitialized space in zBuf - but valgrind errors tend to worry
5096 ** some users. Rather than argue, it seems easier just to initialize
5097 ** the whole array and silence valgrind, even if that means less randomness
5098 ** in the random seed.
5099 **
5100 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005101 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005102 ** tests repeatable.
5103 */
danielk1977b4b47412007-08-17 15:53:36 +00005104 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005105#if !defined(SQLITE_TEST)
5106 {
drh842b8642005-01-21 17:53:17 +00005107 int pid, fd;
drh99ab3b12011-03-02 15:09:07 +00005108 fd = osOpen("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005109 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005110 time_t t;
5111 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005112 memcpy(zBuf, &t, sizeof(t));
5113 pid = getpid();
5114 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005115 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005116 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005117 }else{
drhff812312011-02-23 13:33:46 +00005118 do{ nBuf = read(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005119 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005120 }
drhbbd42a62004-05-22 17:41:58 +00005121 }
5122#endif
drh72cbd072008-10-14 17:58:38 +00005123 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005124}
5125
danielk1977b4b47412007-08-17 15:53:36 +00005126
drhbbd42a62004-05-22 17:41:58 +00005127/*
5128** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005129** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005130** The return value is the number of microseconds of sleep actually
5131** requested from the underlying operating system, a number which
5132** might be greater than or equal to the argument, but not less
5133** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005134*/
danielk1977397d65f2008-11-19 11:35:39 +00005135static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005136#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005137 struct timespec sp;
5138
5139 sp.tv_sec = microseconds / 1000000;
5140 sp.tv_nsec = (microseconds % 1000000) * 1000;
5141 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005142 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005143 return microseconds;
5144#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005145 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005146 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005147 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005148#else
danielk1977b4b47412007-08-17 15:53:36 +00005149 int seconds = (microseconds+999999)/1000000;
5150 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005151 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005152 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005153#endif
drh88f474a2006-01-02 20:00:12 +00005154}
5155
5156/*
drh6b9d6dd2008-12-03 19:34:47 +00005157** The following variable, if set to a non-zero value, is interpreted as
5158** the number of seconds since 1970 and is used to set the result of
5159** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005160*/
5161#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005162int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005163#endif
5164
5165/*
drhb7e8ea22010-05-03 14:32:30 +00005166** Find the current time (in Universal Coordinated Time). Write into *piNow
5167** the current time and date as a Julian Day number times 86_400_000. In
5168** other words, write into *piNow the number of milliseconds since the Julian
5169** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5170** proleptic Gregorian calendar.
5171**
5172** On success, return 0. Return 1 if the time and date cannot be found.
5173*/
5174static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5175 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5176#if defined(NO_GETTOD)
5177 time_t t;
5178 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005179 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005180#elif OS_VXWORKS
5181 struct timespec sNow;
5182 clock_gettime(CLOCK_REALTIME, &sNow);
5183 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5184#else
5185 struct timeval sNow;
5186 gettimeofday(&sNow, 0);
5187 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5188#endif
5189
5190#ifdef SQLITE_TEST
5191 if( sqlite3_current_time ){
5192 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5193 }
5194#endif
5195 UNUSED_PARAMETER(NotUsed);
5196 return 0;
5197}
5198
5199/*
drhbbd42a62004-05-22 17:41:58 +00005200** Find the current time (in Universal Coordinated Time). Write the
5201** current time and date as a Julian Day number into *prNow and
5202** return 0. Return 1 if the time and date cannot be found.
5203*/
danielk1977397d65f2008-11-19 11:35:39 +00005204static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005205 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005206 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005207 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005208 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005209 return 0;
5210}
danielk1977b4b47412007-08-17 15:53:36 +00005211
drh6b9d6dd2008-12-03 19:34:47 +00005212/*
5213** We added the xGetLastError() method with the intention of providing
5214** better low-level error messages when operating-system problems come up
5215** during SQLite operation. But so far, none of that has been implemented
5216** in the core. So this routine is never called. For now, it is merely
5217** a place-holder.
5218*/
danielk1977397d65f2008-11-19 11:35:39 +00005219static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5220 UNUSED_PARAMETER(NotUsed);
5221 UNUSED_PARAMETER(NotUsed2);
5222 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005223 return 0;
5224}
5225
drhf2424c52010-04-26 00:04:55 +00005226
5227/*
drh734c9862008-11-28 15:37:20 +00005228************************ End of sqlite3_vfs methods ***************************
5229******************************************************************************/
5230
drh715ff302008-12-03 22:32:44 +00005231/******************************************************************************
5232************************** Begin Proxy Locking ********************************
5233**
5234** Proxy locking is a "uber-locking-method" in this sense: It uses the
5235** other locking methods on secondary lock files. Proxy locking is a
5236** meta-layer over top of the primitive locking implemented above. For
5237** this reason, the division that implements of proxy locking is deferred
5238** until late in the file (here) after all of the other I/O methods have
5239** been defined - so that the primitive locking methods are available
5240** as services to help with the implementation of proxy locking.
5241**
5242****
5243**
5244** The default locking schemes in SQLite use byte-range locks on the
5245** database file to coordinate safe, concurrent access by multiple readers
5246** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5247** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5248** as POSIX read & write locks over fixed set of locations (via fsctl),
5249** on AFP and SMB only exclusive byte-range locks are available via fsctl
5250** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5251** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5252** address in the shared range is taken for a SHARED lock, the entire
5253** shared range is taken for an EXCLUSIVE lock):
5254**
5255** PENDING_BYTE 0x40000000
5256** RESERVED_BYTE 0x40000001
5257** SHARED_RANGE 0x40000002 -> 0x40000200
5258**
5259** This works well on the local file system, but shows a nearly 100x
5260** slowdown in read performance on AFP because the AFP client disables
5261** the read cache when byte-range locks are present. Enabling the read
5262** cache exposes a cache coherency problem that is present on all OS X
5263** supported network file systems. NFS and AFP both observe the
5264** close-to-open semantics for ensuring cache coherency
5265** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5266** address the requirements for concurrent database access by multiple
5267** readers and writers
5268** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5269**
5270** To address the performance and cache coherency issues, proxy file locking
5271** changes the way database access is controlled by limiting access to a
5272** single host at a time and moving file locks off of the database file
5273** and onto a proxy file on the local file system.
5274**
5275**
5276** Using proxy locks
5277** -----------------
5278**
5279** C APIs
5280**
5281** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5282** <proxy_path> | ":auto:");
5283** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5284**
5285**
5286** SQL pragmas
5287**
5288** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5289** PRAGMA [database.]lock_proxy_file
5290**
5291** Specifying ":auto:" means that if there is a conch file with a matching
5292** host ID in it, the proxy path in the conch file will be used, otherwise
5293** a proxy path based on the user's temp dir
5294** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5295** actual proxy file name is generated from the name and path of the
5296** database file. For example:
5297**
5298** For database path "/Users/me/foo.db"
5299** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5300**
5301** Once a lock proxy is configured for a database connection, it can not
5302** be removed, however it may be switched to a different proxy path via
5303** the above APIs (assuming the conch file is not being held by another
5304** connection or process).
5305**
5306**
5307** How proxy locking works
5308** -----------------------
5309**
5310** Proxy file locking relies primarily on two new supporting files:
5311**
5312** * conch file to limit access to the database file to a single host
5313** at a time
5314**
5315** * proxy file to act as a proxy for the advisory locks normally
5316** taken on the database
5317**
5318** The conch file - to use a proxy file, sqlite must first "hold the conch"
5319** by taking an sqlite-style shared lock on the conch file, reading the
5320** contents and comparing the host's unique host ID (see below) and lock
5321** proxy path against the values stored in the conch. The conch file is
5322** stored in the same directory as the database file and the file name
5323** is patterned after the database file name as ".<databasename>-conch".
5324** If the conch file does not exist, or it's contents do not match the
5325** host ID and/or proxy path, then the lock is escalated to an exclusive
5326** lock and the conch file contents is updated with the host ID and proxy
5327** path and the lock is downgraded to a shared lock again. If the conch
5328** is held by another process (with a shared lock), the exclusive lock
5329** will fail and SQLITE_BUSY is returned.
5330**
5331** The proxy file - a single-byte file used for all advisory file locks
5332** normally taken on the database file. This allows for safe sharing
5333** of the database file for multiple readers and writers on the same
5334** host (the conch ensures that they all use the same local lock file).
5335**
drh715ff302008-12-03 22:32:44 +00005336** Requesting the lock proxy does not immediately take the conch, it is
5337** only taken when the first request to lock database file is made.
5338** This matches the semantics of the traditional locking behavior, where
5339** opening a connection to a database file does not take a lock on it.
5340** The shared lock and an open file descriptor are maintained until
5341** the connection to the database is closed.
5342**
5343** The proxy file and the lock file are never deleted so they only need
5344** to be created the first time they are used.
5345**
5346** Configuration options
5347** ---------------------
5348**
5349** SQLITE_PREFER_PROXY_LOCKING
5350**
5351** Database files accessed on non-local file systems are
5352** automatically configured for proxy locking, lock files are
5353** named automatically using the same logic as
5354** PRAGMA lock_proxy_file=":auto:"
5355**
5356** SQLITE_PROXY_DEBUG
5357**
5358** Enables the logging of error messages during host id file
5359** retrieval and creation
5360**
drh715ff302008-12-03 22:32:44 +00005361** LOCKPROXYDIR
5362**
5363** Overrides the default directory used for lock proxy files that
5364** are named automatically via the ":auto:" setting
5365**
5366** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5367**
5368** Permissions to use when creating a directory for storing the
5369** lock proxy files, only used when LOCKPROXYDIR is not set.
5370**
5371**
5372** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5373** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5374** force proxy locking to be used for every database file opened, and 0
5375** will force automatic proxy locking to be disabled for all database
5376** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5377** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5378*/
5379
5380/*
5381** Proxy locking is only available on MacOSX
5382*/
drhd2cb50b2009-01-09 21:41:17 +00005383#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005384
drh715ff302008-12-03 22:32:44 +00005385/*
5386** The proxyLockingContext has the path and file structures for the remote
5387** and local proxy files in it
5388*/
5389typedef struct proxyLockingContext proxyLockingContext;
5390struct proxyLockingContext {
5391 unixFile *conchFile; /* Open conch file */
5392 char *conchFilePath; /* Name of the conch file */
5393 unixFile *lockProxy; /* Open proxy lock file */
5394 char *lockProxyPath; /* Name of the proxy lock file */
5395 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005396 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005397 void *oldLockingContext; /* Original lockingcontext to restore on close */
5398 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5399};
5400
drh7ed97b92010-01-20 13:07:21 +00005401/*
5402** The proxy lock file path for the database at dbPath is written into lPath,
5403** which must point to valid, writable memory large enough for a maxLen length
5404** file path.
drh715ff302008-12-03 22:32:44 +00005405*/
drh715ff302008-12-03 22:32:44 +00005406static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5407 int len;
5408 int dbLen;
5409 int i;
5410
5411#ifdef LOCKPROXYDIR
5412 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5413#else
5414# ifdef _CS_DARWIN_USER_TEMP_DIR
5415 {
drh7ed97b92010-01-20 13:07:21 +00005416 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005417 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5418 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005419 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005420 }
drh7ed97b92010-01-20 13:07:21 +00005421 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005422 }
5423# else
5424 len = strlcpy(lPath, "/tmp/", maxLen);
5425# endif
5426#endif
5427
5428 if( lPath[len-1]!='/' ){
5429 len = strlcat(lPath, "/", maxLen);
5430 }
5431
5432 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005433 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005434 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005435 char c = dbPath[i];
5436 lPath[i+len] = (c=='/')?'_':c;
5437 }
5438 lPath[i+len]='\0';
5439 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005440 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005441 return SQLITE_OK;
5442}
5443
drh7ed97b92010-01-20 13:07:21 +00005444/*
5445 ** Creates the lock file and any missing directories in lockPath
5446 */
5447static int proxyCreateLockPath(const char *lockPath){
5448 int i, len;
5449 char buf[MAXPATHLEN];
5450 int start = 0;
5451
5452 assert(lockPath!=NULL);
5453 /* try to create all the intermediate directories */
5454 len = (int)strlen(lockPath);
5455 buf[0] = lockPath[0];
5456 for( i=1; i<len; i++ ){
5457 if( lockPath[i] == '/' && (i - start > 0) ){
5458 /* only mkdir if leaf dir != "." or "/" or ".." */
5459 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5460 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5461 buf[i]='\0';
5462 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5463 int err=errno;
5464 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005465 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005466 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005467 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005468 return err;
5469 }
5470 }
5471 }
5472 start=i+1;
5473 }
5474 buf[i] = lockPath[i];
5475 }
drh308c2a52010-05-14 11:30:18 +00005476 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005477 return 0;
5478}
5479
drh715ff302008-12-03 22:32:44 +00005480/*
5481** Create a new VFS file descriptor (stored in memory obtained from
5482** sqlite3_malloc) and open the file named "path" in the file descriptor.
5483**
5484** The caller is responsible not only for closing the file descriptor
5485** but also for freeing the memory associated with the file descriptor.
5486*/
drh7ed97b92010-01-20 13:07:21 +00005487static int proxyCreateUnixFile(
5488 const char *path, /* path for the new unixFile */
5489 unixFile **ppFile, /* unixFile created and returned by ref */
5490 int islockfile /* if non zero missing dirs will be created */
5491) {
5492 int fd = -1;
5493 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005494 unixFile *pNew;
5495 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005496 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005497 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005498 int terrno = 0;
5499 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005500
drh7ed97b92010-01-20 13:07:21 +00005501 /* 1. first try to open/create the file
5502 ** 2. if that fails, and this is a lock file (not-conch), try creating
5503 ** the parent directories and then try again.
5504 ** 3. if that fails, try to open the file read-only
5505 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5506 */
5507 pUnused = findReusableFd(path, openFlags);
5508 if( pUnused ){
5509 fd = pUnused->fd;
5510 }else{
5511 pUnused = sqlite3_malloc(sizeof(*pUnused));
5512 if( !pUnused ){
5513 return SQLITE_NOMEM;
5514 }
5515 }
5516 if( fd<0 ){
drh99ab3b12011-03-02 15:09:07 +00005517 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005518 terrno = errno;
5519 if( fd<0 && errno==ENOENT && islockfile ){
5520 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh99ab3b12011-03-02 15:09:07 +00005521 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005522 }
5523 }
5524 }
5525 if( fd<0 ){
5526 openFlags = O_RDONLY;
drh99ab3b12011-03-02 15:09:07 +00005527 fd = osOpen(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005528 terrno = errno;
5529 }
5530 if( fd<0 ){
5531 if( islockfile ){
5532 return SQLITE_BUSY;
5533 }
5534 switch (terrno) {
5535 case EACCES:
5536 return SQLITE_PERM;
5537 case EIO:
5538 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5539 default:
drh9978c972010-02-23 17:36:32 +00005540 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005541 }
5542 }
5543
5544 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5545 if( pNew==NULL ){
5546 rc = SQLITE_NOMEM;
5547 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005548 }
5549 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005550 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005551 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005552 pUnused->fd = fd;
5553 pUnused->flags = openFlags;
5554 pNew->pUnused = pUnused;
5555
5556 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5557 if( rc==SQLITE_OK ){
5558 *ppFile = pNew;
5559 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005560 }
drh7ed97b92010-01-20 13:07:21 +00005561end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005562 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005563 sqlite3_free(pNew);
5564 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005565 return rc;
5566}
5567
drh7ed97b92010-01-20 13:07:21 +00005568#ifdef SQLITE_TEST
5569/* simulate multiple hosts by creating unique hostid file paths */
5570int sqlite3_hostid_num = 0;
5571#endif
5572
5573#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5574
drh0ab216a2010-07-02 17:10:40 +00005575/* Not always defined in the headers as it ought to be */
5576extern int gethostuuid(uuid_t id, const struct timespec *wait);
5577
drh7ed97b92010-01-20 13:07:21 +00005578/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5579** bytes of writable memory.
5580*/
5581static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005582 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5583 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005584#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5585 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005586 {
5587 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5588 if( gethostuuid(pHostID, &timeout) ){
5589 int err = errno;
5590 if( pError ){
5591 *pError = err;
5592 }
5593 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005594 }
drh7ed97b92010-01-20 13:07:21 +00005595 }
drhe8b0c9b2010-09-25 14:13:17 +00005596#endif
drh7ed97b92010-01-20 13:07:21 +00005597#ifdef SQLITE_TEST
5598 /* simulate multiple hosts by creating unique hostid file paths */
5599 if( sqlite3_hostid_num != 0){
5600 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5601 }
5602#endif
5603
5604 return SQLITE_OK;
5605}
5606
5607/* The conch file contains the header, host id and lock file path
5608 */
5609#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5610#define PROXY_HEADERLEN 1 /* conch file header length */
5611#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5612#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5613
5614/*
5615** Takes an open conch file, copies the contents to a new path and then moves
5616** it back. The newly created file's file descriptor is assigned to the
5617** conch file structure and finally the original conch file descriptor is
5618** closed. Returns zero if successful.
5619*/
5620static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5621 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5622 unixFile *conchFile = pCtx->conchFile;
5623 char tPath[MAXPATHLEN];
5624 char buf[PROXY_MAXCONCHLEN];
5625 char *cPath = pCtx->conchFilePath;
5626 size_t readLen = 0;
5627 size_t pathLen = 0;
5628 char errmsg[64] = "";
5629 int fd = -1;
5630 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005631 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005632
5633 /* create a new path by replace the trailing '-conch' with '-break' */
5634 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5635 if( pathLen>MAXPATHLEN || pathLen<6 ||
5636 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005637 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005638 goto end_breaklock;
5639 }
5640 /* read the conch content */
5641 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5642 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005643 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005644 goto end_breaklock;
5645 }
5646 /* write it out to the temporary break file */
drh99ab3b12011-03-02 15:09:07 +00005647 fd = osOpen(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005648 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005649 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005650 goto end_breaklock;
5651 }
drh0ab216a2010-07-02 17:10:40 +00005652 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005653 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005654 goto end_breaklock;
5655 }
5656 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005657 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005658 goto end_breaklock;
5659 }
5660 rc = 0;
5661 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005662 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005663 conchFile->h = fd;
5664 conchFile->openFlags = O_RDWR | O_CREAT;
5665
5666end_breaklock:
5667 if( rc ){
5668 if( fd>=0 ){
5669 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005670 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005671 }
5672 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5673 }
5674 return rc;
5675}
5676
5677/* Take the requested lock on the conch file and break a stale lock if the
5678** host id matches.
5679*/
5680static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5681 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5682 unixFile *conchFile = pCtx->conchFile;
5683 int rc = SQLITE_OK;
5684 int nTries = 0;
5685 struct timespec conchModTime;
5686
5687 do {
5688 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5689 nTries ++;
5690 if( rc==SQLITE_BUSY ){
5691 /* If the lock failed (busy):
5692 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5693 * 2nd try: fail if the mod time changed or host id is different, wait
5694 * 10 sec and try again
5695 * 3rd try: break the lock unless the mod time has changed.
5696 */
5697 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005698 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005699 pFile->lastErrno = errno;
5700 return SQLITE_IOERR_LOCK;
5701 }
5702
5703 if( nTries==1 ){
5704 conchModTime = buf.st_mtimespec;
5705 usleep(500000); /* wait 0.5 sec and try the lock again*/
5706 continue;
5707 }
5708
5709 assert( nTries>1 );
5710 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5711 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5712 return SQLITE_BUSY;
5713 }
5714
5715 if( nTries==2 ){
5716 char tBuf[PROXY_MAXCONCHLEN];
5717 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5718 if( len<0 ){
5719 pFile->lastErrno = errno;
5720 return SQLITE_IOERR_LOCK;
5721 }
5722 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5723 /* don't break the lock if the host id doesn't match */
5724 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5725 return SQLITE_BUSY;
5726 }
5727 }else{
5728 /* don't break the lock on short read or a version mismatch */
5729 return SQLITE_BUSY;
5730 }
5731 usleep(10000000); /* wait 10 sec and try the lock again */
5732 continue;
5733 }
5734
5735 assert( nTries==3 );
5736 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5737 rc = SQLITE_OK;
5738 if( lockType==EXCLUSIVE_LOCK ){
5739 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5740 }
5741 if( !rc ){
5742 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5743 }
5744 }
5745 }
5746 } while( rc==SQLITE_BUSY && nTries<3 );
5747
5748 return rc;
5749}
5750
5751/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005752** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5753** lockPath means that the lockPath in the conch file will be used if the
5754** host IDs match, or a new lock path will be generated automatically
5755** and written to the conch file.
5756*/
5757static int proxyTakeConch(unixFile *pFile){
5758 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5759
drh7ed97b92010-01-20 13:07:21 +00005760 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005761 return SQLITE_OK;
5762 }else{
5763 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005764 uuid_t myHostID;
5765 int pError = 0;
5766 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005767 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005768 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005769 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005770 int createConch = 0;
5771 int hostIdMatch = 0;
5772 int readLen = 0;
5773 int tryOldLockPath = 0;
5774 int forceNewLockPath = 0;
5775
drh308c2a52010-05-14 11:30:18 +00005776 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5777 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005778
drh7ed97b92010-01-20 13:07:21 +00005779 rc = proxyGetHostID(myHostID, &pError);
5780 if( (rc&0xff)==SQLITE_IOERR ){
5781 pFile->lastErrno = pError;
5782 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005783 }
drh7ed97b92010-01-20 13:07:21 +00005784 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005785 if( rc!=SQLITE_OK ){
5786 goto end_takeconch;
5787 }
drh7ed97b92010-01-20 13:07:21 +00005788 /* read the existing conch file */
5789 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5790 if( readLen<0 ){
5791 /* I/O error: lastErrno set by seekAndRead */
5792 pFile->lastErrno = conchFile->lastErrno;
5793 rc = SQLITE_IOERR_READ;
5794 goto end_takeconch;
5795 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5796 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5797 /* a short read or version format mismatch means we need to create a new
5798 ** conch file.
5799 */
5800 createConch = 1;
5801 }
5802 /* if the host id matches and the lock path already exists in the conch
5803 ** we'll try to use the path there, if we can't open that path, we'll
5804 ** retry with a new auto-generated path
5805 */
5806 do { /* in case we need to try again for an :auto: named lock file */
5807
5808 if( !createConch && !forceNewLockPath ){
5809 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5810 PROXY_HOSTIDLEN);
5811 /* if the conch has data compare the contents */
5812 if( !pCtx->lockProxyPath ){
5813 /* for auto-named local lock file, just check the host ID and we'll
5814 ** use the local lock file path that's already in there
5815 */
5816 if( hostIdMatch ){
5817 size_t pathLen = (readLen - PROXY_PATHINDEX);
5818
5819 if( pathLen>=MAXPATHLEN ){
5820 pathLen=MAXPATHLEN-1;
5821 }
5822 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5823 lockPath[pathLen] = 0;
5824 tempLockPath = lockPath;
5825 tryOldLockPath = 1;
5826 /* create a copy of the lock path if the conch is taken */
5827 goto end_takeconch;
5828 }
5829 }else if( hostIdMatch
5830 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5831 readLen-PROXY_PATHINDEX)
5832 ){
5833 /* conch host and lock path match */
5834 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005835 }
drh7ed97b92010-01-20 13:07:21 +00005836 }
5837
5838 /* if the conch isn't writable and doesn't match, we can't take it */
5839 if( (conchFile->openFlags&O_RDWR) == 0 ){
5840 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005841 goto end_takeconch;
5842 }
drh7ed97b92010-01-20 13:07:21 +00005843
5844 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005845 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005846 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5847 tempLockPath = lockPath;
5848 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005849 }
drh7ed97b92010-01-20 13:07:21 +00005850
5851 /* update conch with host and path (this will fail if other process
5852 ** has a shared lock already), if the host id matches, use the big
5853 ** stick.
drh715ff302008-12-03 22:32:44 +00005854 */
drh7ed97b92010-01-20 13:07:21 +00005855 futimes(conchFile->h, NULL);
5856 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005857 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005858 /* We are trying for an exclusive lock but another thread in this
5859 ** same process is still holding a shared lock. */
5860 rc = SQLITE_BUSY;
5861 } else {
5862 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005863 }
drh715ff302008-12-03 22:32:44 +00005864 }else{
drh7ed97b92010-01-20 13:07:21 +00005865 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005866 }
drh7ed97b92010-01-20 13:07:21 +00005867 if( rc==SQLITE_OK ){
5868 char writeBuffer[PROXY_MAXCONCHLEN];
5869 int writeSize = 0;
5870
5871 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5872 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5873 if( pCtx->lockProxyPath!=NULL ){
5874 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5875 }else{
5876 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5877 }
5878 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00005879 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00005880 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5881 fsync(conchFile->h);
5882 /* If we created a new conch file (not just updated the contents of a
5883 ** valid conch file), try to match the permissions of the database
5884 */
5885 if( rc==SQLITE_OK && createConch ){
5886 struct stat buf;
drhff812312011-02-23 13:33:46 +00005887 int rc;
drh99ab3b12011-03-02 15:09:07 +00005888 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00005889 if( err==0 ){
5890 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5891 S_IROTH|S_IWOTH);
5892 /* try to match the database file R/W permissions, ignore failure */
5893#ifndef SQLITE_PROXY_DEBUG
5894 fchmod(conchFile->h, cmode);
5895#else
drhff812312011-02-23 13:33:46 +00005896 do{
5897 rc = fchmod(conchFile->h, cmode);
5898 }while( rc==(-1) && errno==EINTR );
5899 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00005900 int code = errno;
5901 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5902 cmode, code, strerror(code));
5903 } else {
5904 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5905 }
5906 }else{
5907 int code = errno;
5908 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5909 err, code, strerror(code));
5910#endif
5911 }
drh715ff302008-12-03 22:32:44 +00005912 }
5913 }
drh7ed97b92010-01-20 13:07:21 +00005914 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5915
5916 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005917 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005918 if( rc==SQLITE_OK && pFile->openFlags ){
5919 if( pFile->h>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005920 robust_close(pFile, pFile->h, __LINE__) ){
drh7ed97b92010-01-20 13:07:21 +00005921 }
5922 pFile->h = -1;
drh99ab3b12011-03-02 15:09:07 +00005923 int fd = osOpen(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00005924 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005925 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005926 if( fd>=0 ){
5927 pFile->h = fd;
5928 }else{
drh9978c972010-02-23 17:36:32 +00005929 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005930 during locking */
5931 }
5932 }
5933 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5934 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5935 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5936 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5937 /* we couldn't create the proxy lock file with the old lock file path
5938 ** so try again via auto-naming
5939 */
5940 forceNewLockPath = 1;
5941 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005942 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005943 }
5944 }
5945 if( rc==SQLITE_OK ){
5946 /* Need to make a copy of path if we extracted the value
5947 ** from the conch file or the path was allocated on the stack
5948 */
5949 if( tempLockPath ){
5950 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5951 if( !pCtx->lockProxyPath ){
5952 rc = SQLITE_NOMEM;
5953 }
5954 }
5955 }
5956 if( rc==SQLITE_OK ){
5957 pCtx->conchHeld = 1;
5958
5959 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5960 afpLockingContext *afpCtx;
5961 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5962 afpCtx->dbPath = pCtx->lockProxyPath;
5963 }
5964 } else {
5965 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5966 }
drh308c2a52010-05-14 11:30:18 +00005967 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5968 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005969 return rc;
drh308c2a52010-05-14 11:30:18 +00005970 } while (1); /* in case we need to retry the :auto: lock file -
5971 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005972 }
5973}
5974
5975/*
5976** If pFile holds a lock on a conch file, then release that lock.
5977*/
5978static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005979 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005980 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5981 unixFile *conchFile; /* Name of the conch file */
5982
5983 pCtx = (proxyLockingContext *)pFile->lockingContext;
5984 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005985 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005986 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005987 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005988 if( pCtx->conchHeld>0 ){
5989 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5990 }
drh715ff302008-12-03 22:32:44 +00005991 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005992 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5993 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005994 return rc;
5995}
5996
5997/*
5998** Given the name of a database file, compute the name of its conch file.
5999** Store the conch filename in memory obtained from sqlite3_malloc().
6000** Make *pConchPath point to the new name. Return SQLITE_OK on success
6001** or SQLITE_NOMEM if unable to obtain memory.
6002**
6003** The caller is responsible for ensuring that the allocated memory
6004** space is eventually freed.
6005**
6006** *pConchPath is set to NULL if a memory allocation error occurs.
6007*/
6008static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6009 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006010 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006011 char *conchPath; /* buffer in which to construct conch name */
6012
6013 /* Allocate space for the conch filename and initialize the name to
6014 ** the name of the original database file. */
6015 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6016 if( conchPath==0 ){
6017 return SQLITE_NOMEM;
6018 }
6019 memcpy(conchPath, dbPath, len+1);
6020
6021 /* now insert a "." before the last / character */
6022 for( i=(len-1); i>=0; i-- ){
6023 if( conchPath[i]=='/' ){
6024 i++;
6025 break;
6026 }
6027 }
6028 conchPath[i]='.';
6029 while ( i<len ){
6030 conchPath[i+1]=dbPath[i];
6031 i++;
6032 }
6033
6034 /* append the "-conch" suffix to the file */
6035 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006036 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006037
6038 return SQLITE_OK;
6039}
6040
6041
6042/* Takes a fully configured proxy locking-style unix file and switches
6043** the local lock file path
6044*/
6045static int switchLockProxyPath(unixFile *pFile, const char *path) {
6046 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6047 char *oldPath = pCtx->lockProxyPath;
6048 int rc = SQLITE_OK;
6049
drh308c2a52010-05-14 11:30:18 +00006050 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006051 return SQLITE_BUSY;
6052 }
6053
6054 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6055 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6056 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6057 return SQLITE_OK;
6058 }else{
6059 unixFile *lockProxy = pCtx->lockProxy;
6060 pCtx->lockProxy=NULL;
6061 pCtx->conchHeld = 0;
6062 if( lockProxy!=NULL ){
6063 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6064 if( rc ) return rc;
6065 sqlite3_free(lockProxy);
6066 }
6067 sqlite3_free(oldPath);
6068 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6069 }
6070
6071 return rc;
6072}
6073
6074/*
6075** pFile is a file that has been opened by a prior xOpen call. dbPath
6076** is a string buffer at least MAXPATHLEN+1 characters in size.
6077**
6078** This routine find the filename associated with pFile and writes it
6079** int dbPath.
6080*/
6081static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006082#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006083 if( pFile->pMethod == &afpIoMethods ){
6084 /* afp style keeps a reference to the db path in the filePath field
6085 ** of the struct */
drhea678832008-12-10 19:26:22 +00006086 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006087 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6088 } else
drh715ff302008-12-03 22:32:44 +00006089#endif
6090 if( pFile->pMethod == &dotlockIoMethods ){
6091 /* dot lock style uses the locking context to store the dot lock
6092 ** file path */
6093 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6094 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6095 }else{
6096 /* all other styles use the locking context to store the db file path */
6097 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006098 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006099 }
6100 return SQLITE_OK;
6101}
6102
6103/*
6104** Takes an already filled in unix file and alters it so all file locking
6105** will be performed on the local proxy lock file. The following fields
6106** are preserved in the locking context so that they can be restored and
6107** the unix structure properly cleaned up at close time:
6108** ->lockingContext
6109** ->pMethod
6110*/
6111static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6112 proxyLockingContext *pCtx;
6113 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6114 char *lockPath=NULL;
6115 int rc = SQLITE_OK;
6116
drh308c2a52010-05-14 11:30:18 +00006117 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006118 return SQLITE_BUSY;
6119 }
6120 proxyGetDbPathForUnixFile(pFile, dbPath);
6121 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6122 lockPath=NULL;
6123 }else{
6124 lockPath=(char *)path;
6125 }
6126
drh308c2a52010-05-14 11:30:18 +00006127 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6128 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006129
6130 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6131 if( pCtx==0 ){
6132 return SQLITE_NOMEM;
6133 }
6134 memset(pCtx, 0, sizeof(*pCtx));
6135
6136 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6137 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006138 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6139 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6140 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6141 ** (c) the file system is read-only, then enable no-locking access.
6142 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6143 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6144 */
6145 struct statfs fsInfo;
6146 struct stat conchInfo;
6147 int goLockless = 0;
6148
drh99ab3b12011-03-02 15:09:07 +00006149 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006150 int err = errno;
6151 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6152 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6153 }
6154 }
6155 if( goLockless ){
6156 pCtx->conchHeld = -1; /* read only FS/ lockless */
6157 rc = SQLITE_OK;
6158 }
6159 }
drh715ff302008-12-03 22:32:44 +00006160 }
6161 if( rc==SQLITE_OK && lockPath ){
6162 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6163 }
6164
6165 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006166 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6167 if( pCtx->dbPath==NULL ){
6168 rc = SQLITE_NOMEM;
6169 }
6170 }
6171 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006172 /* all memory is allocated, proxys are created and assigned,
6173 ** switch the locking context and pMethod then return.
6174 */
drh715ff302008-12-03 22:32:44 +00006175 pCtx->oldLockingContext = pFile->lockingContext;
6176 pFile->lockingContext = pCtx;
6177 pCtx->pOldMethod = pFile->pMethod;
6178 pFile->pMethod = &proxyIoMethods;
6179 }else{
6180 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006181 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006182 sqlite3_free(pCtx->conchFile);
6183 }
drhd56b1212010-08-11 06:14:15 +00006184 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006185 sqlite3_free(pCtx->conchFilePath);
6186 sqlite3_free(pCtx);
6187 }
drh308c2a52010-05-14 11:30:18 +00006188 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6189 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006190 return rc;
6191}
6192
6193
6194/*
6195** This routine handles sqlite3_file_control() calls that are specific
6196** to proxy locking.
6197*/
6198static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6199 switch( op ){
6200 case SQLITE_GET_LOCKPROXYFILE: {
6201 unixFile *pFile = (unixFile*)id;
6202 if( pFile->pMethod == &proxyIoMethods ){
6203 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6204 proxyTakeConch(pFile);
6205 if( pCtx->lockProxyPath ){
6206 *(const char **)pArg = pCtx->lockProxyPath;
6207 }else{
6208 *(const char **)pArg = ":auto: (not held)";
6209 }
6210 } else {
6211 *(const char **)pArg = NULL;
6212 }
6213 return SQLITE_OK;
6214 }
6215 case SQLITE_SET_LOCKPROXYFILE: {
6216 unixFile *pFile = (unixFile*)id;
6217 int rc = SQLITE_OK;
6218 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6219 if( pArg==NULL || (const char *)pArg==0 ){
6220 if( isProxyStyle ){
6221 /* turn off proxy locking - not supported */
6222 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6223 }else{
6224 /* turn off proxy locking - already off - NOOP */
6225 rc = SQLITE_OK;
6226 }
6227 }else{
6228 const char *proxyPath = (const char *)pArg;
6229 if( isProxyStyle ){
6230 proxyLockingContext *pCtx =
6231 (proxyLockingContext*)pFile->lockingContext;
6232 if( !strcmp(pArg, ":auto:")
6233 || (pCtx->lockProxyPath &&
6234 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6235 ){
6236 rc = SQLITE_OK;
6237 }else{
6238 rc = switchLockProxyPath(pFile, proxyPath);
6239 }
6240 }else{
6241 /* turn on proxy file locking */
6242 rc = proxyTransformUnixFile(pFile, proxyPath);
6243 }
6244 }
6245 return rc;
6246 }
6247 default: {
6248 assert( 0 ); /* The call assures that only valid opcodes are sent */
6249 }
6250 }
6251 /*NOTREACHED*/
6252 return SQLITE_ERROR;
6253}
6254
6255/*
6256** Within this division (the proxying locking implementation) the procedures
6257** above this point are all utilities. The lock-related methods of the
6258** proxy-locking sqlite3_io_method object follow.
6259*/
6260
6261
6262/*
6263** This routine checks if there is a RESERVED lock held on the specified
6264** file by this or any other process. If such a lock is held, set *pResOut
6265** to a non-zero value otherwise *pResOut is set to zero. The return value
6266** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6267*/
6268static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6269 unixFile *pFile = (unixFile*)id;
6270 int rc = proxyTakeConch(pFile);
6271 if( rc==SQLITE_OK ){
6272 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006273 if( pCtx->conchHeld>0 ){
6274 unixFile *proxy = pCtx->lockProxy;
6275 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6276 }else{ /* conchHeld < 0 is lockless */
6277 pResOut=0;
6278 }
drh715ff302008-12-03 22:32:44 +00006279 }
6280 return rc;
6281}
6282
6283/*
drh308c2a52010-05-14 11:30:18 +00006284** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006285** of the following:
6286**
6287** (1) SHARED_LOCK
6288** (2) RESERVED_LOCK
6289** (3) PENDING_LOCK
6290** (4) EXCLUSIVE_LOCK
6291**
6292** Sometimes when requesting one lock state, additional lock states
6293** are inserted in between. The locking might fail on one of the later
6294** transitions leaving the lock state different from what it started but
6295** still short of its goal. The following chart shows the allowed
6296** transitions and the inserted intermediate states:
6297**
6298** UNLOCKED -> SHARED
6299** SHARED -> RESERVED
6300** SHARED -> (PENDING) -> EXCLUSIVE
6301** RESERVED -> (PENDING) -> EXCLUSIVE
6302** PENDING -> EXCLUSIVE
6303**
6304** This routine will only increase a lock. Use the sqlite3OsUnlock()
6305** routine to lower a locking level.
6306*/
drh308c2a52010-05-14 11:30:18 +00006307static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006308 unixFile *pFile = (unixFile*)id;
6309 int rc = proxyTakeConch(pFile);
6310 if( rc==SQLITE_OK ){
6311 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006312 if( pCtx->conchHeld>0 ){
6313 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006314 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6315 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006316 }else{
6317 /* conchHeld < 0 is lockless */
6318 }
drh715ff302008-12-03 22:32:44 +00006319 }
6320 return rc;
6321}
6322
6323
6324/*
drh308c2a52010-05-14 11:30:18 +00006325** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006326** must be either NO_LOCK or SHARED_LOCK.
6327**
6328** If the locking level of the file descriptor is already at or below
6329** the requested locking level, this routine is a no-op.
6330*/
drh308c2a52010-05-14 11:30:18 +00006331static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006332 unixFile *pFile = (unixFile*)id;
6333 int rc = proxyTakeConch(pFile);
6334 if( rc==SQLITE_OK ){
6335 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006336 if( pCtx->conchHeld>0 ){
6337 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006338 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6339 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006340 }else{
6341 /* conchHeld < 0 is lockless */
6342 }
drh715ff302008-12-03 22:32:44 +00006343 }
6344 return rc;
6345}
6346
6347/*
6348** Close a file that uses proxy locks.
6349*/
6350static int proxyClose(sqlite3_file *id) {
6351 if( id ){
6352 unixFile *pFile = (unixFile*)id;
6353 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6354 unixFile *lockProxy = pCtx->lockProxy;
6355 unixFile *conchFile = pCtx->conchFile;
6356 int rc = SQLITE_OK;
6357
6358 if( lockProxy ){
6359 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6360 if( rc ) return rc;
6361 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6362 if( rc ) return rc;
6363 sqlite3_free(lockProxy);
6364 pCtx->lockProxy = 0;
6365 }
6366 if( conchFile ){
6367 if( pCtx->conchHeld ){
6368 rc = proxyReleaseConch(pFile);
6369 if( rc ) return rc;
6370 }
6371 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6372 if( rc ) return rc;
6373 sqlite3_free(conchFile);
6374 }
drhd56b1212010-08-11 06:14:15 +00006375 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006376 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006377 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006378 /* restore the original locking context and pMethod then close it */
6379 pFile->lockingContext = pCtx->oldLockingContext;
6380 pFile->pMethod = pCtx->pOldMethod;
6381 sqlite3_free(pCtx);
6382 return pFile->pMethod->xClose(id);
6383 }
6384 return SQLITE_OK;
6385}
6386
6387
6388
drhd2cb50b2009-01-09 21:41:17 +00006389#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006390/*
6391** The proxy locking style is intended for use with AFP filesystems.
6392** And since AFP is only supported on MacOSX, the proxy locking is also
6393** restricted to MacOSX.
6394**
6395**
6396******************* End of the proxy lock implementation **********************
6397******************************************************************************/
6398
drh734c9862008-11-28 15:37:20 +00006399/*
danielk1977e339d652008-06-28 11:23:00 +00006400** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006401**
6402** This routine registers all VFS implementations for unix-like operating
6403** systems. This routine, and the sqlite3_os_end() routine that follows,
6404** should be the only routines in this file that are visible from other
6405** files.
drh6b9d6dd2008-12-03 19:34:47 +00006406**
6407** This routine is called once during SQLite initialization and by a
6408** single thread. The memory allocation and mutex subsystems have not
6409** necessarily been initialized when this routine is called, and so they
6410** should not be used.
drh153c62c2007-08-24 03:51:33 +00006411*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006412int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006413 /*
6414 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006415 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6416 ** to the "finder" function. (pAppData is a pointer to a pointer because
6417 ** silly C90 rules prohibit a void* from being cast to a function pointer
6418 ** and so we have to go through the intermediate pointer to avoid problems
6419 ** when compiling with -pedantic-errors on GCC.)
6420 **
6421 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006422 ** finder-function. The finder-function returns a pointer to the
6423 ** sqlite_io_methods object that implements the desired locking
6424 ** behaviors. See the division above that contains the IOMETHODS
6425 ** macro for addition information on finder-functions.
6426 **
6427 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6428 ** object. But the "autolockIoFinder" available on MacOSX does a little
6429 ** more than that; it looks at the filesystem type that hosts the
6430 ** database file and tries to choose an locking method appropriate for
6431 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006432 */
drh7708e972008-11-29 00:56:52 +00006433 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006434 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006435 sizeof(unixFile), /* szOsFile */ \
6436 MAX_PATHNAME, /* mxPathname */ \
6437 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006438 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006439 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006440 unixOpen, /* xOpen */ \
6441 unixDelete, /* xDelete */ \
6442 unixAccess, /* xAccess */ \
6443 unixFullPathname, /* xFullPathname */ \
6444 unixDlOpen, /* xDlOpen */ \
6445 unixDlError, /* xDlError */ \
6446 unixDlSym, /* xDlSym */ \
6447 unixDlClose, /* xDlClose */ \
6448 unixRandomness, /* xRandomness */ \
6449 unixSleep, /* xSleep */ \
6450 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006451 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006452 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006453 unixSetSystemCall, /* xSetSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006454 }
6455
drh6b9d6dd2008-12-03 19:34:47 +00006456 /*
6457 ** All default VFSes for unix are contained in the following array.
6458 **
6459 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6460 ** by the SQLite core when the VFS is registered. So the following
6461 ** array cannot be const.
6462 */
danielk1977e339d652008-06-28 11:23:00 +00006463 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006464#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006465 UNIXVFS("unix", autolockIoFinder ),
6466#else
6467 UNIXVFS("unix", posixIoFinder ),
6468#endif
6469 UNIXVFS("unix-none", nolockIoFinder ),
6470 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006471#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006472 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006473#endif
6474#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006475 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006476#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006477 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006478#endif
chw78a13182009-04-07 05:35:03 +00006479#endif
drhd2cb50b2009-01-09 21:41:17 +00006480#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006481 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006482 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006483 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006484#endif
drh153c62c2007-08-24 03:51:33 +00006485 };
drh6b9d6dd2008-12-03 19:34:47 +00006486 unsigned int i; /* Loop counter */
6487
6488 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006489 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006490 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006491 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006492 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006493}
danielk1977e339d652008-06-28 11:23:00 +00006494
6495/*
drh6b9d6dd2008-12-03 19:34:47 +00006496** Shutdown the operating system interface.
6497**
6498** Some operating systems might need to do some cleanup in this routine,
6499** to release dynamically allocated objects. But not on unix.
6500** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006501*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006502int sqlite3_os_end(void){
6503 return SQLITE_OK;
6504}
drhdce8bdb2007-08-16 13:01:44 +00006505
danielk197729bafea2008-06-26 10:41:19 +00006506#endif /* SQLITE_OS_UNIX */