blob: 8c10d1ed33f1885c6a52672ba9b2fb3ecdfdc54a [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>
drhf2424c52010-04-26 00:04:55 +0000122#include <sys/mman.h>
danielk1977e339d652008-06-28 11:23:00 +0000123
drh40bbb0a2008-09-23 10:23:26 +0000124#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000125# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000126# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <semaphore.h>
128# include <limits.h>
129# else
drh9b35ea62008-11-29 02:20:26 +0000130# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000131# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
drhf8b4d8c2010-03-05 13:53:22 +0000135#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000136# include <sys/mount.h>
137#endif
138
drh9cbe6352005-11-29 03:13:21 +0000139/*
drh7ed97b92010-01-20 13:07:21 +0000140** Allowed values of unixFile.fsFlags
141*/
142#define SQLITE_FSFLAGS_IS_MSDOS 0x1
143
144/*
drhf1a221e2006-01-15 17:27:17 +0000145** If we are to be thread-safe, include the pthreads header and define
146** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000147*/
drhd677b3d2007-08-20 22:48:41 +0000148#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000149# include <pthread.h>
150# define SQLITE_UNIX_THREADS 1
151#endif
152
153/*
154** Default permissions when creating a new file
155*/
156#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
157# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
158#endif
159
danielk1977b4b47412007-08-17 15:53:36 +0000160/*
aswiftaebf4132008-11-21 00:10:35 +0000161 ** Default permissions when creating auto proxy dir
162 */
163#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
164# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
165#endif
166
167/*
danielk1977b4b47412007-08-17 15:53:36 +0000168** Maximum supported path-length.
169*/
170#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000171
drh734c9862008-11-28 15:37:20 +0000172/*
drh734c9862008-11-28 15:37:20 +0000173** Only set the lastErrno if the error code is a real error and not
174** a normal expected return code of SQLITE_BUSY or SQLITE_OK
175*/
176#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
177
drh9cbe6352005-11-29 03:13:21 +0000178
179/*
dane946c392009-08-22 11:39:46 +0000180** Sometimes, after a file handle is closed by SQLite, the file descriptor
181** cannot be closed immediately. In these cases, instances of the following
182** structure are used to store the file descriptor while waiting for an
183** opportunity to either close or reuse it.
184*/
185typedef struct UnixUnusedFd UnixUnusedFd;
186struct UnixUnusedFd {
187 int fd; /* File descriptor to close */
188 int flags; /* Flags this file descriptor was opened with */
189 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
190};
191
192/*
drh9b35ea62008-11-29 02:20:26 +0000193** The unixFile structure is subclass of sqlite3_file specific to the unix
194** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000195*/
drh054889e2005-11-30 03:20:31 +0000196typedef struct unixFile unixFile;
197struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000198 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000199 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
200 struct unixLockInfo *pLock; /* Info about locks on this inode */
201 int h; /* The file descriptor */
202 int dirfd; /* File descriptor for the directory */
203 unsigned char locktype; /* The type of lock held on this fd */
204 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000205 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000206 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000207 int fileFlags; /* Miscellanous flags */
drh08c6d442009-02-09 17:34:07 +0000208#if SQLITE_ENABLE_LOCKING_STYLE
209 int openFlags; /* The flags specified at open() */
210#endif
drh7ed97b92010-01-20 13:07:21 +0000211#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
212 unsigned fsFlags; /* cached details from statfs() */
213#endif
drh734c9862008-11-28 15:37:20 +0000214#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000215 pthread_t tid; /* The thread that "owns" this unixFile */
216#endif
217#if OS_VXWORKS
218 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000219 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000220#endif
drh8f941bc2009-01-14 23:03:40 +0000221#ifndef NDEBUG
222 /* The next group of variables are used to track whether or not the
223 ** transaction counter in bytes 24-27 of database files are updated
224 ** whenever any part of the database changes. An assertion fault will
225 ** occur if a file is updated without also updating the transaction
226 ** counter. This test is made to avoid new problems similar to the
227 ** one described by ticket #3584.
228 */
229 unsigned char transCntrChng; /* True if the transaction counter changed */
230 unsigned char dbUpdate; /* True if any part of database file changed */
231 unsigned char inNormalWrite; /* True if in a normal write operation */
232#endif
danielk1977967a4a12007-08-20 14:23:44 +0000233#ifdef SQLITE_TEST
234 /* In test mode, increase the size of this structure a bit so that
235 ** it is larger than the struct CrashFile defined in test6.c.
236 */
237 char aPadding[32];
238#endif
drh9cbe6352005-11-29 03:13:21 +0000239};
240
drh0ccebe72005-06-07 22:22:50 +0000241/*
drh0c2694b2009-09-03 16:23:44 +0000242** The following macros define bits in unixFile.fileFlags
243*/
244#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
245
246/*
drh198bf392006-01-06 21:52:49 +0000247** Include code that is common to all os_*.c files
248*/
249#include "os_common.h"
250
251/*
drh0ccebe72005-06-07 22:22:50 +0000252** Define various macros that are missing from some systems.
253*/
drhbbd42a62004-05-22 17:41:58 +0000254#ifndef O_LARGEFILE
255# define O_LARGEFILE 0
256#endif
257#ifdef SQLITE_DISABLE_LFS
258# undef O_LARGEFILE
259# define O_LARGEFILE 0
260#endif
261#ifndef O_NOFOLLOW
262# define O_NOFOLLOW 0
263#endif
264#ifndef O_BINARY
265# define O_BINARY 0
266#endif
267
268/*
269** The DJGPP compiler environment looks mostly like Unix, but it
270** lacks the fcntl() system call. So redefine fcntl() to be something
271** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000272** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000273*/
274#ifdef __DJGPP__
275# define fcntl(A,B,C) 0
276#endif
277
278/*
drh2b4b5962005-06-15 17:47:55 +0000279** The threadid macro resolves to the thread-id or to 0. Used for
280** testing and debugging only.
281*/
drhd677b3d2007-08-20 22:48:41 +0000282#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000283#define threadid pthread_self()
284#else
285#define threadid 0
286#endif
287
danielk197713adf8a2004-06-03 16:08:41 +0000288
drh107886a2008-11-21 22:21:50 +0000289/*
dan9359c7b2009-08-21 08:29:10 +0000290** Helper functions to obtain and relinquish the global mutex. The
291** global mutex is used to protect the unixOpenCnt, unixLockInfo and
292** vxworksFileId objects used by this file, all of which may be
293** shared by multiple threads.
294**
295** Function unixMutexHeld() is used to assert() that the global mutex
296** is held when required. This function is only used as part of assert()
297** statements. e.g.
298**
299** unixEnterMutex()
300** assert( unixMutexHeld() );
301** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000302*/
303static void unixEnterMutex(void){
304 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
305}
306static void unixLeaveMutex(void){
307 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
308}
dan9359c7b2009-08-21 08:29:10 +0000309#ifdef SQLITE_DEBUG
310static int unixMutexHeld(void) {
311 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
312}
313#endif
drh107886a2008-11-21 22:21:50 +0000314
drh734c9862008-11-28 15:37:20 +0000315
316#ifdef SQLITE_DEBUG
317/*
318** Helper function for printing out trace information from debugging
319** binaries. This returns the string represetation of the supplied
320** integer lock-type.
321*/
322static const char *locktypeName(int locktype){
323 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000324 case NO_LOCK: return "NONE";
325 case SHARED_LOCK: return "SHARED";
326 case RESERVED_LOCK: return "RESERVED";
327 case PENDING_LOCK: return "PENDING";
328 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000329 }
330 return "ERROR";
331}
332#endif
333
334#ifdef SQLITE_LOCK_TRACE
335/*
336** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000337**
drh734c9862008-11-28 15:37:20 +0000338** This routine is used for troubleshooting locks on multithreaded
339** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
340** command-line option on the compiler. This code is normally
341** turned off.
342*/
343static int lockTrace(int fd, int op, struct flock *p){
344 char *zOpName, *zType;
345 int s;
346 int savedErrno;
347 if( op==F_GETLK ){
348 zOpName = "GETLK";
349 }else if( op==F_SETLK ){
350 zOpName = "SETLK";
351 }else{
352 s = fcntl(fd, op, p);
353 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
354 return s;
355 }
356 if( p->l_type==F_RDLCK ){
357 zType = "RDLCK";
358 }else if( p->l_type==F_WRLCK ){
359 zType = "WRLCK";
360 }else if( p->l_type==F_UNLCK ){
361 zType = "UNLCK";
362 }else{
363 assert( 0 );
364 }
365 assert( p->l_whence==SEEK_SET );
366 s = fcntl(fd, op, p);
367 savedErrno = errno;
368 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
369 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
370 (int)p->l_pid, s);
371 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
372 struct flock l2;
373 l2 = *p;
374 fcntl(fd, F_GETLK, &l2);
375 if( l2.l_type==F_RDLCK ){
376 zType = "RDLCK";
377 }else if( l2.l_type==F_WRLCK ){
378 zType = "WRLCK";
379 }else if( l2.l_type==F_UNLCK ){
380 zType = "UNLCK";
381 }else{
382 assert( 0 );
383 }
384 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
385 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
386 }
387 errno = savedErrno;
388 return s;
389}
390#define fcntl lockTrace
391#endif /* SQLITE_LOCK_TRACE */
392
393
394
395/*
396** This routine translates a standard POSIX errno code into something
397** useful to the clients of the sqlite3 functions. Specifically, it is
398** intended to translate a variety of "try again" errors into SQLITE_BUSY
399** and a variety of "please close the file descriptor NOW" errors into
400** SQLITE_IOERR
401**
402** Errors during initialization of locks, or file system support for locks,
403** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
404*/
405static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
406 switch (posixError) {
407 case 0:
408 return SQLITE_OK;
409
410 case EAGAIN:
411 case ETIMEDOUT:
412 case EBUSY:
413 case EINTR:
414 case ENOLCK:
415 /* random NFS retry error, unless during file system support
416 * introspection, in which it actually means what it says */
417 return SQLITE_BUSY;
418
419 case EACCES:
420 /* EACCES is like EAGAIN during locking operations, but not any other time*/
421 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
422 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
423 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
424 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
425 return SQLITE_BUSY;
426 }
427 /* else fall through */
428 case EPERM:
429 return SQLITE_PERM;
430
431 case EDEADLK:
432 return SQLITE_IOERR_BLOCKED;
433
434#if EOPNOTSUPP!=ENOTSUP
435 case EOPNOTSUPP:
436 /* something went terribly awry, unless during file system support
437 * introspection, in which it actually means what it says */
438#endif
439#ifdef ENOTSUP
440 case ENOTSUP:
441 /* invalid fd, unless during file system support introspection, in which
442 * it actually means what it says */
443#endif
444 case EIO:
445 case EBADF:
446 case EINVAL:
447 case ENOTCONN:
448 case ENODEV:
449 case ENXIO:
450 case ENOENT:
451 case ESTALE:
452 case ENOSYS:
453 /* these should force the client to close the file and reconnect */
454
455 default:
456 return sqliteIOErr;
457 }
458}
459
460
461
462/******************************************************************************
463****************** Begin Unique File ID Utility Used By VxWorks ***************
464**
465** On most versions of unix, we can get a unique ID for a file by concatenating
466** the device number and the inode number. But this does not work on VxWorks.
467** On VxWorks, a unique file id must be based on the canonical filename.
468**
469** A pointer to an instance of the following structure can be used as a
470** unique file ID in VxWorks. Each instance of this structure contains
471** a copy of the canonical filename. There is also a reference count.
472** The structure is reclaimed when the number of pointers to it drops to
473** zero.
474**
475** There are never very many files open at one time and lookups are not
476** a performance-critical path, so it is sufficient to put these
477** structures on a linked list.
478*/
479struct vxworksFileId {
480 struct vxworksFileId *pNext; /* Next in a list of them all */
481 int nRef; /* Number of references to this one */
482 int nName; /* Length of the zCanonicalName[] string */
483 char *zCanonicalName; /* Canonical filename */
484};
485
486#if OS_VXWORKS
487/*
drh9b35ea62008-11-29 02:20:26 +0000488** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000489** variable:
490*/
491static struct vxworksFileId *vxworksFileList = 0;
492
493/*
494** Simplify a filename into its canonical form
495** by making the following changes:
496**
497** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000498** * convert /./ into just /
499** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000500**
501** Changes are made in-place. Return the new name length.
502**
503** The original filename is in z[0..n-1]. Return the number of
504** characters in the simplified name.
505*/
506static int vxworksSimplifyName(char *z, int n){
507 int i, j;
508 while( n>1 && z[n-1]=='/' ){ n--; }
509 for(i=j=0; i<n; i++){
510 if( z[i]=='/' ){
511 if( z[i+1]=='/' ) continue;
512 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
513 i += 1;
514 continue;
515 }
516 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
517 while( j>0 && z[j-1]!='/' ){ j--; }
518 if( j>0 ){ j--; }
519 i += 2;
520 continue;
521 }
522 }
523 z[j++] = z[i];
524 }
525 z[j] = 0;
526 return j;
527}
528
529/*
530** Find a unique file ID for the given absolute pathname. Return
531** a pointer to the vxworksFileId object. This pointer is the unique
532** file ID.
533**
534** The nRef field of the vxworksFileId object is incremented before
535** the object is returned. A new vxworksFileId object is created
536** and added to the global list if necessary.
537**
538** If a memory allocation error occurs, return NULL.
539*/
540static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
541 struct vxworksFileId *pNew; /* search key and new file ID */
542 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
543 int n; /* Length of zAbsoluteName string */
544
545 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000546 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000547 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
548 if( pNew==0 ) return 0;
549 pNew->zCanonicalName = (char*)&pNew[1];
550 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
551 n = vxworksSimplifyName(pNew->zCanonicalName, n);
552
553 /* Search for an existing entry that matching the canonical name.
554 ** If found, increment the reference count and return a pointer to
555 ** the existing file ID.
556 */
557 unixEnterMutex();
558 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
559 if( pCandidate->nName==n
560 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
561 ){
562 sqlite3_free(pNew);
563 pCandidate->nRef++;
564 unixLeaveMutex();
565 return pCandidate;
566 }
567 }
568
569 /* No match was found. We will make a new file ID */
570 pNew->nRef = 1;
571 pNew->nName = n;
572 pNew->pNext = vxworksFileList;
573 vxworksFileList = pNew;
574 unixLeaveMutex();
575 return pNew;
576}
577
578/*
579** Decrement the reference count on a vxworksFileId object. Free
580** the object when the reference count reaches zero.
581*/
582static void vxworksReleaseFileId(struct vxworksFileId *pId){
583 unixEnterMutex();
584 assert( pId->nRef>0 );
585 pId->nRef--;
586 if( pId->nRef==0 ){
587 struct vxworksFileId **pp;
588 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
589 assert( *pp==pId );
590 *pp = pId->pNext;
591 sqlite3_free(pId);
592 }
593 unixLeaveMutex();
594}
595#endif /* OS_VXWORKS */
596/*************** End of Unique File ID Utility Used By VxWorks ****************
597******************************************************************************/
598
599
600/******************************************************************************
601*************************** Posix Advisory Locking ****************************
602**
drh9b35ea62008-11-29 02:20:26 +0000603** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000604** section 6.5.2.2 lines 483 through 490 specify that when a process
605** sets or clears a lock, that operation overrides any prior locks set
606** by the same process. It does not explicitly say so, but this implies
607** that it overrides locks set by the same process using a different
608** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000609**
610** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000611** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
612**
613** Suppose ./file1 and ./file2 are really the same file (because
614** one is a hard or symbolic link to the other) then if you set
615** an exclusive lock on fd1, then try to get an exclusive lock
616** on fd2, it works. I would have expected the second lock to
617** fail since there was already a lock on the file due to fd1.
618** But not so. Since both locks came from the same process, the
619** second overrides the first, even though they were on different
620** file descriptors opened on different file names.
621**
drh734c9862008-11-28 15:37:20 +0000622** This means that we cannot use POSIX locks to synchronize file access
623** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000624** to synchronize access for threads in separate processes, but not
625** threads within the same process.
626**
627** To work around the problem, SQLite has to manage file locks internally
628** on its own. Whenever a new database is opened, we have to find the
629** specific inode of the database file (the inode is determined by the
630** st_dev and st_ino fields of the stat structure that fstat() fills in)
631** and check for locks already existing on that inode. When locks are
632** created or removed, we have to look at our own internal record of the
633** locks to see if another thread has previously set a lock on that same
634** inode.
635**
drh9b35ea62008-11-29 02:20:26 +0000636** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
637** For VxWorks, we have to use the alternative unique ID system based on
638** canonical filename and implemented in the previous division.)
639**
danielk1977ad94b582007-08-20 06:44:22 +0000640** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000641** descriptor. It is now a structure that holds the integer file
642** descriptor and a pointer to a structure that describes the internal
643** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000644** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000645** point to the same locking structure. The locking structure keeps
646** a reference count (so we will know when to delete it) and a "cnt"
647** field that tells us its internal lock status. cnt==0 means the
648** file is unlocked. cnt==-1 means the file has an exclusive lock.
649** cnt>0 means there are cnt shared locks on the file.
650**
651** Any attempt to lock or unlock a file first checks the locking
652** structure. The fcntl() system call is only invoked to set a
653** POSIX lock if the internal lock structure transitions between
654** a locked and an unlocked state.
655**
drh734c9862008-11-28 15:37:20 +0000656** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000657**
658** If you close a file descriptor that points to a file that has locks,
659** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000660** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000661** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000662** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000663** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000664** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000665** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000666** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000667** be closed and that list is walked (and cleared) when the last lock
668** clears.
669**
drh9b35ea62008-11-29 02:20:26 +0000670** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000671**
drh9b35ea62008-11-29 02:20:26 +0000672** Many older versions of linux use the LinuxThreads library which is
673** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000674** A cannot be modified or overridden by a different thread B.
675** Only thread A can modify the lock. Locking behavior is correct
676** if the appliation uses the newer Native Posix Thread Library (NPTL)
677** on linux - with NPTL a lock created by thread A can override locks
678** in thread B. But there is no way to know at compile-time which
679** threading library is being used. So there is no way to know at
680** compile-time whether or not thread A can override locks on thread B.
681** We have to do a run-time check to discover the behavior of the
682** current process.
drh5fdae772004-06-29 03:29:00 +0000683**
drh734c9862008-11-28 15:37:20 +0000684** On systems where thread A is unable to modify locks created by
685** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000686** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000687** structure to record this information. And on those systems it
688** is illegal to begin a transaction in one thread and finish it
689** in another. For this latter restriction, there is no work-around.
690** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000691*/
692
693/*
drh6c7d5c52008-11-21 20:32:33 +0000694** Set or check the unixFile.tid field. This field is set when an unixFile
695** is first opened. All subsequent uses of the unixFile verify that the
696** same thread is operating on the unixFile. Some operating systems do
697** not allow locks to be overridden by other threads and that restriction
698** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000699** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000700**
701** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
702** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000703** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000704** or if no locks are held. But the unixFile.pLock field needs to be
705** recomputed because its key includes the thread-id. See the
706** transferOwnership() function below for additional information
707*/
drh734c9862008-11-28 15:37:20 +0000708#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000709# define SET_THREADID(X) (X)->tid = pthread_self()
710# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
711 !pthread_equal((X)->tid, pthread_self()))
712#else
713# define SET_THREADID(X)
714# define CHECK_THREADID(X) 0
715#endif
716
717/*
drhbbd42a62004-05-22 17:41:58 +0000718** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000719** to locate a particular unixOpenCnt structure given its inode. This
720** is the same as the unixLockKey except that the thread ID is omitted.
721*/
722struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000723 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000724#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000725 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000726#else
drh107886a2008-11-21 22:21:50 +0000727 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000728#endif
729};
730
731/*
732** An instance of the following structure serves as the key used
733** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000734**
drh734c9862008-11-28 15:37:20 +0000735** If threads cannot override each others locks (LinuxThreads), then we
736** set the unixLockKey.tid field to the thread ID. If threads can override
737** each others locks (Posix and NPTL) then tid is always set to zero.
738** tid is omitted if we compile without threading support or on an OS
739** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000740*/
drh6c7d5c52008-11-21 20:32:33 +0000741struct unixLockKey {
742 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000743#if SQLITE_THREADSAFE && defined(__linux__)
744 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000745#endif
drhbbd42a62004-05-22 17:41:58 +0000746};
747
748/*
749** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000750** inode. Or, on LinuxThreads, there is one of these structures for
751** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000752**
danielk1977ad94b582007-08-20 06:44:22 +0000753** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000754** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000755** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000756*/
drh6c7d5c52008-11-21 20:32:33 +0000757struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000758 struct unixLockKey lockKey; /* The lookup key */
759 int cnt; /* Number of SHARED locks held */
760 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
761 int nRef; /* Number of pointers to this structure */
drh7ed97b92010-01-20 13:07:21 +0000762#if defined(SQLITE_ENABLE_LOCKING_STYLE)
763 unsigned long long sharedByte; /* for AFP simulated shared lock */
764#endif
drh734c9862008-11-28 15:37:20 +0000765 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
766 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000767};
768
769/*
770** An instance of the following structure is allocated for each open
771** inode. This structure keeps track of the number of locks on that
772** inode. If a close is attempted against an inode that is holding
773** locks, the close is deferred until all locks clear by adding the
774** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000775**
776** TODO: Consider changing this so that there is only a single file
777** descriptor for each open file, even when it is opened multiple times.
778** The close() system call would only occur when the last database
779** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000780*/
drh6c7d5c52008-11-21 20:32:33 +0000781struct unixOpenCnt {
782 struct unixFileId fileId; /* The lookup key */
783 int nRef; /* Number of pointers to this structure */
784 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000785 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000786#if OS_VXWORKS
787 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000788 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000789#endif
drh6c7d5c52008-11-21 20:32:33 +0000790 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000791};
792
drhda0e7682008-07-30 15:27:54 +0000793/*
drh9b35ea62008-11-29 02:20:26 +0000794** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
795** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000796** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000797** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000798*/
drh6c7d5c52008-11-21 20:32:33 +0000799static struct unixLockInfo *lockList = 0;
800static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000801
drh5fdae772004-06-29 03:29:00 +0000802/*
drh9b35ea62008-11-29 02:20:26 +0000803** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000804** locks.
805**
drh9b35ea62008-11-29 02:20:26 +0000806** 0: No. Threads cannot override each others locks. (LinuxThreads)
807** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000808** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000809**
drh5062d3a2006-01-31 23:03:35 +0000810** On some systems, we know at compile-time if threads can override each
811** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
812** will be set appropriately. On other systems, we have to check at
813** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
814** undefined.
815**
drhf1a221e2006-01-15 17:27:17 +0000816** This variable normally has file scope only. But during testing, we make
817** it a global so that the test code can change its value in order to verify
818** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000819*/
drh715ff302008-12-03 22:32:44 +0000820#if SQLITE_THREADSAFE && defined(__linux__)
821# ifndef SQLITE_THREAD_OVERRIDE_LOCK
822# define SQLITE_THREAD_OVERRIDE_LOCK -1
823# endif
824# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000825int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000826# else
drh5062d3a2006-01-31 23:03:35 +0000827static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000828# endif
drh029b44b2006-01-15 00:13:15 +0000829#endif
drh5fdae772004-06-29 03:29:00 +0000830
831/*
832** This structure holds information passed into individual test
833** threads by the testThreadLockingBehavior() routine.
834*/
835struct threadTestData {
836 int fd; /* File to be locked */
837 struct flock lock; /* The locking operation */
838 int result; /* Result of the locking operation */
839};
840
drh6c7d5c52008-11-21 20:32:33 +0000841#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000842/*
danielk197741a6a612008-11-11 18:34:35 +0000843** This function is used as the main routine for a thread launched by
844** testThreadLockingBehavior(). It tests whether the shared-lock obtained
845** by the main thread in testThreadLockingBehavior() conflicts with a
846** hypothetical write-lock obtained by this thread on the same file.
847**
848** The write-lock is not actually acquired, as this is not possible if
849** the file is open in read-only mode (see ticket #3472).
850*/
drh5fdae772004-06-29 03:29:00 +0000851static void *threadLockingTest(void *pArg){
852 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000853 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000854 return pArg;
855}
drh6c7d5c52008-11-21 20:32:33 +0000856#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000857
drh6c7d5c52008-11-21 20:32:33 +0000858
859#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000860/*
861** This procedure attempts to determine whether or not threads
862** can override each others locks then sets the
863** threadsOverrideEachOthersLocks variable appropriately.
864*/
danielk19774d5238f2006-01-27 06:32:00 +0000865static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000866 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000867 int rc;
868 struct threadTestData d;
869 struct flock l;
870 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000871
872 fd = dup(fd_orig);
873 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000874 memset(&l, 0, sizeof(l));
875 l.l_type = F_RDLCK;
876 l.l_len = 1;
877 l.l_start = 0;
878 l.l_whence = SEEK_SET;
879 rc = fcntl(fd_orig, F_SETLK, &l);
880 if( rc!=0 ) return;
881 memset(&d, 0, sizeof(d));
882 d.fd = fd;
883 d.lock = l;
884 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000885 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
886 pthread_join(t, 0);
887 }
drh5fdae772004-06-29 03:29:00 +0000888 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000889 if( d.result!=0 ) return;
890 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000891}
drh06150f92009-07-03 12:57:58 +0000892#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000893
drhbbd42a62004-05-22 17:41:58 +0000894/*
drh6c7d5c52008-11-21 20:32:33 +0000895** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000896**
897** The mutex entered using the unixEnterMutex() function must be held
898** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000899*/
900static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000901 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000902 if( pLock ){
903 pLock->nRef--;
904 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000905 if( pLock->pPrev ){
906 assert( pLock->pPrev->pNext==pLock );
907 pLock->pPrev->pNext = pLock->pNext;
908 }else{
909 assert( lockList==pLock );
910 lockList = pLock->pNext;
911 }
912 if( pLock->pNext ){
913 assert( pLock->pNext->pPrev==pLock );
914 pLock->pNext->pPrev = pLock->pPrev;
915 }
danielk1977e339d652008-06-28 11:23:00 +0000916 sqlite3_free(pLock);
917 }
drhbbd42a62004-05-22 17:41:58 +0000918 }
919}
920
921/*
drh6c7d5c52008-11-21 20:32:33 +0000922** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000923**
924** The mutex entered using the unixEnterMutex() function must be held
925** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000926*/
drh6c7d5c52008-11-21 20:32:33 +0000927static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000928 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000929 if( pOpen ){
930 pOpen->nRef--;
931 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000932 if( pOpen->pPrev ){
933 assert( pOpen->pPrev->pNext==pOpen );
934 pOpen->pPrev->pNext = pOpen->pNext;
935 }else{
936 assert( openList==pOpen );
937 openList = pOpen->pNext;
938 }
939 if( pOpen->pNext ){
940 assert( pOpen->pNext->pPrev==pOpen );
941 pOpen->pNext->pPrev = pOpen->pPrev;
942 }
drh08da4bb2009-09-10 19:20:03 +0000943#if SQLITE_THREADSAFE && defined(__linux__)
dan11b38792009-09-09 18:46:52 +0000944 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
drh08da4bb2009-09-10 19:20:03 +0000945#endif
dan11b38792009-09-09 18:46:52 +0000946
947 /* If pOpen->pUnused is not null, then memory and file-descriptors
948 ** are leaked.
949 **
950 ** This will only happen if, under Linuxthreads, the user has opened
951 ** a transaction in one thread, then attempts to close the database
952 ** handle from another thread (without first unlocking the db file).
953 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000954 sqlite3_free(pOpen);
955 }
drhbbd42a62004-05-22 17:41:58 +0000956 }
957}
958
drh6c7d5c52008-11-21 20:32:33 +0000959/*
960** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
961** describes that file descriptor. Create new ones if necessary. The
962** return values might be uninitialized if an error occurs.
963**
dan9359c7b2009-08-21 08:29:10 +0000964** The mutex entered using the unixEnterMutex() function must be held
965** when this function is called.
966**
drh6c7d5c52008-11-21 20:32:33 +0000967** Return an appropriate error code.
968*/
969static int findLockInfo(
970 unixFile *pFile, /* Unix file with file desc used in the key */
971 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
972 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
973){
974 int rc; /* System call return code */
975 int fd; /* The file descriptor for pFile */
976 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
977 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
978 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000979 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000980 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
981
dan9359c7b2009-08-21 08:29:10 +0000982 assert( unixMutexHeld() );
983
drh6c7d5c52008-11-21 20:32:33 +0000984 /* Get low-level information about the file that we can used to
985 ** create a unique name for the file.
986 */
987 fd = pFile->h;
988 rc = fstat(fd, &statbuf);
989 if( rc!=0 ){
990 pFile->lastErrno = errno;
991#ifdef EOVERFLOW
992 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
993#endif
994 return SQLITE_IOERR;
995 }
996
drheb0d74f2009-02-03 15:27:02 +0000997#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000998 /* On OS X on an msdos filesystem, the inode number is reported
999 ** incorrectly for zero-size files. See ticket #3260. To work
1000 ** around this problem (we consider it a bug in OS X, not SQLite)
1001 ** we always increase the file size to 1 by writing a single byte
1002 ** prior to accessing the inode number. The one byte written is
1003 ** an ASCII 'S' character which also happens to be the first byte
1004 ** in the header of every SQLite database. In this way, if there
1005 ** is a race condition such that another thread has already populated
1006 ** the first page of the database, no damage is done.
1007 */
drh7ed97b92010-01-20 13:07:21 +00001008 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +00001009 rc = write(fd, "S", 1);
1010 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001011 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001012 return SQLITE_IOERR;
1013 }
drh6c7d5c52008-11-21 20:32:33 +00001014 rc = fstat(fd, &statbuf);
1015 if( rc!=0 ){
1016 pFile->lastErrno = errno;
1017 return SQLITE_IOERR;
1018 }
1019 }
drheb0d74f2009-02-03 15:27:02 +00001020#endif
drh6c7d5c52008-11-21 20:32:33 +00001021
1022 memset(&lockKey, 0, sizeof(lockKey));
1023 lockKey.fid.dev = statbuf.st_dev;
1024#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001025 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001026#else
1027 lockKey.fid.ino = statbuf.st_ino;
1028#endif
drh734c9862008-11-28 15:37:20 +00001029#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001030 if( threadsOverrideEachOthersLocks<0 ){
1031 testThreadLockingBehavior(fd);
1032 }
1033 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1034#endif
1035 fileId = lockKey.fid;
1036 if( ppLock!=0 ){
1037 pLock = lockList;
1038 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1039 pLock = pLock->pNext;
1040 }
1041 if( pLock==0 ){
1042 pLock = sqlite3_malloc( sizeof(*pLock) );
1043 if( pLock==0 ){
1044 rc = SQLITE_NOMEM;
1045 goto exit_findlockinfo;
1046 }
drh9b5db1d2009-10-07 23:42:25 +00001047 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
drh6c7d5c52008-11-21 20:32:33 +00001048 pLock->nRef = 1;
1049 pLock->cnt = 0;
1050 pLock->locktype = 0;
drh7ed97b92010-01-20 13:07:21 +00001051#if defined(SQLITE_ENABLE_LOCKING_STYLE)
1052 pLock->sharedByte = 0;
1053#endif
drh6c7d5c52008-11-21 20:32:33 +00001054 pLock->pNext = lockList;
1055 pLock->pPrev = 0;
1056 if( lockList ) lockList->pPrev = pLock;
1057 lockList = pLock;
1058 }else{
1059 pLock->nRef++;
1060 }
1061 *ppLock = pLock;
1062 }
1063 if( ppOpen!=0 ){
1064 pOpen = openList;
1065 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1066 pOpen = pOpen->pNext;
1067 }
1068 if( pOpen==0 ){
1069 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1070 if( pOpen==0 ){
1071 releaseLockInfo(pLock);
1072 rc = SQLITE_NOMEM;
1073 goto exit_findlockinfo;
1074 }
dane946c392009-08-22 11:39:46 +00001075 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001076 pOpen->fileId = fileId;
1077 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001078 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001079 if( openList ) openList->pPrev = pOpen;
1080 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001081 }else{
1082 pOpen->nRef++;
1083 }
1084 *ppOpen = pOpen;
1085 }
1086
1087exit_findlockinfo:
1088 return rc;
1089}
drh6c7d5c52008-11-21 20:32:33 +00001090
drh7708e972008-11-29 00:56:52 +00001091/*
1092** If we are currently in a different thread than the thread that the
1093** unixFile argument belongs to, then transfer ownership of the unixFile
1094** over to the current thread.
1095**
1096** A unixFile is only owned by a thread on systems that use LinuxThreads.
1097**
1098** Ownership transfer is only allowed if the unixFile is currently unlocked.
1099** If the unixFile is locked and an ownership is wrong, then return
1100** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1101*/
1102#if SQLITE_THREADSAFE && defined(__linux__)
1103static int transferOwnership(unixFile *pFile){
1104 int rc;
1105 pthread_t hSelf;
1106 if( threadsOverrideEachOthersLocks ){
1107 /* Ownership transfers not needed on this system */
1108 return SQLITE_OK;
1109 }
1110 hSelf = pthread_self();
1111 if( pthread_equal(pFile->tid, hSelf) ){
1112 /* We are still in the same thread */
1113 OSTRACE1("No-transfer, same thread\n");
1114 return SQLITE_OK;
1115 }
1116 if( pFile->locktype!=NO_LOCK ){
1117 /* We cannot change ownership while we are holding a lock! */
drh413c3d32010-02-23 20:11:56 +00001118 return SQLITE_MISUSE_BKPT;
drh7708e972008-11-29 00:56:52 +00001119 }
1120 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1121 pFile->h, pFile->tid, hSelf);
1122 pFile->tid = hSelf;
1123 if (pFile->pLock != NULL) {
1124 releaseLockInfo(pFile->pLock);
1125 rc = findLockInfo(pFile, &pFile->pLock, 0);
1126 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1127 locktypeName(pFile->locktype),
1128 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1129 return rc;
1130 } else {
1131 return SQLITE_OK;
1132 }
1133}
1134#else /* if not SQLITE_THREADSAFE */
1135 /* On single-threaded builds, ownership transfer is a no-op */
1136# define transferOwnership(X) SQLITE_OK
1137#endif /* SQLITE_THREADSAFE */
1138
aswift5b1a2562008-08-22 00:22:35 +00001139
1140/*
danielk197713adf8a2004-06-03 16:08:41 +00001141** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001142** file by this or any other process. If such a lock is held, set *pResOut
1143** to a non-zero value otherwise *pResOut is set to zero. The return value
1144** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001145*/
danielk1977861f7452008-06-05 11:39:11 +00001146static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001147 int rc = SQLITE_OK;
1148 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001149 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001150
danielk1977861f7452008-06-05 11:39:11 +00001151 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1152
drh054889e2005-11-30 03:20:31 +00001153 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001154 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001155
1156 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001157 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001158 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001159 }
1160
drh2ac3ee92004-06-07 16:27:46 +00001161 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001162 */
danielk197709480a92009-02-09 05:32:32 +00001163#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001164 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001165 struct flock lock;
1166 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001167 lock.l_start = RESERVED_BYTE;
1168 lock.l_len = 1;
1169 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001170 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1171 int tErrno = errno;
1172 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1173 pFile->lastErrno = tErrno;
1174 } else if( lock.l_type!=F_UNLCK ){
1175 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001176 }
1177 }
danielk197709480a92009-02-09 05:32:32 +00001178#endif
danielk197713adf8a2004-06-03 16:08:41 +00001179
drh6c7d5c52008-11-21 20:32:33 +00001180 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001181 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001182
aswift5b1a2562008-08-22 00:22:35 +00001183 *pResOut = reserved;
1184 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001185}
1186
1187/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001188** Lock the file with the lock specified by parameter locktype - one
1189** of the following:
1190**
drh2ac3ee92004-06-07 16:27:46 +00001191** (1) SHARED_LOCK
1192** (2) RESERVED_LOCK
1193** (3) PENDING_LOCK
1194** (4) EXCLUSIVE_LOCK
1195**
drhb3e04342004-06-08 00:47:47 +00001196** Sometimes when requesting one lock state, additional lock states
1197** are inserted in between. The locking might fail on one of the later
1198** transitions leaving the lock state different from what it started but
1199** still short of its goal. The following chart shows the allowed
1200** transitions and the inserted intermediate states:
1201**
1202** UNLOCKED -> SHARED
1203** SHARED -> RESERVED
1204** SHARED -> (PENDING) -> EXCLUSIVE
1205** RESERVED -> (PENDING) -> EXCLUSIVE
1206** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001207**
drha6abd042004-06-09 17:37:22 +00001208** This routine will only increase a lock. Use the sqlite3OsUnlock()
1209** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001210*/
danielk197762079062007-08-15 17:08:46 +00001211static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001212 /* The following describes the implementation of the various locks and
1213 ** lock transitions in terms of the POSIX advisory shared and exclusive
1214 ** lock primitives (called read-locks and write-locks below, to avoid
1215 ** confusion with SQLite lock names). The algorithms are complicated
1216 ** slightly in order to be compatible with windows systems simultaneously
1217 ** accessing the same database file, in case that is ever required.
1218 **
1219 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1220 ** byte', each single bytes at well known offsets, and the 'shared byte
1221 ** range', a range of 510 bytes at a well known offset.
1222 **
1223 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1224 ** byte'. If this is successful, a random byte from the 'shared byte
1225 ** range' is read-locked and the lock on the 'pending byte' released.
1226 **
danielk197790ba3bd2004-06-25 08:32:25 +00001227 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1228 ** A RESERVED lock is implemented by grabbing a write-lock on the
1229 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001230 **
1231 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001232 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1233 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1234 ** obtained, but existing SHARED locks are allowed to persist. A process
1235 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1236 ** This property is used by the algorithm for rolling back a journal file
1237 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001238 **
danielk197790ba3bd2004-06-25 08:32:25 +00001239 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1240 ** implemented by obtaining a write-lock on the entire 'shared byte
1241 ** range'. Since all other locks require a read-lock on one of the bytes
1242 ** within this range, this ensures that no other locks are held on the
1243 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001244 **
1245 ** The reason a single byte cannot be used instead of the 'shared byte
1246 ** range' is that some versions of windows do not support read-locks. By
1247 ** locking a random byte from a range, concurrent SHARED locks may exist
1248 ** even if the locking primitive used is always a write-lock.
1249 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001250 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001251 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001252 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001253 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001254 int s = 0;
drh383d30f2010-02-26 13:07:37 +00001255 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001256
drh054889e2005-11-30 03:20:31 +00001257 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001258 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001259 locktypeName(locktype), locktypeName(pFile->locktype),
1260 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001261
1262 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001263 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001264 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001265 */
drh054889e2005-11-30 03:20:31 +00001266 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00001267 OSTRACE3("LOCK %d %s ok (already held) (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001268 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001269 return SQLITE_OK;
1270 }
1271
drh0c2694b2009-09-03 16:23:44 +00001272 /* Make sure the locking sequence is correct.
1273 ** (1) We never move from unlocked to anything higher than shared lock.
1274 ** (2) SQLite never explicitly requests a pendig lock.
1275 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001276 */
drh054889e2005-11-30 03:20:31 +00001277 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001278 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001279 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001280
drh054889e2005-11-30 03:20:31 +00001281 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001282 */
drh6c7d5c52008-11-21 20:32:33 +00001283 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001284
drh029b44b2006-01-15 00:13:15 +00001285 /* Make sure the current thread owns the pFile.
1286 */
1287 rc = transferOwnership(pFile);
1288 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001289 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001290 return rc;
1291 }
drh64b1bea2006-01-15 02:30:57 +00001292 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001293
danielk1977ad94b582007-08-20 06:44:22 +00001294 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 ** handle that precludes the requested lock, return BUSY.
1296 */
drh054889e2005-11-30 03:20:31 +00001297 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001298 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 ){
1300 rc = SQLITE_BUSY;
1301 goto end_lock;
1302 }
1303
1304 /* If a SHARED lock is requested, and some thread using this PID already
1305 ** has a SHARED or RESERVED lock, then increment reference counts and
1306 ** return SQLITE_OK.
1307 */
1308 if( locktype==SHARED_LOCK &&
1309 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1310 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001311 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001312 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001313 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001314 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001315 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 goto end_lock;
1317 }
1318
danielk19779a1d0ab2004-06-01 14:09:28 +00001319
drh3cde3bb2004-06-12 02:17:14 +00001320 /* A PENDING lock is needed before acquiring a SHARED lock and before
1321 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1322 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 */
drh0c2694b2009-09-03 16:23:44 +00001324 lock.l_len = 1L;
1325 lock.l_whence = SEEK_SET;
drh3cde3bb2004-06-12 02:17:14 +00001326 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001327 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001328 ){
danielk1977489468c2004-06-28 08:25:47 +00001329 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001330 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001331 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001332 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001333 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001334 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1335 if( IS_LOCK_ERROR(rc) ){
1336 pFile->lastErrno = tErrno;
1337 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001338 goto end_lock;
1339 }
drh3cde3bb2004-06-12 02:17:14 +00001340 }
1341
1342
1343 /* If control gets to this point, then actually go ahead and make
1344 ** operating system calls for the specified lock.
1345 */
1346 if( locktype==SHARED_LOCK ){
1347 assert( pLock->cnt==0 );
1348 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001349
drh2ac3ee92004-06-07 16:27:46 +00001350 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001351 lock.l_start = SHARED_FIRST;
1352 lock.l_len = SHARED_SIZE;
1353 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1354 tErrno = errno;
1355 }
drh2ac3ee92004-06-07 16:27:46 +00001356 /* Drop the temporary PENDING lock */
1357 lock.l_start = PENDING_BYTE;
1358 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001359 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001360 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001361 if( s != -1 ){
1362 /* This could happen with a network mount */
1363 tErrno = errno;
1364 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1365 if( IS_LOCK_ERROR(rc) ){
1366 pFile->lastErrno = tErrno;
1367 }
1368 goto end_lock;
1369 }
drh2b4b5962005-06-15 17:47:55 +00001370 }
drhe2396a12007-03-29 20:19:58 +00001371 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001372 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1373 if( IS_LOCK_ERROR(rc) ){
1374 pFile->lastErrno = tErrno;
1375 }
drhbbd42a62004-05-22 17:41:58 +00001376 }else{
drh054889e2005-11-30 03:20:31 +00001377 pFile->locktype = SHARED_LOCK;
1378 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001379 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001380 }
drh3cde3bb2004-06-12 02:17:14 +00001381 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1382 /* We are trying for an exclusive lock but another thread in this
1383 ** same process is still holding a shared lock. */
1384 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001385 }else{
drh3cde3bb2004-06-12 02:17:14 +00001386 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001387 ** assumed that there is a SHARED or greater lock on the file
1388 ** already.
1389 */
drh054889e2005-11-30 03:20:31 +00001390 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 lock.l_type = F_WRLCK;
1392 switch( locktype ){
1393 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001394 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001395 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001397 lock.l_start = SHARED_FIRST;
1398 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001399 break;
1400 default:
1401 assert(0);
1402 }
drh7ed97b92010-01-20 13:07:21 +00001403 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001404 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001405 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1407 if( IS_LOCK_ERROR(rc) ){
1408 pFile->lastErrno = tErrno;
1409 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001410 }
drhbbd42a62004-05-22 17:41:58 +00001411 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001412
drh8f941bc2009-01-14 23:03:40 +00001413
1414#ifndef NDEBUG
1415 /* Set up the transaction-counter change checking flags when
1416 ** transitioning from a SHARED to a RESERVED lock. The change
1417 ** from SHARED to RESERVED marks the beginning of a normal
1418 ** write operation (not a hot journal rollback).
1419 */
1420 if( rc==SQLITE_OK
1421 && pFile->locktype<=SHARED_LOCK
1422 && locktype==RESERVED_LOCK
1423 ){
1424 pFile->transCntrChng = 0;
1425 pFile->dbUpdate = 0;
1426 pFile->inNormalWrite = 1;
1427 }
1428#endif
1429
1430
danielk1977ecb2a962004-06-02 06:30:16 +00001431 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001432 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001433 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001434 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001435 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001436 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001437 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001438
1439end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001440 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001441 OSTRACE4("LOCK %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001442 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001443 return rc;
1444}
1445
1446/*
dane946c392009-08-22 11:39:46 +00001447** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1448** If all such file descriptors are closed without error, the list is
1449** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001450**
1451** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001452** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001453** not deleted and SQLITE_IOERR_CLOSE returned.
1454*/
1455static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001456 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001457 struct unixOpenCnt *pOpen = pFile->pOpen;
1458 UnixUnusedFd *pError = 0;
1459 UnixUnusedFd *p;
1460 UnixUnusedFd *pNext;
1461 for(p=pOpen->pUnused; p; p=pNext){
1462 pNext = p->pNext;
1463 if( close(p->fd) ){
1464 pFile->lastErrno = errno;
1465 rc = SQLITE_IOERR_CLOSE;
1466 p->pNext = pError;
1467 pError = p;
dane946c392009-08-22 11:39:46 +00001468 }else{
1469 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001470 }
1471 }
dane946c392009-08-22 11:39:46 +00001472 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001473 return rc;
1474}
1475
1476/*
1477** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001478** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001479*/
1480static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001481 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001482 UnixUnusedFd *p = pFile->pUnused;
1483 p->pNext = pOpen->pUnused;
1484 pOpen->pUnused = p;
1485 pFile->h = -1;
1486 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001487}
1488
1489/*
drh054889e2005-11-30 03:20:31 +00001490** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001491** must be either NO_LOCK or SHARED_LOCK.
1492**
1493** If the locking level of the file descriptor is already at or below
1494** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001495**
1496** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1497** the byte range is divided into 2 parts and the first part is unlocked then
1498** set to a read lock, then the other part is simply unlocked. This works
1499** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1500** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001501*/
drh7ed97b92010-01-20 13:07:21 +00001502static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
1503 unixFile *pFile = (unixFile*)id;
1504 struct unixLockInfo *pLock;
1505 struct flock lock;
1506 int rc = SQLITE_OK;
1507 int h;
drh0c2694b2009-09-03 16:23:44 +00001508 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001509
drh054889e2005-11-30 03:20:31 +00001510 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001511 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001512 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001513
1514 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001515 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001516 return SQLITE_OK;
1517 }
drhf1a221e2006-01-15 17:27:17 +00001518 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00001519 return SQLITE_MISUSE_BKPT;
drhf1a221e2006-01-15 17:27:17 +00001520 }
drh6c7d5c52008-11-21 20:32:33 +00001521 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001522 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001523 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001524 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001525 if( pFile->locktype>SHARED_LOCK ){
1526 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001527 SimulateIOErrorBenign(1);
1528 SimulateIOError( h=(-1) )
1529 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001530
1531#ifndef NDEBUG
1532 /* When reducing a lock such that other processes can start
1533 ** reading the database file again, make sure that the
1534 ** transaction counter was updated if any part of the database
1535 ** file changed. If the transaction counter is not updated,
1536 ** other connections to the same file might not realize that
1537 ** the file has changed and hence might not know to flush their
1538 ** cache. The use of a stale cache can lead to database corruption.
1539 */
dan7c246102010-04-12 19:00:29 +00001540#if 0
drh8f941bc2009-01-14 23:03:40 +00001541 assert( pFile->inNormalWrite==0
1542 || pFile->dbUpdate==0
1543 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001544#endif
drh8f941bc2009-01-14 23:03:40 +00001545 pFile->inNormalWrite = 0;
1546#endif
1547
drh7ed97b92010-01-20 13:07:21 +00001548 /* downgrading to a shared lock on NFS involves clearing the write lock
1549 ** before establishing the readlock - to avoid a race condition we downgrade
1550 ** the lock in 2 blocks, so that part of the range will be covered by a
1551 ** write lock until the rest is covered by a read lock:
1552 ** 1: [WWWWW]
1553 ** 2: [....W]
1554 ** 3: [RRRRW]
1555 ** 4: [RRRR.]
1556 */
drh9c105bb2004-10-02 20:38:28 +00001557 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001558 if( handleNFSUnlock ){
1559 off_t divSize = SHARED_SIZE - 1;
1560
1561 lock.l_type = F_UNLCK;
1562 lock.l_whence = SEEK_SET;
1563 lock.l_start = SHARED_FIRST;
1564 lock.l_len = divSize;
1565 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001566 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001567 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1568 if( IS_LOCK_ERROR(rc) ){
1569 pFile->lastErrno = tErrno;
1570 }
1571 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001572 }
drh7ed97b92010-01-20 13:07:21 +00001573 lock.l_type = F_RDLCK;
1574 lock.l_whence = SEEK_SET;
1575 lock.l_start = SHARED_FIRST;
1576 lock.l_len = divSize;
1577 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001578 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001579 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1580 if( IS_LOCK_ERROR(rc) ){
1581 pFile->lastErrno = tErrno;
1582 }
1583 goto end_unlock;
1584 }
1585 lock.l_type = F_UNLCK;
1586 lock.l_whence = SEEK_SET;
1587 lock.l_start = SHARED_FIRST+divSize;
1588 lock.l_len = SHARED_SIZE-divSize;
1589 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001590 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1592 if( IS_LOCK_ERROR(rc) ){
1593 pFile->lastErrno = tErrno;
1594 }
1595 goto end_unlock;
1596 }
1597 }else{
1598 lock.l_type = F_RDLCK;
1599 lock.l_whence = SEEK_SET;
1600 lock.l_start = SHARED_FIRST;
1601 lock.l_len = SHARED_SIZE;
1602 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001603 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001604 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1605 if( IS_LOCK_ERROR(rc) ){
1606 pFile->lastErrno = tErrno;
1607 }
1608 goto end_unlock;
1609 }
drh9c105bb2004-10-02 20:38:28 +00001610 }
1611 }
drhbbd42a62004-05-22 17:41:58 +00001612 lock.l_type = F_UNLCK;
1613 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001614 lock.l_start = PENDING_BYTE;
1615 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001616 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001617 pLock->locktype = SHARED_LOCK;
1618 }else{
drh0c2694b2009-09-03 16:23:44 +00001619 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001620 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1621 if( IS_LOCK_ERROR(rc) ){
1622 pFile->lastErrno = tErrno;
1623 }
drhcd731cf2009-03-28 23:23:02 +00001624 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001625 }
drhbbd42a62004-05-22 17:41:58 +00001626 }
drha6abd042004-06-09 17:37:22 +00001627 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001628 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001629
drha6abd042004-06-09 17:37:22 +00001630 /* Decrement the shared lock counter. Release the lock using an
1631 ** OS call only when all threads in this same process have released
1632 ** the lock.
1633 */
1634 pLock->cnt--;
1635 if( pLock->cnt==0 ){
1636 lock.l_type = F_UNLCK;
1637 lock.l_whence = SEEK_SET;
1638 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001639 SimulateIOErrorBenign(1);
1640 SimulateIOError( h=(-1) )
1641 SimulateIOErrorBenign(0);
1642 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001643 pLock->locktype = NO_LOCK;
1644 }else{
drh0c2694b2009-09-03 16:23:44 +00001645 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001646 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001647 if( IS_LOCK_ERROR(rc) ){
1648 pFile->lastErrno = tErrno;
1649 }
drhf48f9ca2009-03-28 23:47:10 +00001650 pLock->locktype = NO_LOCK;
1651 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001652 }
drha6abd042004-06-09 17:37:22 +00001653 }
1654
drhbbd42a62004-05-22 17:41:58 +00001655 /* Decrement the count of locks against this same file. When the
1656 ** count reaches zero, close any other file descriptors whose close
1657 ** was deferred because of outstanding locks.
1658 */
danielk197764a54c52009-03-30 07:39:35 +00001659 pOpen = pFile->pOpen;
1660 pOpen->nLock--;
1661 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001662 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001663 int rc2 = closePendingFds(pFile);
1664 if( rc==SQLITE_OK ){
1665 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001666 }
drhbbd42a62004-05-22 17:41:58 +00001667 }
1668 }
aswift5b1a2562008-08-22 00:22:35 +00001669
1670end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001671 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001672 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001673 return rc;
drhbbd42a62004-05-22 17:41:58 +00001674}
1675
1676/*
drh7ed97b92010-01-20 13:07:21 +00001677** Lower the locking level on file descriptor pFile to locktype. locktype
1678** must be either NO_LOCK or SHARED_LOCK.
1679**
1680** If the locking level of the file descriptor is already at or below
1681** the requested locking level, this routine is a no-op.
1682*/
1683static int unixUnlock(sqlite3_file *id, int locktype){
1684 return _posixUnlock(id, locktype, 0);
1685}
1686
1687/*
danielk1977e339d652008-06-28 11:23:00 +00001688** This function performs the parts of the "close file" operation
1689** common to all locking schemes. It closes the directory and file
1690** handles, if they are valid, and sets all fields of the unixFile
1691** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001692**
1693** It is *not* necessary to hold the mutex when this routine is called,
1694** even on VxWorks. A mutex will be acquired on VxWorks by the
1695** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001696*/
1697static int closeUnixFile(sqlite3_file *id){
1698 unixFile *pFile = (unixFile*)id;
1699 if( pFile ){
1700 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001701 int err = close(pFile->dirfd);
1702 if( err ){
1703 pFile->lastErrno = errno;
1704 return SQLITE_IOERR_DIR_CLOSE;
1705 }else{
1706 pFile->dirfd=-1;
1707 }
danielk1977e339d652008-06-28 11:23:00 +00001708 }
1709 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001710 int err = close(pFile->h);
1711 if( err ){
1712 pFile->lastErrno = errno;
1713 return SQLITE_IOERR_CLOSE;
1714 }
danielk1977e339d652008-06-28 11:23:00 +00001715 }
drh6c7d5c52008-11-21 20:32:33 +00001716#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001717 if( pFile->pId ){
1718 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001719 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001720 }
drh107886a2008-11-21 22:21:50 +00001721 vxworksReleaseFileId(pFile->pId);
1722 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001723 }
1724#endif
danielk1977e339d652008-06-28 11:23:00 +00001725 OSTRACE2("CLOSE %-3d\n", pFile->h);
1726 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001727 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001728 memset(pFile, 0, sizeof(unixFile));
1729 }
1730 return SQLITE_OK;
1731}
1732
1733/*
danielk1977e3026632004-06-22 11:29:02 +00001734** Close a file.
1735*/
danielk197762079062007-08-15 17:08:46 +00001736static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001737 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001738 if( id ){
1739 unixFile *pFile = (unixFile *)id;
1740 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001741 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001742 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001743 /* If there are outstanding locks, do not actually close the file just
1744 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001745 ** descriptor to pOpen->pUnused list. It will be automatically closed
1746 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001747 */
dan08da86a2009-08-21 17:18:03 +00001748 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001749 }
danielk1977e339d652008-06-28 11:23:00 +00001750 releaseLockInfo(pFile->pLock);
1751 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001752 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001753 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001754 }
aswiftaebf4132008-11-21 00:10:35 +00001755 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001756}
1757
drh734c9862008-11-28 15:37:20 +00001758/************** End of the posix advisory lock implementation *****************
1759******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001760
drh734c9862008-11-28 15:37:20 +00001761/******************************************************************************
1762****************************** No-op Locking **********************************
1763**
1764** Of the various locking implementations available, this is by far the
1765** simplest: locking is ignored. No attempt is made to lock the database
1766** file for reading or writing.
1767**
1768** This locking mode is appropriate for use on read-only databases
1769** (ex: databases that are burned into CD-ROM, for example.) It can
1770** also be used if the application employs some external mechanism to
1771** prevent simultaneous access of the same database by two or more
1772** database connections. But there is a serious risk of database
1773** corruption if this locking mode is used in situations where multiple
1774** database connections are accessing the same database file at the same
1775** time and one or more of those connections are writing.
1776*/
drhbfe66312006-10-03 17:40:40 +00001777
drh734c9862008-11-28 15:37:20 +00001778static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1779 UNUSED_PARAMETER(NotUsed);
1780 *pResOut = 0;
1781 return SQLITE_OK;
1782}
drh734c9862008-11-28 15:37:20 +00001783static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1784 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1785 return SQLITE_OK;
1786}
drh734c9862008-11-28 15:37:20 +00001787static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1788 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1789 return SQLITE_OK;
1790}
1791
1792/*
drh9b35ea62008-11-29 02:20:26 +00001793** Close the file.
drh734c9862008-11-28 15:37:20 +00001794*/
1795static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001796 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001797}
1798
1799/******************* End of the no-op lock implementation *********************
1800******************************************************************************/
1801
1802/******************************************************************************
1803************************* Begin dot-file Locking ******************************
1804**
drh0c2694b2009-09-03 16:23:44 +00001805** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001806** files in order to control access to the database. This works on just
1807** about every filesystem imaginable. But there are serious downsides:
1808**
1809** (1) There is zero concurrency. A single reader blocks all other
1810** connections from reading or writing the database.
1811**
1812** (2) An application crash or power loss can leave stale lock files
1813** sitting around that need to be cleared manually.
1814**
1815** Nevertheless, a dotlock is an appropriate locking mode for use if no
1816** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001817**
1818** Dotfile locking works by creating a file in the same directory as the
1819** database and with the same name but with a ".lock" extension added.
1820** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1821** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001822*/
1823
1824/*
1825** The file suffix added to the data base filename in order to create the
1826** lock file.
1827*/
1828#define DOTLOCK_SUFFIX ".lock"
1829
drh7708e972008-11-29 00:56:52 +00001830/*
1831** This routine checks if there is a RESERVED lock held on the specified
1832** file by this or any other process. If such a lock is held, set *pResOut
1833** to a non-zero value otherwise *pResOut is set to zero. The return value
1834** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1835**
1836** In dotfile locking, either a lock exists or it does not. So in this
1837** variation of CheckReservedLock(), *pResOut is set to true if any lock
1838** is held on the file and false if the file is unlocked.
1839*/
drh734c9862008-11-28 15:37:20 +00001840static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1841 int rc = SQLITE_OK;
1842 int reserved = 0;
1843 unixFile *pFile = (unixFile*)id;
1844
1845 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1846
1847 assert( pFile );
1848
1849 /* Check if a thread in this process holds such a lock */
1850 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001851 /* Either this connection or some other connection in the same process
1852 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001853 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001854 }else{
1855 /* The lock is held if and only if the lockfile exists */
1856 const char *zLockFile = (const char*)pFile->lockingContext;
1857 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001858 }
drh476bda72009-12-04 14:25:18 +00001859 OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001860 *pResOut = reserved;
1861 return rc;
1862}
1863
drh7708e972008-11-29 00:56:52 +00001864/*
1865** Lock the file with the lock specified by parameter locktype - one
1866** of the following:
1867**
1868** (1) SHARED_LOCK
1869** (2) RESERVED_LOCK
1870** (3) PENDING_LOCK
1871** (4) EXCLUSIVE_LOCK
1872**
1873** Sometimes when requesting one lock state, additional lock states
1874** are inserted in between. The locking might fail on one of the later
1875** transitions leaving the lock state different from what it started but
1876** still short of its goal. The following chart shows the allowed
1877** transitions and the inserted intermediate states:
1878**
1879** UNLOCKED -> SHARED
1880** SHARED -> RESERVED
1881** SHARED -> (PENDING) -> EXCLUSIVE
1882** RESERVED -> (PENDING) -> EXCLUSIVE
1883** PENDING -> EXCLUSIVE
1884**
1885** This routine will only increase a lock. Use the sqlite3OsUnlock()
1886** routine to lower a locking level.
1887**
1888** With dotfile locking, we really only support state (4): EXCLUSIVE.
1889** But we track the other locking levels internally.
1890*/
drh734c9862008-11-28 15:37:20 +00001891static int dotlockLock(sqlite3_file *id, int locktype) {
1892 unixFile *pFile = (unixFile*)id;
1893 int fd;
1894 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001895 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001896
drh7708e972008-11-29 00:56:52 +00001897
1898 /* If we have any lock, then the lock file already exists. All we have
1899 ** to do is adjust our internal record of the lock level.
1900 */
1901 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001902 pFile->locktype = locktype;
1903#if !OS_VXWORKS
1904 /* Always update the timestamp on the old file */
1905 utimes(zLockFile, NULL);
1906#endif
drh7708e972008-11-29 00:56:52 +00001907 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001908 }
1909
1910 /* grab an exclusive lock */
1911 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1912 if( fd<0 ){
1913 /* failed to open/create the file, someone else may have stolen the lock */
1914 int tErrno = errno;
1915 if( EEXIST == tErrno ){
1916 rc = SQLITE_BUSY;
1917 } else {
1918 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1919 if( IS_LOCK_ERROR(rc) ){
1920 pFile->lastErrno = tErrno;
1921 }
1922 }
drh7708e972008-11-29 00:56:52 +00001923 return rc;
drh734c9862008-11-28 15:37:20 +00001924 }
1925 if( close(fd) ){
1926 pFile->lastErrno = errno;
1927 rc = SQLITE_IOERR_CLOSE;
1928 }
1929
1930 /* got it, set the type and return ok */
1931 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001932 return rc;
1933}
1934
drh7708e972008-11-29 00:56:52 +00001935/*
1936** Lower the locking level on file descriptor pFile to locktype. locktype
1937** must be either NO_LOCK or SHARED_LOCK.
1938**
1939** If the locking level of the file descriptor is already at or below
1940** the requested locking level, this routine is a no-op.
1941**
1942** When the locking level reaches NO_LOCK, delete the lock file.
1943*/
drh734c9862008-11-28 15:37:20 +00001944static int dotlockUnlock(sqlite3_file *id, int locktype) {
1945 unixFile *pFile = (unixFile*)id;
1946 char *zLockFile = (char *)pFile->lockingContext;
1947
1948 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001949 OSTRACE5("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00001950 pFile->locktype, getpid());
1951 assert( locktype<=SHARED_LOCK );
1952
1953 /* no-op if possible */
1954 if( pFile->locktype==locktype ){
1955 return SQLITE_OK;
1956 }
drh7708e972008-11-29 00:56:52 +00001957
1958 /* To downgrade to shared, simply update our internal notion of the
1959 ** lock state. No need to mess with the file on disk.
1960 */
1961 if( locktype==SHARED_LOCK ){
1962 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001963 return SQLITE_OK;
1964 }
1965
drh7708e972008-11-29 00:56:52 +00001966 /* To fully unlock the database, delete the lock file */
1967 assert( locktype==NO_LOCK );
1968 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001969 int rc = 0;
1970 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001971 if( ENOENT != tErrno ){
1972 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1973 }
1974 if( IS_LOCK_ERROR(rc) ){
1975 pFile->lastErrno = tErrno;
1976 }
1977 return rc;
1978 }
1979 pFile->locktype = NO_LOCK;
1980 return SQLITE_OK;
1981}
1982
1983/*
drh9b35ea62008-11-29 02:20:26 +00001984** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001985*/
1986static int dotlockClose(sqlite3_file *id) {
1987 int rc;
1988 if( id ){
1989 unixFile *pFile = (unixFile*)id;
1990 dotlockUnlock(id, NO_LOCK);
1991 sqlite3_free(pFile->lockingContext);
1992 }
drh734c9862008-11-28 15:37:20 +00001993 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001994 return rc;
1995}
1996/****************** End of the dot-file lock implementation *******************
1997******************************************************************************/
1998
1999/******************************************************************************
2000************************** Begin flock Locking ********************************
2001**
2002** Use the flock() system call to do file locking.
2003**
drh6b9d6dd2008-12-03 19:34:47 +00002004** flock() locking is like dot-file locking in that the various
2005** fine-grain locking levels supported by SQLite are collapsed into
2006** a single exclusive lock. In other words, SHARED, RESERVED, and
2007** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2008** still works when you do this, but concurrency is reduced since
2009** only a single process can be reading the database at a time.
2010**
drh734c9862008-11-28 15:37:20 +00002011** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2012** compiling for VXWORKS.
2013*/
2014#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002015
drh6b9d6dd2008-12-03 19:34:47 +00002016/*
2017** This routine checks if there is a RESERVED lock held on the specified
2018** file by this or any other process. If such a lock is held, set *pResOut
2019** to a non-zero value otherwise *pResOut is set to zero. The return value
2020** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2021*/
drh734c9862008-11-28 15:37:20 +00002022static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2023 int rc = SQLITE_OK;
2024 int reserved = 0;
2025 unixFile *pFile = (unixFile*)id;
2026
2027 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2028
2029 assert( pFile );
2030
2031 /* Check if a thread in this process holds such a lock */
2032 if( pFile->locktype>SHARED_LOCK ){
2033 reserved = 1;
2034 }
2035
2036 /* Otherwise see if some other process holds it. */
2037 if( !reserved ){
2038 /* attempt to get the lock */
2039 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2040 if( !lrc ){
2041 /* got the lock, unlock it */
2042 lrc = flock(pFile->h, LOCK_UN);
2043 if ( lrc ) {
2044 int tErrno = errno;
2045 /* unlock failed with an error */
2046 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2047 if( IS_LOCK_ERROR(lrc) ){
2048 pFile->lastErrno = tErrno;
2049 rc = lrc;
2050 }
2051 }
2052 } else {
2053 int tErrno = errno;
2054 reserved = 1;
2055 /* someone else might have it reserved */
2056 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2057 if( IS_LOCK_ERROR(lrc) ){
2058 pFile->lastErrno = tErrno;
2059 rc = lrc;
2060 }
2061 }
2062 }
drh476bda72009-12-04 14:25:18 +00002063 OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002064
2065#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2066 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2067 rc = SQLITE_OK;
2068 reserved=1;
2069 }
2070#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2071 *pResOut = reserved;
2072 return rc;
2073}
2074
drh6b9d6dd2008-12-03 19:34:47 +00002075/*
2076** Lock the file with the lock specified by parameter locktype - one
2077** of the following:
2078**
2079** (1) SHARED_LOCK
2080** (2) RESERVED_LOCK
2081** (3) PENDING_LOCK
2082** (4) EXCLUSIVE_LOCK
2083**
2084** Sometimes when requesting one lock state, additional lock states
2085** are inserted in between. The locking might fail on one of the later
2086** transitions leaving the lock state different from what it started but
2087** still short of its goal. The following chart shows the allowed
2088** transitions and the inserted intermediate states:
2089**
2090** UNLOCKED -> SHARED
2091** SHARED -> RESERVED
2092** SHARED -> (PENDING) -> EXCLUSIVE
2093** RESERVED -> (PENDING) -> EXCLUSIVE
2094** PENDING -> EXCLUSIVE
2095**
2096** flock() only really support EXCLUSIVE locks. We track intermediate
2097** lock states in the sqlite3_file structure, but all locks SHARED or
2098** above are really EXCLUSIVE locks and exclude all other processes from
2099** access the file.
2100**
2101** This routine will only increase a lock. Use the sqlite3OsUnlock()
2102** routine to lower a locking level.
2103*/
drh734c9862008-11-28 15:37:20 +00002104static int flockLock(sqlite3_file *id, int locktype) {
2105 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002106 unixFile *pFile = (unixFile*)id;
2107
2108 assert( pFile );
2109
2110 /* if we already have a lock, it is exclusive.
2111 ** Just adjust level and punt on outta here. */
2112 if (pFile->locktype > NO_LOCK) {
2113 pFile->locktype = locktype;
2114 return SQLITE_OK;
2115 }
2116
2117 /* grab an exclusive lock */
2118
2119 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2120 int tErrno = errno;
2121 /* didn't get, must be busy */
2122 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2123 if( IS_LOCK_ERROR(rc) ){
2124 pFile->lastErrno = tErrno;
2125 }
2126 } else {
2127 /* got it, set the type and return ok */
2128 pFile->locktype = locktype;
2129 }
drh476bda72009-12-04 14:25:18 +00002130 OSTRACE4("LOCK %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
drh734c9862008-11-28 15:37:20 +00002131 rc==SQLITE_OK ? "ok" : "failed");
2132#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2133 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2134 rc = SQLITE_BUSY;
2135 }
2136#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2137 return rc;
2138}
2139
drh6b9d6dd2008-12-03 19:34:47 +00002140
2141/*
2142** Lower the locking level on file descriptor pFile to locktype. locktype
2143** must be either NO_LOCK or SHARED_LOCK.
2144**
2145** If the locking level of the file descriptor is already at or below
2146** the requested locking level, this routine is a no-op.
2147*/
drh734c9862008-11-28 15:37:20 +00002148static int flockUnlock(sqlite3_file *id, int locktype) {
2149 unixFile *pFile = (unixFile*)id;
2150
2151 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002152 OSTRACE5("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002153 pFile->locktype, getpid());
2154 assert( locktype<=SHARED_LOCK );
2155
2156 /* no-op if possible */
2157 if( pFile->locktype==locktype ){
2158 return SQLITE_OK;
2159 }
2160
2161 /* shared can just be set because we always have an exclusive */
2162 if (locktype==SHARED_LOCK) {
2163 pFile->locktype = locktype;
2164 return SQLITE_OK;
2165 }
2166
2167 /* no, really, unlock. */
2168 int rc = flock(pFile->h, LOCK_UN);
2169 if (rc) {
2170 int r, tErrno = errno;
2171 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2172 if( IS_LOCK_ERROR(r) ){
2173 pFile->lastErrno = tErrno;
2174 }
2175#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2176 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2177 r = SQLITE_BUSY;
2178 }
2179#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2180
2181 return r;
2182 } else {
2183 pFile->locktype = NO_LOCK;
2184 return SQLITE_OK;
2185 }
2186}
2187
2188/*
2189** Close a file.
2190*/
2191static int flockClose(sqlite3_file *id) {
2192 if( id ){
2193 flockUnlock(id, NO_LOCK);
2194 }
2195 return closeUnixFile(id);
2196}
2197
2198#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2199
2200/******************* End of the flock lock implementation *********************
2201******************************************************************************/
2202
2203/******************************************************************************
2204************************ Begin Named Semaphore Locking ************************
2205**
2206** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002207**
2208** Semaphore locking is like dot-lock and flock in that it really only
2209** supports EXCLUSIVE locking. Only a single process can read or write
2210** the database file at a time. This reduces potential concurrency, but
2211** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002212*/
2213#if OS_VXWORKS
2214
drh6b9d6dd2008-12-03 19:34:47 +00002215/*
2216** This routine checks if there is a RESERVED lock held on the specified
2217** file by this or any other process. If such a lock is held, set *pResOut
2218** to a non-zero value otherwise *pResOut is set to zero. The return value
2219** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2220*/
drh734c9862008-11-28 15:37:20 +00002221static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2222 int rc = SQLITE_OK;
2223 int reserved = 0;
2224 unixFile *pFile = (unixFile*)id;
2225
2226 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2227
2228 assert( pFile );
2229
2230 /* Check if a thread in this process holds such a lock */
2231 if( pFile->locktype>SHARED_LOCK ){
2232 reserved = 1;
2233 }
2234
2235 /* Otherwise see if some other process holds it. */
2236 if( !reserved ){
2237 sem_t *pSem = pFile->pOpen->pSem;
2238 struct stat statBuf;
2239
2240 if( sem_trywait(pSem)==-1 ){
2241 int tErrno = errno;
2242 if( EAGAIN != tErrno ){
2243 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2244 pFile->lastErrno = tErrno;
2245 } else {
2246 /* someone else has the lock when we are in NO_LOCK */
2247 reserved = (pFile->locktype < SHARED_LOCK);
2248 }
2249 }else{
2250 /* we could have it if we want it */
2251 sem_post(pSem);
2252 }
2253 }
drh476bda72009-12-04 14:25:18 +00002254 OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002255
2256 *pResOut = reserved;
2257 return rc;
2258}
2259
drh6b9d6dd2008-12-03 19:34:47 +00002260/*
2261** Lock the file with the lock specified by parameter locktype - one
2262** of the following:
2263**
2264** (1) SHARED_LOCK
2265** (2) RESERVED_LOCK
2266** (3) PENDING_LOCK
2267** (4) EXCLUSIVE_LOCK
2268**
2269** Sometimes when requesting one lock state, additional lock states
2270** are inserted in between. The locking might fail on one of the later
2271** transitions leaving the lock state different from what it started but
2272** still short of its goal. The following chart shows the allowed
2273** transitions and the inserted intermediate states:
2274**
2275** UNLOCKED -> SHARED
2276** SHARED -> RESERVED
2277** SHARED -> (PENDING) -> EXCLUSIVE
2278** RESERVED -> (PENDING) -> EXCLUSIVE
2279** PENDING -> EXCLUSIVE
2280**
2281** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2282** lock states in the sqlite3_file structure, but all locks SHARED or
2283** above are really EXCLUSIVE locks and exclude all other processes from
2284** access the file.
2285**
2286** This routine will only increase a lock. Use the sqlite3OsUnlock()
2287** routine to lower a locking level.
2288*/
drh734c9862008-11-28 15:37:20 +00002289static int semLock(sqlite3_file *id, int locktype) {
2290 unixFile *pFile = (unixFile*)id;
2291 int fd;
2292 sem_t *pSem = pFile->pOpen->pSem;
2293 int rc = SQLITE_OK;
2294
2295 /* if we already have a lock, it is exclusive.
2296 ** Just adjust level and punt on outta here. */
2297 if (pFile->locktype > NO_LOCK) {
2298 pFile->locktype = locktype;
2299 rc = SQLITE_OK;
2300 goto sem_end_lock;
2301 }
2302
2303 /* lock semaphore now but bail out when already locked. */
2304 if( sem_trywait(pSem)==-1 ){
2305 rc = SQLITE_BUSY;
2306 goto sem_end_lock;
2307 }
2308
2309 /* got it, set the type and return ok */
2310 pFile->locktype = locktype;
2311
2312 sem_end_lock:
2313 return rc;
2314}
2315
drh6b9d6dd2008-12-03 19:34:47 +00002316/*
2317** Lower the locking level on file descriptor pFile to locktype. locktype
2318** must be either NO_LOCK or SHARED_LOCK.
2319**
2320** If the locking level of the file descriptor is already at or below
2321** the requested locking level, this routine is a no-op.
2322*/
drh734c9862008-11-28 15:37:20 +00002323static int semUnlock(sqlite3_file *id, int locktype) {
2324 unixFile *pFile = (unixFile*)id;
2325 sem_t *pSem = pFile->pOpen->pSem;
2326
2327 assert( pFile );
2328 assert( pSem );
drh476bda72009-12-04 14:25:18 +00002329 OSTRACE5("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002330 pFile->locktype, getpid());
2331 assert( locktype<=SHARED_LOCK );
2332
2333 /* no-op if possible */
2334 if( pFile->locktype==locktype ){
2335 return SQLITE_OK;
2336 }
2337
2338 /* shared can just be set because we always have an exclusive */
2339 if (locktype==SHARED_LOCK) {
2340 pFile->locktype = locktype;
2341 return SQLITE_OK;
2342 }
2343
2344 /* no, really unlock. */
2345 if ( sem_post(pSem)==-1 ) {
2346 int rc, tErrno = errno;
2347 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2348 if( IS_LOCK_ERROR(rc) ){
2349 pFile->lastErrno = tErrno;
2350 }
2351 return rc;
2352 }
2353 pFile->locktype = NO_LOCK;
2354 return SQLITE_OK;
2355}
2356
2357/*
2358 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002359 */
drh734c9862008-11-28 15:37:20 +00002360static int semClose(sqlite3_file *id) {
2361 if( id ){
2362 unixFile *pFile = (unixFile*)id;
2363 semUnlock(id, NO_LOCK);
2364 assert( pFile );
2365 unixEnterMutex();
2366 releaseLockInfo(pFile->pLock);
2367 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002368 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002369 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002370 }
2371 return SQLITE_OK;
2372}
2373
2374#endif /* OS_VXWORKS */
2375/*
2376** Named semaphore locking is only available on VxWorks.
2377**
2378*************** End of the named semaphore lock implementation ****************
2379******************************************************************************/
2380
2381
2382/******************************************************************************
2383*************************** Begin AFP Locking *********************************
2384**
2385** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2386** on Apple Macintosh computers - both OS9 and OSX.
2387**
2388** Third-party implementations of AFP are available. But this code here
2389** only works on OSX.
2390*/
2391
drhd2cb50b2009-01-09 21:41:17 +00002392#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002393/*
2394** The afpLockingContext structure contains all afp lock specific state
2395*/
drhbfe66312006-10-03 17:40:40 +00002396typedef struct afpLockingContext afpLockingContext;
2397struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002398 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002399 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002400};
2401
2402struct ByteRangeLockPB2
2403{
2404 unsigned long long offset; /* offset to first byte to lock */
2405 unsigned long long length; /* nbr of bytes to lock */
2406 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2407 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2408 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2409 int fd; /* file desc to assoc this lock with */
2410};
2411
drhfd131da2007-08-07 17:13:03 +00002412#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002413
drh6b9d6dd2008-12-03 19:34:47 +00002414/*
2415** This is a utility for setting or clearing a bit-range lock on an
2416** AFP filesystem.
2417**
2418** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2419*/
2420static int afpSetLock(
2421 const char *path, /* Name of the file to be locked or unlocked */
2422 unixFile *pFile, /* Open file descriptor on path */
2423 unsigned long long offset, /* First byte to be locked */
2424 unsigned long long length, /* Number of bytes to lock */
2425 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002426){
drh6b9d6dd2008-12-03 19:34:47 +00002427 struct ByteRangeLockPB2 pb;
2428 int err;
drhbfe66312006-10-03 17:40:40 +00002429
2430 pb.unLockFlag = setLockFlag ? 0 : 1;
2431 pb.startEndFlag = 0;
2432 pb.offset = offset;
2433 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002434 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002435
2436 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002437 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2438 offset, length);
drhbfe66312006-10-03 17:40:40 +00002439 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2440 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002441 int rc;
2442 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002443 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2444 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002445#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2446 rc = SQLITE_BUSY;
2447#else
drh734c9862008-11-28 15:37:20 +00002448 rc = sqliteErrorFromPosixError(tErrno,
2449 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002450#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002451 if( IS_LOCK_ERROR(rc) ){
2452 pFile->lastErrno = tErrno;
2453 }
2454 return rc;
drhbfe66312006-10-03 17:40:40 +00002455 } else {
aswift5b1a2562008-08-22 00:22:35 +00002456 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002457 }
2458}
2459
drh6b9d6dd2008-12-03 19:34:47 +00002460/*
2461** This routine checks if there is a RESERVED lock held on the specified
2462** file by this or any other process. If such a lock is held, set *pResOut
2463** to a non-zero value otherwise *pResOut is set to zero. The return value
2464** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2465*/
danielk1977e339d652008-06-28 11:23:00 +00002466static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002467 int rc = SQLITE_OK;
2468 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002469 unixFile *pFile = (unixFile*)id;
2470
aswift5b1a2562008-08-22 00:22:35 +00002471 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2472
2473 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002474 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002475 if( context->reserved ){
2476 *pResOut = 1;
2477 return SQLITE_OK;
2478 }
2479 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002480
2481 /* Check if a thread in this process holds such a lock */
drh7ed97b92010-01-20 13:07:21 +00002482 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002483 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002484 }
2485
2486 /* Otherwise see if some other process holds it.
2487 */
aswift5b1a2562008-08-22 00:22:35 +00002488 if( !reserved ){
2489 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002490 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002491 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002492 /* if we succeeded in taking the reserved lock, unlock it to restore
2493 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002494 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002495 } else {
2496 /* if we failed to get the lock then someone else must have it */
2497 reserved = 1;
2498 }
2499 if( IS_LOCK_ERROR(lrc) ){
2500 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002501 }
2502 }
drhbfe66312006-10-03 17:40:40 +00002503
drh7ed97b92010-01-20 13:07:21 +00002504 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002505 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
aswift5b1a2562008-08-22 00:22:35 +00002506
2507 *pResOut = reserved;
2508 return rc;
drhbfe66312006-10-03 17:40:40 +00002509}
2510
drh6b9d6dd2008-12-03 19:34:47 +00002511/*
2512** Lock the file with the lock specified by parameter locktype - one
2513** of the following:
2514**
2515** (1) SHARED_LOCK
2516** (2) RESERVED_LOCK
2517** (3) PENDING_LOCK
2518** (4) EXCLUSIVE_LOCK
2519**
2520** Sometimes when requesting one lock state, additional lock states
2521** are inserted in between. The locking might fail on one of the later
2522** transitions leaving the lock state different from what it started but
2523** still short of its goal. The following chart shows the allowed
2524** transitions and the inserted intermediate states:
2525**
2526** UNLOCKED -> SHARED
2527** SHARED -> RESERVED
2528** SHARED -> (PENDING) -> EXCLUSIVE
2529** RESERVED -> (PENDING) -> EXCLUSIVE
2530** PENDING -> EXCLUSIVE
2531**
2532** This routine will only increase a lock. Use the sqlite3OsUnlock()
2533** routine to lower a locking level.
2534*/
danielk1977e339d652008-06-28 11:23:00 +00002535static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002536 int rc = SQLITE_OK;
2537 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002538 struct unixLockInfo *pLock = pFile->pLock;
drhbfe66312006-10-03 17:40:40 +00002539 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002540
2541 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002542 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2543 locktypeName(locktype), locktypeName(pFile->locktype),
2544 locktypeName(pLock->locktype), pLock->cnt , getpid());
drh339eb0b2008-03-07 15:34:11 +00002545
drhbfe66312006-10-03 17:40:40 +00002546 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002547 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002548 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002549 */
drhbfe66312006-10-03 17:40:40 +00002550 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00002551 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002552 locktypeName(locktype));
2553 return SQLITE_OK;
2554 }
2555
2556 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002557 ** (1) We never move from unlocked to anything higher than shared lock.
2558 ** (2) SQLite never explicitly requests a pendig lock.
2559 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002560 */
drhbfe66312006-10-03 17:40:40 +00002561 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2562 assert( locktype!=PENDING_LOCK );
2563 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2564
2565 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002566 */
drh6c7d5c52008-11-21 20:32:33 +00002567 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002568
2569 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002570 */
drhbfe66312006-10-03 17:40:40 +00002571 rc = transferOwnership(pFile);
2572 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002573 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002574 return rc;
2575 }
drh7ed97b92010-01-20 13:07:21 +00002576 pLock = pFile->pLock;
2577
2578 /* If some thread using this PID has a lock via a different unixFile*
2579 ** handle that precludes the requested lock, return BUSY.
2580 */
2581 if( (pFile->locktype!=pLock->locktype &&
2582 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
2583 ){
2584 rc = SQLITE_BUSY;
2585 goto afp_end_lock;
2586 }
2587
2588 /* If a SHARED lock is requested, and some thread using this PID already
2589 ** has a SHARED or RESERVED lock, then increment reference counts and
2590 ** return SQLITE_OK.
2591 */
2592 if( locktype==SHARED_LOCK &&
2593 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
2594 assert( locktype==SHARED_LOCK );
2595 assert( pFile->locktype==0 );
2596 assert( pLock->cnt>0 );
2597 pFile->locktype = SHARED_LOCK;
2598 pLock->cnt++;
2599 pFile->pOpen->nLock++;
2600 goto afp_end_lock;
2601 }
drhbfe66312006-10-03 17:40:40 +00002602
2603 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002604 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2605 ** be released.
2606 */
drhbfe66312006-10-03 17:40:40 +00002607 if( locktype==SHARED_LOCK
2608 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002609 ){
2610 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002611 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002612 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002613 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002614 goto afp_end_lock;
2615 }
2616 }
2617
2618 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002619 ** operating system calls for the specified lock.
2620 */
drhbfe66312006-10-03 17:40:40 +00002621 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002622 int lrc1, lrc2, lrc1Errno;
2623 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002624
drh7ed97b92010-01-20 13:07:21 +00002625 assert( pLock->cnt==0 );
2626 assert( pLock->locktype==0 );
2627
2628 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002629 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002630 /* note that the quality of the randomness doesn't matter that much */
2631 lk = random();
drh7ed97b92010-01-20 13:07:21 +00002632 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002633 lrc1 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002634 SHARED_FIRST+pLock->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002635 if( IS_LOCK_ERROR(lrc1) ){
2636 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002637 }
aswift5b1a2562008-08-22 00:22:35 +00002638 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002639 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002640
aswift5b1a2562008-08-22 00:22:35 +00002641 if( IS_LOCK_ERROR(lrc1) ) {
2642 pFile->lastErrno = lrc1Errno;
2643 rc = lrc1;
2644 goto afp_end_lock;
2645 } else if( IS_LOCK_ERROR(lrc2) ){
2646 rc = lrc2;
2647 goto afp_end_lock;
2648 } else if( lrc1 != SQLITE_OK ) {
2649 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002650 } else {
2651 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002652 pFile->pOpen->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002653 pLock->cnt = 1;
drhbfe66312006-10-03 17:40:40 +00002654 }
drh7ed97b92010-01-20 13:07:21 +00002655 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
2656 /* We are trying for an exclusive lock but another thread in this
2657 ** same process is still holding a shared lock. */
2658 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002659 }else{
2660 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2661 ** assumed that there is a SHARED or greater lock on the file
2662 ** already.
2663 */
2664 int failed = 0;
2665 assert( 0!=pFile->locktype );
2666 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2667 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002668 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002669 if( !failed ){
2670 context->reserved = 1;
2671 }
drhbfe66312006-10-03 17:40:40 +00002672 }
2673 if (!failed && locktype == EXCLUSIVE_LOCK) {
2674 /* Acquire an EXCLUSIVE lock */
2675
2676 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002677 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002678 */
drh6b9d6dd2008-12-03 19:34:47 +00002679 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh7ed97b92010-01-20 13:07:21 +00002680 pLock->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002681 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002682 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002683 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002684 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002685 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002686 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002687 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2688 ** a critical I/O error
2689 */
2690 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2691 SQLITE_IOERR_LOCK;
2692 goto afp_end_lock;
2693 }
2694 }else{
aswift5b1a2562008-08-22 00:22:35 +00002695 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002696 }
2697 }
aswift5b1a2562008-08-22 00:22:35 +00002698 if( failed ){
2699 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002700 }
2701 }
2702
2703 if( rc==SQLITE_OK ){
2704 pFile->locktype = locktype;
drh7ed97b92010-01-20 13:07:21 +00002705 pLock->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002706 }else if( locktype==EXCLUSIVE_LOCK ){
2707 pFile->locktype = PENDING_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002708 pLock->locktype = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002709 }
2710
2711afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002712 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002713 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002714 rc==SQLITE_OK ? "ok" : "failed");
2715 return rc;
2716}
2717
2718/*
drh339eb0b2008-03-07 15:34:11 +00002719** Lower the locking level on file descriptor pFile to locktype. locktype
2720** must be either NO_LOCK or SHARED_LOCK.
2721**
2722** If the locking level of the file descriptor is already at or below
2723** the requested locking level, this routine is a no-op.
2724*/
danielk1977e339d652008-06-28 11:23:00 +00002725static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002726 int rc = SQLITE_OK;
2727 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002728 struct unixLockInfo *pLock;
2729 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2730 int skipShared = 0;
2731#ifdef SQLITE_TEST
2732 int h = pFile->h;
2733#endif
drhbfe66312006-10-03 17:40:40 +00002734
2735 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002736 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
2737 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002738
drhbfe66312006-10-03 17:40:40 +00002739 assert( locktype<=SHARED_LOCK );
2740 if( pFile->locktype<=locktype ){
2741 return SQLITE_OK;
2742 }
2743 if( CHECK_THREADID(pFile) ){
drh413c3d32010-02-23 20:11:56 +00002744 return SQLITE_MISUSE_BKPT;
drhbfe66312006-10-03 17:40:40 +00002745 }
drh6c7d5c52008-11-21 20:32:33 +00002746 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00002747 pLock = pFile->pLock;
2748 assert( pLock->cnt!=0 );
drhbfe66312006-10-03 17:40:40 +00002749 if( pFile->locktype>SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002750 assert( pLock->locktype==pFile->locktype );
2751 SimulateIOErrorBenign(1);
2752 SimulateIOError( h=(-1) )
2753 SimulateIOErrorBenign(0);
2754
2755#ifndef NDEBUG
2756 /* When reducing a lock such that other processes can start
2757 ** reading the database file again, make sure that the
2758 ** transaction counter was updated if any part of the database
2759 ** file changed. If the transaction counter is not updated,
2760 ** other connections to the same file might not realize that
2761 ** the file has changed and hence might not know to flush their
2762 ** cache. The use of a stale cache can lead to database corruption.
2763 */
2764 assert( pFile->inNormalWrite==0
2765 || pFile->dbUpdate==0
2766 || pFile->transCntrChng==1 );
2767 pFile->inNormalWrite = 0;
2768#endif
aswiftaebf4132008-11-21 00:10:35 +00002769
2770 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002771 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2772 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002773 /* only re-establish the shared lock if necessary */
drh7ed97b92010-01-20 13:07:21 +00002774 int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2775 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2776 } else {
2777 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002778 }
2779 }
2780 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002781 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002782 }
drh7ed97b92010-01-20 13:07:21 +00002783 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
2784 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2785 if( !rc ){
2786 context->reserved = 0;
2787 }
aswiftaebf4132008-11-21 00:10:35 +00002788 }
drh7ed97b92010-01-20 13:07:21 +00002789 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
2790 pLock->locktype = SHARED_LOCK;
2791 }
aswiftaebf4132008-11-21 00:10:35 +00002792 }
drh7ed97b92010-01-20 13:07:21 +00002793 if( rc==SQLITE_OK && locktype==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002794
drh7ed97b92010-01-20 13:07:21 +00002795 /* Decrement the shared lock counter. Release the lock using an
2796 ** OS call only when all threads in this same process have released
2797 ** the lock.
2798 */
2799 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2800 pLock->cnt--;
2801 if( pLock->cnt==0 ){
2802 SimulateIOErrorBenign(1);
2803 SimulateIOError( h=(-1) )
2804 SimulateIOErrorBenign(0);
2805 if( !skipShared ){
2806 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2807 }
2808 if( !rc ){
2809 pLock->locktype = NO_LOCK;
2810 pFile->locktype = NO_LOCK;
2811 }
2812 }
2813 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002814 struct unixOpenCnt *pOpen = pFile->pOpen;
drh7ed97b92010-01-20 13:07:21 +00002815
aswiftaebf4132008-11-21 00:10:35 +00002816 pOpen->nLock--;
2817 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002818 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002819 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002820 }
2821 }
drhbfe66312006-10-03 17:40:40 +00002822 }
drh7ed97b92010-01-20 13:07:21 +00002823
drh6c7d5c52008-11-21 20:32:33 +00002824 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00002825 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002826 return rc;
2827}
2828
2829/*
drh339eb0b2008-03-07 15:34:11 +00002830** Close a file & cleanup AFP specific locking context
2831*/
danielk1977e339d652008-06-28 11:23:00 +00002832static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002833 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002834 if( id ){
2835 unixFile *pFile = (unixFile*)id;
2836 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002837 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002838 if( pFile->pOpen && pFile->pOpen->nLock ){
2839 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002840 ** yet because that would clear those locks. Instead, add the file
2841 ** descriptor to pOpen->aPending. It will be automatically closed when
2842 ** the last lock is cleared.
2843 */
dan08da86a2009-08-21 17:18:03 +00002844 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002845 }
drh7ed97b92010-01-20 13:07:21 +00002846 releaseLockInfo(pFile->pLock);
aswiftaebf4132008-11-21 00:10:35 +00002847 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002848 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002849 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002850 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002851 }
drh7ed97b92010-01-20 13:07:21 +00002852 return rc;
drhbfe66312006-10-03 17:40:40 +00002853}
2854
drhd2cb50b2009-01-09 21:41:17 +00002855#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002856/*
2857** The code above is the AFP lock implementation. The code is specific
2858** to MacOSX and does not work on other unix platforms. No alternative
2859** is available. If you don't compile for a mac, then the "unix-afp"
2860** VFS is not available.
2861**
2862********************* End of the AFP lock implementation **********************
2863******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002864
drh7ed97b92010-01-20 13:07:21 +00002865/******************************************************************************
2866*************************** Begin NFS Locking ********************************/
2867
2868#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2869/*
2870 ** Lower the locking level on file descriptor pFile to locktype. locktype
2871 ** must be either NO_LOCK or SHARED_LOCK.
2872 **
2873 ** If the locking level of the file descriptor is already at or below
2874 ** the requested locking level, this routine is a no-op.
2875 */
2876static int nfsUnlock(sqlite3_file *id, int locktype){
2877 return _posixUnlock(id, locktype, 1);
2878}
2879
2880#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2881/*
2882** The code above is the NFS lock implementation. The code is specific
2883** to MacOSX and does not work on other unix platforms. No alternative
2884** is available.
2885**
2886********************* End of the NFS lock implementation **********************
2887******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002888
2889/******************************************************************************
2890**************** Non-locking sqlite3_file methods *****************************
2891**
2892** The next division contains implementations for all methods of the
2893** sqlite3_file object other than the locking methods. The locking
2894** methods were defined in divisions above (one locking method per
2895** division). Those methods that are common to all locking modes
2896** are gather together into this division.
2897*/
drhbfe66312006-10-03 17:40:40 +00002898
2899/*
drh734c9862008-11-28 15:37:20 +00002900** Seek to the offset passed as the second argument, then read cnt
2901** bytes into pBuf. Return the number of bytes actually read.
2902**
2903** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2904** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2905** one system to another. Since SQLite does not define USE_PREAD
2906** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2907** See tickets #2741 and #2681.
2908**
2909** To avoid stomping the errno value on a failed read the lastErrno value
2910** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002911*/
drh734c9862008-11-28 15:37:20 +00002912static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2913 int got;
drh7ed97b92010-01-20 13:07:21 +00002914#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002915 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002916#endif
drh734c9862008-11-28 15:37:20 +00002917 TIMER_START;
2918#if defined(USE_PREAD)
2919 got = pread(id->h, pBuf, cnt, offset);
2920 SimulateIOError( got = -1 );
2921#elif defined(USE_PREAD64)
2922 got = pread64(id->h, pBuf, cnt, offset);
2923 SimulateIOError( got = -1 );
2924#else
2925 newOffset = lseek(id->h, offset, SEEK_SET);
2926 SimulateIOError( newOffset-- );
2927 if( newOffset!=offset ){
2928 if( newOffset == -1 ){
2929 ((unixFile*)id)->lastErrno = errno;
2930 }else{
2931 ((unixFile*)id)->lastErrno = 0;
2932 }
2933 return -1;
2934 }
2935 got = read(id->h, pBuf, cnt);
2936#endif
2937 TIMER_END;
2938 if( got<0 ){
2939 ((unixFile*)id)->lastErrno = errno;
2940 }
2941 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2942 return got;
drhbfe66312006-10-03 17:40:40 +00002943}
2944
2945/*
drh734c9862008-11-28 15:37:20 +00002946** Read data from a file into a buffer. Return SQLITE_OK if all
2947** bytes were read successfully and SQLITE_IOERR if anything goes
2948** wrong.
drh339eb0b2008-03-07 15:34:11 +00002949*/
drh734c9862008-11-28 15:37:20 +00002950static int unixRead(
2951 sqlite3_file *id,
2952 void *pBuf,
2953 int amt,
2954 sqlite3_int64 offset
2955){
dan08da86a2009-08-21 17:18:03 +00002956 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002957 int got;
2958 assert( id );
drh08c6d442009-02-09 17:34:07 +00002959
dan08da86a2009-08-21 17:18:03 +00002960 /* If this is a database file (not a journal, master-journal or temp
2961 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002962#if 0
dane946c392009-08-22 11:39:46 +00002963 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002964 || offset>=PENDING_BYTE+512
2965 || offset+amt<=PENDING_BYTE
2966 );
dan7c246102010-04-12 19:00:29 +00002967#endif
drh08c6d442009-02-09 17:34:07 +00002968
dan08da86a2009-08-21 17:18:03 +00002969 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002970 if( got==amt ){
2971 return SQLITE_OK;
2972 }else if( got<0 ){
2973 /* lastErrno set by seekAndRead */
2974 return SQLITE_IOERR_READ;
2975 }else{
dan08da86a2009-08-21 17:18:03 +00002976 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002977 /* Unread parts of the buffer must be zero-filled */
2978 memset(&((char*)pBuf)[got], 0, amt-got);
2979 return SQLITE_IOERR_SHORT_READ;
2980 }
2981}
2982
2983/*
2984** Seek to the offset in id->offset then read cnt bytes into pBuf.
2985** Return the number of bytes actually read. Update the offset.
2986**
2987** To avoid stomping the errno value on a failed write the lastErrno value
2988** is set before returning.
2989*/
2990static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2991 int got;
drh7ed97b92010-01-20 13:07:21 +00002992#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002993 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002994#endif
drh734c9862008-11-28 15:37:20 +00002995 TIMER_START;
2996#if defined(USE_PREAD)
2997 got = pwrite(id->h, pBuf, cnt, offset);
2998#elif defined(USE_PREAD64)
2999 got = pwrite64(id->h, pBuf, cnt, offset);
3000#else
3001 newOffset = lseek(id->h, offset, SEEK_SET);
3002 if( newOffset!=offset ){
3003 if( newOffset == -1 ){
3004 ((unixFile*)id)->lastErrno = errno;
3005 }else{
3006 ((unixFile*)id)->lastErrno = 0;
3007 }
3008 return -1;
3009 }
3010 got = write(id->h, pBuf, cnt);
3011#endif
3012 TIMER_END;
3013 if( got<0 ){
3014 ((unixFile*)id)->lastErrno = errno;
3015 }
3016
3017 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3018 return got;
3019}
3020
3021
3022/*
3023** Write data from a buffer into a file. Return SQLITE_OK on success
3024** or some other error code on failure.
3025*/
3026static int unixWrite(
3027 sqlite3_file *id,
3028 const void *pBuf,
3029 int amt,
3030 sqlite3_int64 offset
3031){
dan08da86a2009-08-21 17:18:03 +00003032 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003033 int wrote = 0;
3034 assert( id );
3035 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003036
dan08da86a2009-08-21 17:18:03 +00003037 /* If this is a database file (not a journal, master-journal or temp
3038 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003039#if 0
dane946c392009-08-22 11:39:46 +00003040 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003041 || offset>=PENDING_BYTE+512
3042 || offset+amt<=PENDING_BYTE
3043 );
dan7c246102010-04-12 19:00:29 +00003044#endif
drh08c6d442009-02-09 17:34:07 +00003045
drh8f941bc2009-01-14 23:03:40 +00003046#ifndef NDEBUG
3047 /* If we are doing a normal write to a database file (as opposed to
3048 ** doing a hot-journal rollback or a write to some file other than a
3049 ** normal database file) then record the fact that the database
3050 ** has changed. If the transaction counter is modified, record that
3051 ** fact too.
3052 */
dan08da86a2009-08-21 17:18:03 +00003053 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003054 pFile->dbUpdate = 1; /* The database has been modified */
3055 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003056 int rc;
drh8f941bc2009-01-14 23:03:40 +00003057 char oldCntr[4];
3058 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003059 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003060 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003061 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003062 pFile->transCntrChng = 1; /* The transaction counter has changed */
3063 }
3064 }
3065 }
3066#endif
3067
dan08da86a2009-08-21 17:18:03 +00003068 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003069 amt -= wrote;
3070 offset += wrote;
3071 pBuf = &((char*)pBuf)[wrote];
3072 }
3073 SimulateIOError(( wrote=(-1), amt=1 ));
3074 SimulateDiskfullError(( wrote=0, amt=1 ));
3075 if( amt>0 ){
3076 if( wrote<0 ){
3077 /* lastErrno set by seekAndWrite */
3078 return SQLITE_IOERR_WRITE;
3079 }else{
dan08da86a2009-08-21 17:18:03 +00003080 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003081 return SQLITE_FULL;
3082 }
3083 }
3084 return SQLITE_OK;
3085}
3086
3087#ifdef SQLITE_TEST
3088/*
3089** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003090** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003091*/
3092int sqlite3_sync_count = 0;
3093int sqlite3_fullsync_count = 0;
3094#endif
3095
3096/*
drh89240432009-03-25 01:06:01 +00003097** We do not trust systems to provide a working fdatasync(). Some do.
3098** Others do no. To be safe, we will stick with the (slower) fsync().
3099** If you know that your system does support fdatasync() correctly,
3100** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003101*/
drh89240432009-03-25 01:06:01 +00003102#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003103# define fdatasync fsync
3104#endif
3105
3106/*
3107** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3108** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3109** only available on Mac OS X. But that could change.
3110*/
3111#ifdef F_FULLFSYNC
3112# define HAVE_FULLFSYNC 1
3113#else
3114# define HAVE_FULLFSYNC 0
3115#endif
3116
3117
3118/*
3119** The fsync() system call does not work as advertised on many
3120** unix systems. The following procedure is an attempt to make
3121** it work better.
3122**
3123** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3124** for testing when we want to run through the test suite quickly.
3125** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3126** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3127** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003128**
3129** SQLite sets the dataOnly flag if the size of the file is unchanged.
3130** The idea behind dataOnly is that it should only write the file content
3131** to disk, not the inode. We only set dataOnly if the file size is
3132** unchanged since the file size is part of the inode. However,
3133** Ted Ts'o tells us that fdatasync() will also write the inode if the
3134** file size has changed. The only real difference between fdatasync()
3135** and fsync(), Ted tells us, is that fdatasync() will not flush the
3136** inode if the mtime or owner or other inode attributes have changed.
3137** We only care about the file size, not the other file attributes, so
3138** as far as SQLite is concerned, an fdatasync() is always adequate.
3139** So, we always use fdatasync() if it is available, regardless of
3140** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003141*/
3142static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003143 int rc;
drh734c9862008-11-28 15:37:20 +00003144
3145 /* The following "ifdef/elif/else/" block has the same structure as
3146 ** the one below. It is replicated here solely to avoid cluttering
3147 ** up the real code with the UNUSED_PARAMETER() macros.
3148 */
3149#ifdef SQLITE_NO_SYNC
3150 UNUSED_PARAMETER(fd);
3151 UNUSED_PARAMETER(fullSync);
3152 UNUSED_PARAMETER(dataOnly);
3153#elif HAVE_FULLFSYNC
3154 UNUSED_PARAMETER(dataOnly);
3155#else
3156 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003157 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003158#endif
3159
3160 /* Record the number of times that we do a normal fsync() and
3161 ** FULLSYNC. This is used during testing to verify that this procedure
3162 ** gets called with the correct arguments.
3163 */
3164#ifdef SQLITE_TEST
3165 if( fullSync ) sqlite3_fullsync_count++;
3166 sqlite3_sync_count++;
3167#endif
3168
3169 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3170 ** no-op
3171 */
3172#ifdef SQLITE_NO_SYNC
3173 rc = SQLITE_OK;
3174#elif HAVE_FULLFSYNC
3175 if( fullSync ){
3176 rc = fcntl(fd, F_FULLFSYNC, 0);
3177 }else{
3178 rc = 1;
3179 }
3180 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003181 ** It shouldn't be possible for fullfsync to fail on the local
3182 ** file system (on OSX), so failure indicates that FULLFSYNC
3183 ** isn't supported for this file system. So, attempt an fsync
3184 ** and (for now) ignore the overhead of a superfluous fcntl call.
3185 ** It'd be better to detect fullfsync support once and avoid
3186 ** the fcntl call every time sync is called.
3187 */
drh734c9862008-11-28 15:37:20 +00003188 if( rc ) rc = fsync(fd);
3189
drh7ed97b92010-01-20 13:07:21 +00003190#elif defined(__APPLE__)
3191 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3192 ** so currently we default to the macro that redefines fdatasync to fsync
3193 */
3194 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003195#else
drh0b647ff2009-03-21 14:41:04 +00003196 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003197#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003198 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003199 rc = fsync(fd);
3200 }
drh0b647ff2009-03-21 14:41:04 +00003201#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003202#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3203
3204 if( OS_VXWORKS && rc!= -1 ){
3205 rc = 0;
3206 }
chw97185482008-11-17 08:05:31 +00003207 return rc;
drhbfe66312006-10-03 17:40:40 +00003208}
3209
drh734c9862008-11-28 15:37:20 +00003210/*
3211** Make sure all writes to a particular file are committed to disk.
3212**
3213** If dataOnly==0 then both the file itself and its metadata (file
3214** size, access time, etc) are synced. If dataOnly!=0 then only the
3215** file data is synced.
3216**
3217** Under Unix, also make sure that the directory entry for the file
3218** has been created by fsync-ing the directory that contains the file.
3219** If we do not do this and we encounter a power failure, the directory
3220** entry for the journal might not exist after we reboot. The next
3221** SQLite to access the file will not know that the journal exists (because
3222** the directory entry for the journal was never created) and the transaction
3223** will not roll back - possibly leading to database corruption.
3224*/
3225static int unixSync(sqlite3_file *id, int flags){
3226 int rc;
3227 unixFile *pFile = (unixFile*)id;
3228
3229 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3230 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3231
3232 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3233 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3234 || (flags&0x0F)==SQLITE_SYNC_FULL
3235 );
3236
3237 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3238 ** line is to test that doing so does not cause any problems.
3239 */
3240 SimulateDiskfullError( return SQLITE_FULL );
3241
3242 assert( pFile );
3243 OSTRACE2("SYNC %-3d\n", pFile->h);
3244 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3245 SimulateIOError( rc=1 );
3246 if( rc ){
3247 pFile->lastErrno = errno;
3248 return SQLITE_IOERR_FSYNC;
3249 }
3250 if( pFile->dirfd>=0 ){
3251 int err;
3252 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3253 HAVE_FULLFSYNC, isFullsync);
3254#ifndef SQLITE_DISABLE_DIRSYNC
3255 /* The directory sync is only attempted if full_fsync is
3256 ** turned off or unavailable. If a full_fsync occurred above,
3257 ** then the directory sync is superfluous.
3258 */
3259 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3260 /*
3261 ** We have received multiple reports of fsync() returning
3262 ** errors when applied to directories on certain file systems.
3263 ** A failed directory sync is not a big deal. So it seems
3264 ** better to ignore the error. Ticket #1657
3265 */
3266 /* pFile->lastErrno = errno; */
3267 /* return SQLITE_IOERR; */
3268 }
3269#endif
3270 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3271 if( err==0 ){ /* directory when we are done */
3272 pFile->dirfd = -1;
3273 }else{
3274 pFile->lastErrno = errno;
3275 rc = SQLITE_IOERR_DIR_CLOSE;
3276 }
3277 }
3278 return rc;
3279}
3280
3281/*
3282** Truncate an open file to a specified size
3283*/
3284static int unixTruncate(sqlite3_file *id, i64 nByte){
3285 int rc;
3286 assert( id );
3287 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3288 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3289 if( rc ){
3290 ((unixFile*)id)->lastErrno = errno;
3291 return SQLITE_IOERR_TRUNCATE;
3292 }else{
drh3313b142009-11-06 04:13:18 +00003293#ifndef NDEBUG
3294 /* If we are doing a normal write to a database file (as opposed to
3295 ** doing a hot-journal rollback or a write to some file other than a
3296 ** normal database file) and we truncate the file to zero length,
3297 ** that effectively updates the change counter. This might happen
3298 ** when restoring a database using the backup API from a zero-length
3299 ** source.
3300 */
3301 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3302 ((unixFile*)id)->transCntrChng = 1;
3303 }
3304#endif
3305
drh734c9862008-11-28 15:37:20 +00003306 return SQLITE_OK;
3307 }
3308}
3309
3310/*
3311** Determine the current size of a file in bytes
3312*/
3313static int unixFileSize(sqlite3_file *id, i64 *pSize){
3314 int rc;
3315 struct stat buf;
3316 assert( id );
3317 rc = fstat(((unixFile*)id)->h, &buf);
3318 SimulateIOError( rc=1 );
3319 if( rc!=0 ){
3320 ((unixFile*)id)->lastErrno = errno;
3321 return SQLITE_IOERR_FSTAT;
3322 }
3323 *pSize = buf.st_size;
3324
3325 /* When opening a zero-size database, the findLockInfo() procedure
3326 ** writes a single byte into that file in order to work around a bug
3327 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3328 ** layers, we need to report this file size as zero even though it is
3329 ** really 1. Ticket #3260.
3330 */
3331 if( *pSize==1 ) *pSize = 0;
3332
3333
3334 return SQLITE_OK;
3335}
3336
drhd2cb50b2009-01-09 21:41:17 +00003337#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003338/*
3339** Handler for proxy-locking file-control verbs. Defined below in the
3340** proxying locking division.
3341*/
3342static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003343#endif
drh715ff302008-12-03 22:32:44 +00003344
danielk1977ad94b582007-08-20 06:44:22 +00003345
danielk1977e3026632004-06-22 11:29:02 +00003346/*
drh9e33c2c2007-08-31 18:34:59 +00003347** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003348*/
drhcc6bb3e2007-08-31 16:11:35 +00003349static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003350 switch( op ){
3351 case SQLITE_FCNTL_LOCKSTATE: {
3352 *(int*)pArg = ((unixFile*)id)->locktype;
3353 return SQLITE_OK;
3354 }
drh7708e972008-11-29 00:56:52 +00003355 case SQLITE_LAST_ERRNO: {
3356 *(int*)pArg = ((unixFile*)id)->lastErrno;
3357 return SQLITE_OK;
3358 }
drh8f941bc2009-01-14 23:03:40 +00003359#ifndef NDEBUG
3360 /* The pager calls this method to signal that it has done
3361 ** a rollback and that the database is therefore unchanged and
3362 ** it hence it is OK for the transaction change counter to be
3363 ** unchanged.
3364 */
3365 case SQLITE_FCNTL_DB_UNCHANGED: {
3366 ((unixFile*)id)->dbUpdate = 0;
3367 return SQLITE_OK;
3368 }
3369#endif
drhd2cb50b2009-01-09 21:41:17 +00003370#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003371 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003372 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003373 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003374 }
drhd2cb50b2009-01-09 21:41:17 +00003375#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003376 }
drhcc6bb3e2007-08-31 16:11:35 +00003377 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003378}
3379
3380/*
danielk1977a3d4c882007-03-23 10:08:38 +00003381** Return the sector size in bytes of the underlying block device for
3382** the specified file. This is almost always 512 bytes, but may be
3383** larger for some devices.
3384**
3385** SQLite code assumes this function cannot fail. It also assumes that
3386** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003387** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003388** same for both.
3389*/
danielk1977397d65f2008-11-19 11:35:39 +00003390static int unixSectorSize(sqlite3_file *NotUsed){
3391 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003392 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003393}
3394
danielk197790949c22007-08-17 16:50:38 +00003395/*
danielk1977397d65f2008-11-19 11:35:39 +00003396** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003397*/
danielk1977397d65f2008-11-19 11:35:39 +00003398static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3399 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003400 return 0;
3401}
3402
drh734c9862008-11-28 15:37:20 +00003403/*
3404** Here ends the implementation of all sqlite3_file methods.
3405**
3406********************** End sqlite3_file Methods *******************************
3407******************************************************************************/
3408
3409/*
drh6b9d6dd2008-12-03 19:34:47 +00003410** This division contains definitions of sqlite3_io_methods objects that
3411** implement various file locking strategies. It also contains definitions
3412** of "finder" functions. A finder-function is used to locate the appropriate
3413** sqlite3_io_methods object for a particular database file. The pAppData
3414** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3415** the correct finder-function for that VFS.
3416**
3417** Most finder functions return a pointer to a fixed sqlite3_io_methods
3418** object. The only interesting finder-function is autolockIoFinder, which
3419** looks at the filesystem type and tries to guess the best locking
3420** strategy from that.
3421**
drh1875f7a2008-12-08 18:19:17 +00003422** For finder-funtion F, two objects are created:
3423**
3424** (1) The real finder-function named "FImpt()".
3425**
dane946c392009-08-22 11:39:46 +00003426** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003427**
3428**
3429** A pointer to the F pointer is used as the pAppData value for VFS
3430** objects. We have to do this instead of letting pAppData point
3431** directly at the finder-function since C90 rules prevent a void*
3432** from be cast into a function pointer.
3433**
drh6b9d6dd2008-12-03 19:34:47 +00003434**
drh7708e972008-11-29 00:56:52 +00003435** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003436**
drh7708e972008-11-29 00:56:52 +00003437** * A constant sqlite3_io_methods object call METHOD that has locking
3438** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3439**
3440** * An I/O method finder function called FINDER that returns a pointer
3441** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003442*/
drh7708e972008-11-29 00:56:52 +00003443#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3444static const sqlite3_io_methods METHOD = { \
3445 1, /* iVersion */ \
3446 CLOSE, /* xClose */ \
3447 unixRead, /* xRead */ \
3448 unixWrite, /* xWrite */ \
3449 unixTruncate, /* xTruncate */ \
3450 unixSync, /* xSync */ \
3451 unixFileSize, /* xFileSize */ \
3452 LOCK, /* xLock */ \
3453 UNLOCK, /* xUnlock */ \
3454 CKLOCK, /* xCheckReservedLock */ \
3455 unixFileControl, /* xFileControl */ \
3456 unixSectorSize, /* xSectorSize */ \
3457 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3458}; \
drh0c2694b2009-09-03 16:23:44 +00003459static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3460 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003461 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003462} \
drh0c2694b2009-09-03 16:23:44 +00003463static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003464 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003465
3466/*
3467** Here are all of the sqlite3_io_methods objects for each of the
3468** locking strategies. Functions that return pointers to these methods
3469** are also created.
3470*/
3471IOMETHODS(
3472 posixIoFinder, /* Finder function name */
3473 posixIoMethods, /* sqlite3_io_methods object name */
3474 unixClose, /* xClose method */
3475 unixLock, /* xLock method */
3476 unixUnlock, /* xUnlock method */
3477 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003478)
drh7708e972008-11-29 00:56:52 +00003479IOMETHODS(
3480 nolockIoFinder, /* Finder function name */
3481 nolockIoMethods, /* sqlite3_io_methods object name */
3482 nolockClose, /* xClose method */
3483 nolockLock, /* xLock method */
3484 nolockUnlock, /* xUnlock method */
3485 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003486)
drh7708e972008-11-29 00:56:52 +00003487IOMETHODS(
3488 dotlockIoFinder, /* Finder function name */
3489 dotlockIoMethods, /* sqlite3_io_methods object name */
3490 dotlockClose, /* xClose method */
3491 dotlockLock, /* xLock method */
3492 dotlockUnlock, /* xUnlock method */
3493 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003494)
drh7708e972008-11-29 00:56:52 +00003495
chw78a13182009-04-07 05:35:03 +00003496#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003497IOMETHODS(
3498 flockIoFinder, /* Finder function name */
3499 flockIoMethods, /* sqlite3_io_methods object name */
3500 flockClose, /* xClose method */
3501 flockLock, /* xLock method */
3502 flockUnlock, /* xUnlock method */
3503 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003504)
drh7708e972008-11-29 00:56:52 +00003505#endif
3506
drh6c7d5c52008-11-21 20:32:33 +00003507#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003508IOMETHODS(
3509 semIoFinder, /* Finder function name */
3510 semIoMethods, /* sqlite3_io_methods object name */
3511 semClose, /* xClose method */
3512 semLock, /* xLock method */
3513 semUnlock, /* xUnlock method */
3514 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003515)
aswiftaebf4132008-11-21 00:10:35 +00003516#endif
drh7708e972008-11-29 00:56:52 +00003517
drhd2cb50b2009-01-09 21:41:17 +00003518#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003519IOMETHODS(
3520 afpIoFinder, /* Finder function name */
3521 afpIoMethods, /* sqlite3_io_methods object name */
3522 afpClose, /* xClose method */
3523 afpLock, /* xLock method */
3524 afpUnlock, /* xUnlock method */
3525 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003526)
drh715ff302008-12-03 22:32:44 +00003527#endif
3528
3529/*
3530** The proxy locking method is a "super-method" in the sense that it
3531** opens secondary file descriptors for the conch and lock files and
3532** it uses proxy, dot-file, AFP, and flock() locking methods on those
3533** secondary files. For this reason, the division that implements
3534** proxy locking is located much further down in the file. But we need
3535** to go ahead and define the sqlite3_io_methods and finder function
3536** for proxy locking here. So we forward declare the I/O methods.
3537*/
drhd2cb50b2009-01-09 21:41:17 +00003538#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003539static int proxyClose(sqlite3_file*);
3540static int proxyLock(sqlite3_file*, int);
3541static int proxyUnlock(sqlite3_file*, int);
3542static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003543IOMETHODS(
3544 proxyIoFinder, /* Finder function name */
3545 proxyIoMethods, /* sqlite3_io_methods object name */
3546 proxyClose, /* xClose method */
3547 proxyLock, /* xLock method */
3548 proxyUnlock, /* xUnlock method */
3549 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003550)
aswiftaebf4132008-11-21 00:10:35 +00003551#endif
drh7708e972008-11-29 00:56:52 +00003552
drh7ed97b92010-01-20 13:07:21 +00003553/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3554#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3555IOMETHODS(
3556 nfsIoFinder, /* Finder function name */
3557 nfsIoMethods, /* sqlite3_io_methods object name */
3558 unixClose, /* xClose method */
3559 unixLock, /* xLock method */
3560 nfsUnlock, /* xUnlock method */
3561 unixCheckReservedLock /* xCheckReservedLock method */
3562)
3563#endif
drh7708e972008-11-29 00:56:52 +00003564
drhd2cb50b2009-01-09 21:41:17 +00003565#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003566/*
drh6b9d6dd2008-12-03 19:34:47 +00003567** This "finder" function attempts to determine the best locking strategy
3568** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003569** object that implements that strategy.
3570**
3571** This is for MacOSX only.
3572*/
drh1875f7a2008-12-08 18:19:17 +00003573static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003574 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003575 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003576){
3577 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003578 const char *zFilesystem; /* Filesystem type name */
3579 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003580 } aMap[] = {
3581 { "hfs", &posixIoMethods },
3582 { "ufs", &posixIoMethods },
3583 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003584 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003585 { "webdav", &nolockIoMethods },
3586 { 0, 0 }
3587 };
3588 int i;
3589 struct statfs fsInfo;
3590 struct flock lockInfo;
3591
3592 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003593 /* If filePath==NULL that means we are dealing with a transient file
3594 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003595 return &nolockIoMethods;
3596 }
3597 if( statfs(filePath, &fsInfo) != -1 ){
3598 if( fsInfo.f_flags & MNT_RDONLY ){
3599 return &nolockIoMethods;
3600 }
3601 for(i=0; aMap[i].zFilesystem; i++){
3602 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3603 return aMap[i].pMethods;
3604 }
3605 }
3606 }
3607
3608 /* Default case. Handles, amongst others, "nfs".
3609 ** Test byte-range lock using fcntl(). If the call succeeds,
3610 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003611 */
drh7708e972008-11-29 00:56:52 +00003612 lockInfo.l_len = 1;
3613 lockInfo.l_start = 0;
3614 lockInfo.l_whence = SEEK_SET;
3615 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003616 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003617 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3618 return &nfsIoMethods;
3619 } else {
3620 return &posixIoMethods;
3621 }
drh7708e972008-11-29 00:56:52 +00003622 }else{
3623 return &dotlockIoMethods;
3624 }
3625}
drh0c2694b2009-09-03 16:23:44 +00003626static const sqlite3_io_methods
3627 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003628
drhd2cb50b2009-01-09 21:41:17 +00003629#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003630
chw78a13182009-04-07 05:35:03 +00003631#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3632/*
3633** This "finder" function attempts to determine the best locking strategy
3634** for the database file "filePath". It then returns the sqlite3_io_methods
3635** object that implements that strategy.
3636**
3637** This is for VXWorks only.
3638*/
3639static const sqlite3_io_methods *autolockIoFinderImpl(
3640 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003641 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003642){
3643 struct flock lockInfo;
3644
3645 if( !filePath ){
3646 /* If filePath==NULL that means we are dealing with a transient file
3647 ** that does not need to be locked. */
3648 return &nolockIoMethods;
3649 }
3650
3651 /* Test if fcntl() is supported and use POSIX style locks.
3652 ** Otherwise fall back to the named semaphore method.
3653 */
3654 lockInfo.l_len = 1;
3655 lockInfo.l_start = 0;
3656 lockInfo.l_whence = SEEK_SET;
3657 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003658 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003659 return &posixIoMethods;
3660 }else{
3661 return &semIoMethods;
3662 }
3663}
drh0c2694b2009-09-03 16:23:44 +00003664static const sqlite3_io_methods
3665 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003666
3667#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3668
drh7708e972008-11-29 00:56:52 +00003669/*
3670** An abstract type for a pointer to a IO method finder function:
3671*/
drh0c2694b2009-09-03 16:23:44 +00003672typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003673
aswiftaebf4132008-11-21 00:10:35 +00003674
drh734c9862008-11-28 15:37:20 +00003675/****************************************************************************
3676**************************** sqlite3_vfs methods ****************************
3677**
3678** This division contains the implementation of methods on the
3679** sqlite3_vfs object.
3680*/
3681
danielk1977a3d4c882007-03-23 10:08:38 +00003682/*
danielk1977e339d652008-06-28 11:23:00 +00003683** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003684*/
3685static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003686 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003687 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003688 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003689 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003690 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003691 int noLock, /* Omit locking if true */
3692 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003693){
drh7708e972008-11-29 00:56:52 +00003694 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003695 unixFile *pNew = (unixFile *)pId;
3696 int rc = SQLITE_OK;
3697
danielk197717b90b52008-06-06 11:11:25 +00003698 assert( pNew->pLock==NULL );
3699 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003700
dane946c392009-08-22 11:39:46 +00003701 /* Parameter isDelete is only used on vxworks. Express this explicitly
3702 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003703 */
drh7708e972008-11-29 00:56:52 +00003704 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003705
drh218c5082008-03-07 00:27:10 +00003706 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003707 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003708 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003709 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00003710 pNew->fileFlags = 0;
drh339eb0b2008-03-07 15:34:11 +00003711
drh6c7d5c52008-11-21 20:32:33 +00003712#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003713 pNew->pId = vxworksFindFileId(zFilename);
3714 if( pNew->pId==0 ){
3715 noLock = 1;
3716 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003717 }
3718#endif
3719
drhda0e7682008-07-30 15:27:54 +00003720 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003721 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003722 }else{
drh0c2694b2009-09-03 16:23:44 +00003723 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003724#if SQLITE_ENABLE_LOCKING_STYLE
3725 /* Cache zFilename in the locking context (AFP and dotlock override) for
3726 ** proxyLock activation is possible (remote proxy is based on db name)
3727 ** zFilename remains valid until file is closed, to support */
3728 pNew->lockingContext = (void*)zFilename;
3729#endif
drhda0e7682008-07-30 15:27:54 +00003730 }
danielk1977e339d652008-06-28 11:23:00 +00003731
drh7ed97b92010-01-20 13:07:21 +00003732 if( pLockingStyle == &posixIoMethods
3733#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3734 || pLockingStyle == &nfsIoMethods
3735#endif
3736 ){
drh7708e972008-11-29 00:56:52 +00003737 unixEnterMutex();
3738 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003739 if( rc!=SQLITE_OK ){
3740 /* If an error occured in findLockInfo(), close the file descriptor
3741 ** immediately, before releasing the mutex. findLockInfo() may fail
3742 ** in two scenarios:
3743 **
3744 ** (a) A call to fstat() failed.
3745 ** (b) A malloc failed.
3746 **
3747 ** Scenario (b) may only occur if the process is holding no other
3748 ** file descriptors open on the same file. If there were other file
3749 ** descriptors on this file, then no malloc would be required by
3750 ** findLockInfo(). If this is the case, it is quite safe to close
3751 ** handle h - as it is guaranteed that no posix locks will be released
3752 ** by doing so.
3753 **
3754 ** If scenario (a) caused the error then things are not so safe. The
3755 ** implicit assumption here is that if fstat() fails, things are in
3756 ** such bad shape that dropping a lock or two doesn't matter much.
3757 */
3758 close(h);
3759 h = -1;
3760 }
drh7708e972008-11-29 00:56:52 +00003761 unixLeaveMutex();
3762 }
danielk1977e339d652008-06-28 11:23:00 +00003763
drhd2cb50b2009-01-09 21:41:17 +00003764#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003765 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003766 /* AFP locking uses the file path so it needs to be included in
3767 ** the afpLockingContext.
3768 */
3769 afpLockingContext *pCtx;
3770 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3771 if( pCtx==0 ){
3772 rc = SQLITE_NOMEM;
3773 }else{
3774 /* NB: zFilename exists and remains valid until the file is closed
3775 ** according to requirement F11141. So we do not need to make a
3776 ** copy of the filename. */
3777 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00003778 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00003779 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003780 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00003781 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3782 if( rc!=SQLITE_OK ){
3783 sqlite3_free(pNew->lockingContext);
3784 close(h);
3785 h = -1;
3786 }
drh7708e972008-11-29 00:56:52 +00003787 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003788 }
drh7708e972008-11-29 00:56:52 +00003789 }
3790#endif
danielk1977e339d652008-06-28 11:23:00 +00003791
drh7708e972008-11-29 00:56:52 +00003792 else if( pLockingStyle == &dotlockIoMethods ){
3793 /* Dotfile locking uses the file path so it needs to be included in
3794 ** the dotlockLockingContext
3795 */
3796 char *zLockFile;
3797 int nFilename;
drhea678832008-12-10 19:26:22 +00003798 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003799 zLockFile = (char *)sqlite3_malloc(nFilename);
3800 if( zLockFile==0 ){
3801 rc = SQLITE_NOMEM;
3802 }else{
3803 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003804 }
drh7708e972008-11-29 00:56:52 +00003805 pNew->lockingContext = zLockFile;
3806 }
danielk1977e339d652008-06-28 11:23:00 +00003807
drh6c7d5c52008-11-21 20:32:33 +00003808#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003809 else if( pLockingStyle == &semIoMethods ){
3810 /* Named semaphore locking uses the file path so it needs to be
3811 ** included in the semLockingContext
3812 */
3813 unixEnterMutex();
3814 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3815 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3816 char *zSemName = pNew->pOpen->aSemName;
3817 int n;
drh2238dcc2009-08-27 17:56:20 +00003818 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003819 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003820 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003821 if( zSemName[n]=='/' ) zSemName[n] = '_';
3822 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3823 if( pNew->pOpen->pSem == SEM_FAILED ){
3824 rc = SQLITE_NOMEM;
3825 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003826 }
chw97185482008-11-17 08:05:31 +00003827 }
drh7708e972008-11-29 00:56:52 +00003828 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003829 }
drh7708e972008-11-29 00:56:52 +00003830#endif
aswift5b1a2562008-08-22 00:22:35 +00003831
3832 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003833#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003834 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00003835 if( h>=0 ) close(h);
3836 h = -1;
chw97185482008-11-17 08:05:31 +00003837 unlink(zFilename);
3838 isDelete = 0;
3839 }
3840 pNew->isDelete = isDelete;
3841#endif
danielk1977e339d652008-06-28 11:23:00 +00003842 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003843 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003844 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003845 }else{
drh7708e972008-11-29 00:56:52 +00003846 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003847 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003848 }
danielk1977e339d652008-06-28 11:23:00 +00003849 return rc;
drh054889e2005-11-30 03:20:31 +00003850}
drh9c06c952005-11-26 00:25:00 +00003851
danielk1977ad94b582007-08-20 06:44:22 +00003852/*
3853** Open a file descriptor to the directory containing file zFilename.
3854** If successful, *pFd is set to the opened file descriptor and
3855** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3856** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3857** value.
3858**
3859** If SQLITE_OK is returned, the caller is responsible for closing
3860** the file descriptor *pFd using close().
3861*/
danielk1977fee2d252007-08-18 10:59:19 +00003862static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003863 int ii;
drh777b17a2007-09-20 10:02:54 +00003864 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003865 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003866
drh153c62c2007-08-24 03:51:33 +00003867 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003868 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003869 if( ii>0 ){
3870 zDirname[ii] = '\0';
3871 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003872 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003873#ifdef FD_CLOEXEC
3874 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3875#endif
3876 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3877 }
3878 }
danielk1977fee2d252007-08-18 10:59:19 +00003879 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00003880 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00003881}
3882
danielk1977b4b47412007-08-17 15:53:36 +00003883/*
danielk197717b90b52008-06-06 11:11:25 +00003884** Create a temporary file name in zBuf. zBuf must be allocated
3885** by the calling process and must be big enough to hold at least
3886** pVfs->mxPathname bytes.
3887*/
3888static int getTempname(int nBuf, char *zBuf){
3889 static const char *azDirs[] = {
3890 0,
aswiftaebf4132008-11-21 00:10:35 +00003891 0,
danielk197717b90b52008-06-06 11:11:25 +00003892 "/var/tmp",
3893 "/usr/tmp",
3894 "/tmp",
3895 ".",
3896 };
3897 static const unsigned char zChars[] =
3898 "abcdefghijklmnopqrstuvwxyz"
3899 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3900 "0123456789";
drh41022642008-11-21 00:24:42 +00003901 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003902 struct stat buf;
3903 const char *zDir = ".";
3904
3905 /* It's odd to simulate an io-error here, but really this is just
3906 ** using the io-error infrastructure to test that SQLite handles this
3907 ** function failing.
3908 */
3909 SimulateIOError( return SQLITE_IOERR );
3910
3911 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003912 if (NULL == azDirs[1]) {
3913 azDirs[1] = getenv("TMPDIR");
3914 }
3915
3916 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003917 if( azDirs[i]==0 ) continue;
3918 if( stat(azDirs[i], &buf) ) continue;
3919 if( !S_ISDIR(buf.st_mode) ) continue;
3920 if( access(azDirs[i], 07) ) continue;
3921 zDir = azDirs[i];
3922 break;
3923 }
3924
3925 /* Check that the output buffer is large enough for the temporary file
3926 ** name. If it is not, return SQLITE_ERROR.
3927 */
danielk197700e13612008-11-17 19:18:54 +00003928 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003929 return SQLITE_ERROR;
3930 }
3931
3932 do{
3933 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003934 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003935 sqlite3_randomness(15, &zBuf[j]);
3936 for(i=0; i<15; i++, j++){
3937 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3938 }
3939 zBuf[j] = 0;
3940 }while( access(zBuf,0)==0 );
3941 return SQLITE_OK;
3942}
3943
drhd2cb50b2009-01-09 21:41:17 +00003944#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003945/*
3946** Routine to transform a unixFile into a proxy-locking unixFile.
3947** Implementation in the proxy-lock division, but used by unixOpen()
3948** if SQLITE_PREFER_PROXY_LOCKING is defined.
3949*/
3950static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003951#endif
drhc66d5b62008-12-03 22:48:32 +00003952
dan08da86a2009-08-21 17:18:03 +00003953/*
3954** Search for an unused file descriptor that was opened on the database
3955** file (not a journal or master-journal file) identified by pathname
3956** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3957** argument to this function.
3958**
3959** Such a file descriptor may exist if a database connection was closed
3960** but the associated file descriptor could not be closed because some
3961** other file descriptor open on the same file is holding a file-lock.
3962** Refer to comments in the unixClose() function and the lengthy comment
3963** describing "Posix Advisory Locking" at the start of this file for
3964** further details. Also, ticket #4018.
3965**
3966** If a suitable file descriptor is found, then it is returned. If no
3967** such file descriptor is located, -1 is returned.
3968*/
dane946c392009-08-22 11:39:46 +00003969static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3970 UnixUnusedFd *pUnused = 0;
3971
3972 /* Do not search for an unused file descriptor on vxworks. Not because
3973 ** vxworks would not benefit from the change (it might, we're not sure),
3974 ** but because no way to test it is currently available. It is better
3975 ** not to risk breaking vxworks support for the sake of such an obscure
3976 ** feature. */
3977#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003978 struct stat sStat; /* Results of stat() call */
3979
3980 /* A stat() call may fail for various reasons. If this happens, it is
3981 ** almost certain that an open() call on the same path will also fail.
3982 ** For this reason, if an error occurs in the stat() call here, it is
3983 ** ignored and -1 is returned. The caller will try to open a new file
3984 ** descriptor on the same path, fail, and return an error to SQLite.
3985 **
3986 ** Even if a subsequent open() call does succeed, the consequences of
3987 ** not searching for a resusable file descriptor are not dire. */
3988 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00003989 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00003990
3991 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00003992 pOpen = openList;
3993 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
3994 || pOpen->fileId.ino!=sStat.st_ino) ){
3995 pOpen = pOpen->pNext;
3996 }
3997 if( pOpen ){
dane946c392009-08-22 11:39:46 +00003998 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00003999 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004000 pUnused = *pp;
4001 if( pUnused ){
4002 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004003 }
4004 }
4005 unixLeaveMutex();
4006 }
dane946c392009-08-22 11:39:46 +00004007#endif /* if !OS_VXWORKS */
4008 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004009}
danielk197717b90b52008-06-06 11:11:25 +00004010
4011/*
danielk1977ad94b582007-08-20 06:44:22 +00004012** Open the file zPath.
4013**
danielk1977b4b47412007-08-17 15:53:36 +00004014** Previously, the SQLite OS layer used three functions in place of this
4015** one:
4016**
4017** sqlite3OsOpenReadWrite();
4018** sqlite3OsOpenReadOnly();
4019** sqlite3OsOpenExclusive();
4020**
4021** These calls correspond to the following combinations of flags:
4022**
4023** ReadWrite() -> (READWRITE | CREATE)
4024** ReadOnly() -> (READONLY)
4025** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4026**
4027** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4028** true, the file was configured to be automatically deleted when the
4029** file handle closed. To achieve the same effect using this new
4030** interface, add the DELETEONCLOSE flag to those specified above for
4031** OpenExclusive().
4032*/
4033static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004034 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4035 const char *zPath, /* Pathname of file to be opened */
4036 sqlite3_file *pFile, /* The file descriptor to be filled in */
4037 int flags, /* Input flags to control the opening */
4038 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004039){
dan08da86a2009-08-21 17:18:03 +00004040 unixFile *p = (unixFile *)pFile;
4041 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004042 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004043 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004044 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004045 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004046 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004047
4048 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4049 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4050 int isCreate = (flags & SQLITE_OPEN_CREATE);
4051 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4052 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004053#if SQLITE_ENABLE_LOCKING_STYLE
4054 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4055#endif
danielk1977b4b47412007-08-17 15:53:36 +00004056
danielk1977fee2d252007-08-18 10:59:19 +00004057 /* If creating a master or main-file journal, this function will open
4058 ** a file-descriptor on the directory too. The first time unixSync()
4059 ** is called the directory file descriptor will be fsync()ed and close()d.
4060 */
4061 int isOpenDirectory = (isCreate &&
4062 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4063 );
4064
danielk197717b90b52008-06-06 11:11:25 +00004065 /* If argument zPath is a NULL pointer, this function is required to open
4066 ** a temporary file. Use this buffer to store the file name in.
4067 */
4068 char zTmpname[MAX_PATHNAME+1];
4069 const char *zName = zPath;
4070
danielk1977fee2d252007-08-18 10:59:19 +00004071 /* Check the following statements are true:
4072 **
4073 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4074 ** (b) if CREATE is set, then READWRITE must also be set, and
4075 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004076 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004077 */
danielk1977b4b47412007-08-17 15:53:36 +00004078 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004079 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004080 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004081 assert(isDelete==0 || isCreate);
4082
drh33f4e022007-09-03 15:19:34 +00004083 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004084 ** deleted. Nor are they ever temporary files. */
4085 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4086 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4087 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004088
danielk1977fee2d252007-08-18 10:59:19 +00004089 /* Assert that the upper layer has set one of the "file-type" flags. */
4090 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4091 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4092 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004093 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004094 );
4095
dan08da86a2009-08-21 17:18:03 +00004096 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004097
dan08da86a2009-08-21 17:18:03 +00004098 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004099 UnixUnusedFd *pUnused;
4100 pUnused = findReusableFd(zName, flags);
4101 if( pUnused ){
4102 fd = pUnused->fd;
4103 }else{
dan6aa657f2009-08-24 18:57:58 +00004104 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004105 if( !pUnused ){
4106 return SQLITE_NOMEM;
4107 }
4108 }
4109 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004110 }else if( !zName ){
4111 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004112 assert(isDelete && !isOpenDirectory);
4113 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4114 if( rc!=SQLITE_OK ){
4115 return rc;
4116 }
4117 zName = zTmpname;
4118 }
4119
dan08da86a2009-08-21 17:18:03 +00004120 /* Determine the value of the flags parameter passed to POSIX function
4121 ** open(). These must be calculated even if open() is not called, as
4122 ** they may be stored as part of the file handle and used by the
4123 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004124 if( isReadonly ) openFlags |= O_RDONLY;
4125 if( isReadWrite ) openFlags |= O_RDWR;
4126 if( isCreate ) openFlags |= O_CREAT;
4127 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4128 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004129
danielk1977b4b47412007-08-17 15:53:36 +00004130 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004131 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4132 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004133 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
4134 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4135 /* Failed to open the file for read/write access. Try read-only. */
4136 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004137 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004138 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004139 openFlags |= O_RDONLY;
4140 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004141 }
4142 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004143 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004144 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004145 }
danielk1977b4b47412007-08-17 15:53:36 +00004146 }
dan08da86a2009-08-21 17:18:03 +00004147 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004148 if( pOutFlags ){
4149 *pOutFlags = flags;
4150 }
4151
dane946c392009-08-22 11:39:46 +00004152 if( p->pUnused ){
4153 p->pUnused->fd = fd;
4154 p->pUnused->flags = flags;
4155 }
4156
danielk1977b4b47412007-08-17 15:53:36 +00004157 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004158#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004159 zPath = zName;
4160#else
danielk197717b90b52008-06-06 11:11:25 +00004161 unlink(zName);
chw97185482008-11-17 08:05:31 +00004162#endif
danielk1977b4b47412007-08-17 15:53:36 +00004163 }
drh41022642008-11-21 00:24:42 +00004164#if SQLITE_ENABLE_LOCKING_STYLE
4165 else{
dan08da86a2009-08-21 17:18:03 +00004166 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004167 }
4168#endif
4169
danielk1977fee2d252007-08-18 10:59:19 +00004170 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004171 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004172 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004173 /* It is safe to close fd at this point, because it is guaranteed not
4174 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004175 ** it would not be safe to close as this would release any locks held
4176 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004177 assert( eType!=SQLITE_OPEN_MAIN_DB );
4178 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004179 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004180 }
4181 }
danielk1977e339d652008-06-28 11:23:00 +00004182
4183#ifdef FD_CLOEXEC
4184 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4185#endif
4186
drhda0e7682008-07-30 15:27:54 +00004187 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004188
drh7ed97b92010-01-20 13:07:21 +00004189
4190#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4191 struct statfs fsInfo;
4192 if( fstatfs(fd, &fsInfo) == -1 ){
4193 ((unixFile*)pFile)->lastErrno = errno;
4194 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4195 close(fd); /* silently leak if fail, in error */
4196 return SQLITE_IOERR_ACCESS;
4197 }
4198 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4199 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4200 }
4201#endif
4202
4203#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004204#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004205 isAutoProxy = 1;
4206#endif
4207 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004208 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4209 int useProxy = 0;
4210
dan08da86a2009-08-21 17:18:03 +00004211 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4212 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004213 if( envforce!=NULL ){
4214 useProxy = atoi(envforce)>0;
4215 }else{
4216 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004217 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004218 /* In theory, the close(fd) call is sub-optimal. If the file opened
4219 ** with fd is a database file, and there are other connections open
4220 ** on that file that are currently holding advisory locks on it,
4221 ** then the call to close() will cancel those locks. In practice,
4222 ** we're assuming that statfs() doesn't fail very often. At least
4223 ** not while other file descriptors opened by the same process on
4224 ** the same file are working. */
4225 p->lastErrno = errno;
4226 if( dirfd>=0 ){
4227 close(dirfd); /* silently leak if fail, in error */
4228 }
aswiftaebf4132008-11-21 00:10:35 +00004229 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004230 rc = SQLITE_IOERR_ACCESS;
4231 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004232 }
4233 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4234 }
4235 if( useProxy ){
4236 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4237 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004238 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004239 if( rc!=SQLITE_OK ){
4240 /* Use unixClose to clean up the resources added in fillInUnixFile
4241 ** and clear all the structure's references. Specifically,
4242 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4243 */
4244 unixClose(pFile);
4245 return rc;
4246 }
aswiftaebf4132008-11-21 00:10:35 +00004247 }
dane946c392009-08-22 11:39:46 +00004248 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004249 }
4250 }
4251#endif
4252
dane946c392009-08-22 11:39:46 +00004253 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4254open_finished:
4255 if( rc!=SQLITE_OK ){
4256 sqlite3_free(p->pUnused);
4257 }
4258 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004259}
4260
dane946c392009-08-22 11:39:46 +00004261
danielk1977b4b47412007-08-17 15:53:36 +00004262/*
danielk1977fee2d252007-08-18 10:59:19 +00004263** Delete the file at zPath. If the dirSync argument is true, fsync()
4264** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004265*/
drh6b9d6dd2008-12-03 19:34:47 +00004266static int unixDelete(
4267 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4268 const char *zPath, /* Name of file to be deleted */
4269 int dirSync /* If true, fsync() directory after deleting file */
4270){
danielk1977fee2d252007-08-18 10:59:19 +00004271 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004272 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004273 SimulateIOError(return SQLITE_IOERR_DELETE);
4274 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004275#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004276 if( dirSync ){
4277 int fd;
4278 rc = openDirectory(zPath, &fd);
4279 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004280#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004281 if( fsync(fd)==-1 )
4282#else
4283 if( fsync(fd) )
4284#endif
4285 {
danielk1977fee2d252007-08-18 10:59:19 +00004286 rc = SQLITE_IOERR_DIR_FSYNC;
4287 }
aswiftaebf4132008-11-21 00:10:35 +00004288 if( close(fd)&&!rc ){
4289 rc = SQLITE_IOERR_DIR_CLOSE;
4290 }
danielk1977fee2d252007-08-18 10:59:19 +00004291 }
4292 }
danielk1977d138dd82008-10-15 16:02:48 +00004293#endif
danielk1977fee2d252007-08-18 10:59:19 +00004294 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004295}
4296
danielk197790949c22007-08-17 16:50:38 +00004297/*
4298** Test the existance of or access permissions of file zPath. The
4299** test performed depends on the value of flags:
4300**
4301** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4302** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4303** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4304**
4305** Otherwise return 0.
4306*/
danielk1977861f7452008-06-05 11:39:11 +00004307static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004308 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4309 const char *zPath, /* Path of the file to examine */
4310 int flags, /* What do we want to learn about the zPath file? */
4311 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004312){
rse25c0d1a2007-09-20 08:38:14 +00004313 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004314 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004315 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004316 switch( flags ){
4317 case SQLITE_ACCESS_EXISTS:
4318 amode = F_OK;
4319 break;
4320 case SQLITE_ACCESS_READWRITE:
4321 amode = W_OK|R_OK;
4322 break;
drh50d3f902007-08-27 21:10:36 +00004323 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004324 amode = R_OK;
4325 break;
4326
4327 default:
4328 assert(!"Invalid flags argument");
4329 }
danielk1977861f7452008-06-05 11:39:11 +00004330 *pResOut = (access(zPath, amode)==0);
4331 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004332}
4333
danielk1977b4b47412007-08-17 15:53:36 +00004334
4335/*
4336** Turn a relative pathname into a full pathname. The relative path
4337** is stored as a nul-terminated string in the buffer pointed to by
4338** zPath.
4339**
4340** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4341** (in this case, MAX_PATHNAME bytes). The full-path is written to
4342** this buffer before returning.
4343*/
danielk1977adfb9b02007-09-17 07:02:56 +00004344static int unixFullPathname(
4345 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4346 const char *zPath, /* Possibly relative input path */
4347 int nOut, /* Size of output buffer in bytes */
4348 char *zOut /* Output buffer */
4349){
danielk1977843e65f2007-09-01 16:16:15 +00004350
4351 /* It's odd to simulate an io-error here, but really this is just
4352 ** using the io-error infrastructure to test that SQLite handles this
4353 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004354 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004355 */
4356 SimulateIOError( return SQLITE_ERROR );
4357
drh153c62c2007-08-24 03:51:33 +00004358 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004359 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004360
drh3c7f2dc2007-12-06 13:26:20 +00004361 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004362 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004363 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004364 }else{
4365 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004366 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004367 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004368 }
drhea678832008-12-10 19:26:22 +00004369 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004370 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004371 }
4372 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004373}
4374
drh0ccebe72005-06-07 22:22:50 +00004375
drh761df872006-12-21 01:29:22 +00004376#ifndef SQLITE_OMIT_LOAD_EXTENSION
4377/*
4378** Interfaces for opening a shared library, finding entry points
4379** within the shared library, and closing the shared library.
4380*/
4381#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004382static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4383 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004384 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4385}
danielk197795c8a542007-09-01 06:51:27 +00004386
4387/*
4388** SQLite calls this function immediately after a call to unixDlSym() or
4389** unixDlOpen() fails (returns a null pointer). If a more detailed error
4390** message is available, it is written to zBufOut. If no error message
4391** is available, zBufOut is left unmodified and SQLite uses a default
4392** error message.
4393*/
danielk1977397d65f2008-11-19 11:35:39 +00004394static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004395 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004396 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004397 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004398 zErr = dlerror();
4399 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004400 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004401 }
drh6c7d5c52008-11-21 20:32:33 +00004402 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004403}
drh1875f7a2008-12-08 18:19:17 +00004404static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4405 /*
4406 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4407 ** cast into a pointer to a function. And yet the library dlsym() routine
4408 ** returns a void* which is really a pointer to a function. So how do we
4409 ** use dlsym() with -pedantic-errors?
4410 **
4411 ** Variable x below is defined to be a pointer to a function taking
4412 ** parameters void* and const char* and returning a pointer to a function.
4413 ** We initialize x by assigning it a pointer to the dlsym() function.
4414 ** (That assignment requires a cast.) Then we call the function that
4415 ** x points to.
4416 **
4417 ** This work-around is unlikely to work correctly on any system where
4418 ** you really cannot cast a function pointer into void*. But then, on the
4419 ** other hand, dlsym() will not work on such a system either, so we have
4420 ** not really lost anything.
4421 */
4422 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004423 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004424 x = (void(*(*)(void*,const char*))(void))dlsym;
4425 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004426}
danielk1977397d65f2008-11-19 11:35:39 +00004427static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4428 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004429 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004430}
danielk1977b4b47412007-08-17 15:53:36 +00004431#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4432 #define unixDlOpen 0
4433 #define unixDlError 0
4434 #define unixDlSym 0
4435 #define unixDlClose 0
4436#endif
4437
4438/*
danielk197790949c22007-08-17 16:50:38 +00004439** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004440*/
danielk1977397d65f2008-11-19 11:35:39 +00004441static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4442 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004443 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004444
drhbbd42a62004-05-22 17:41:58 +00004445 /* We have to initialize zBuf to prevent valgrind from reporting
4446 ** errors. The reports issued by valgrind are incorrect - we would
4447 ** prefer that the randomness be increased by making use of the
4448 ** uninitialized space in zBuf - but valgrind errors tend to worry
4449 ** some users. Rather than argue, it seems easier just to initialize
4450 ** the whole array and silence valgrind, even if that means less randomness
4451 ** in the random seed.
4452 **
4453 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004454 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004455 ** tests repeatable.
4456 */
danielk1977b4b47412007-08-17 15:53:36 +00004457 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004458#if !defined(SQLITE_TEST)
4459 {
drh842b8642005-01-21 17:53:17 +00004460 int pid, fd;
4461 fd = open("/dev/urandom", O_RDONLY);
4462 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004463 time_t t;
4464 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004465 memcpy(zBuf, &t, sizeof(t));
4466 pid = getpid();
4467 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004468 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004469 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004470 }else{
drh72cbd072008-10-14 17:58:38 +00004471 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004472 close(fd);
4473 }
drhbbd42a62004-05-22 17:41:58 +00004474 }
4475#endif
drh72cbd072008-10-14 17:58:38 +00004476 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004477}
4478
danielk1977b4b47412007-08-17 15:53:36 +00004479
drhbbd42a62004-05-22 17:41:58 +00004480/*
4481** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004482** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004483** The return value is the number of microseconds of sleep actually
4484** requested from the underlying operating system, a number which
4485** might be greater than or equal to the argument, but not less
4486** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004487*/
danielk1977397d65f2008-11-19 11:35:39 +00004488static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004489#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004490 struct timespec sp;
4491
4492 sp.tv_sec = microseconds / 1000000;
4493 sp.tv_nsec = (microseconds % 1000000) * 1000;
4494 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004495 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004496 return microseconds;
4497#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004498 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004499 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004500 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004501#else
danielk1977b4b47412007-08-17 15:53:36 +00004502 int seconds = (microseconds+999999)/1000000;
4503 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004504 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004505 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004506#endif
drh88f474a2006-01-02 20:00:12 +00004507}
4508
4509/*
drh6b9d6dd2008-12-03 19:34:47 +00004510** The following variable, if set to a non-zero value, is interpreted as
4511** the number of seconds since 1970 and is used to set the result of
4512** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004513*/
4514#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004515int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004516#endif
4517
4518/*
drhb7e8ea22010-05-03 14:32:30 +00004519** Find the current time (in Universal Coordinated Time). Write into *piNow
4520** the current time and date as a Julian Day number times 86_400_000. In
4521** other words, write into *piNow the number of milliseconds since the Julian
4522** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4523** proleptic Gregorian calendar.
4524**
4525** On success, return 0. Return 1 if the time and date cannot be found.
4526*/
4527static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
4528 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
4529#if defined(NO_GETTOD)
4530 time_t t;
4531 time(&t);
4532 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
4533#elif OS_VXWORKS
4534 struct timespec sNow;
4535 clock_gettime(CLOCK_REALTIME, &sNow);
4536 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
4537#else
4538 struct timeval sNow;
4539 gettimeofday(&sNow, 0);
4540 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
4541#endif
4542
4543#ifdef SQLITE_TEST
4544 if( sqlite3_current_time ){
4545 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
4546 }
4547#endif
4548 UNUSED_PARAMETER(NotUsed);
4549 return 0;
4550}
4551
4552/*
drhbbd42a62004-05-22 17:41:58 +00004553** Find the current time (in Universal Coordinated Time). Write the
4554** current time and date as a Julian Day number into *prNow and
4555** return 0. Return 1 if the time and date cannot be found.
4556*/
danielk1977397d65f2008-11-19 11:35:39 +00004557static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00004558 sqlite3_int64 i;
4559 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00004560 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00004561 return 0;
4562}
danielk1977b4b47412007-08-17 15:53:36 +00004563
drh6b9d6dd2008-12-03 19:34:47 +00004564/*
4565** We added the xGetLastError() method with the intention of providing
4566** better low-level error messages when operating-system problems come up
4567** during SQLite operation. But so far, none of that has been implemented
4568** in the core. So this routine is never called. For now, it is merely
4569** a place-holder.
4570*/
danielk1977397d65f2008-11-19 11:35:39 +00004571static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4572 UNUSED_PARAMETER(NotUsed);
4573 UNUSED_PARAMETER(NotUsed2);
4574 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004575 return 0;
4576}
4577
dan5cf53532010-05-01 16:40:20 +00004578#ifndef SQLITE_OMIT_WAL
4579
drh7b694402010-04-29 15:17:48 +00004580/* Forward reference */
4581typedef struct unixShm unixShm;
4582typedef struct unixShmFile unixShmFile;
4583
drh153c62c2007-08-24 03:51:33 +00004584/*
drh7b694402010-04-29 15:17:48 +00004585** Object used to represent a single file opened and mmapped to provide
4586** shared memory. When multiple threads all reference the same
4587** log-summary, each thread has its own unixFile object, but they all
4588** point to a single instance of this object. In other words, each
4589** log-summary is opened only once per process.
4590**
4591** unixMutexHeld() must be true when creating or destroying
4592** this object or while reading or writing the following fields:
4593**
4594** nRef
4595** pNext
4596**
4597** The following fields are read-only after the object is created:
4598**
4599** fid
4600** zFilename
4601**
4602** Either unixShmFile.mutex must be held or unixShmFile.nRef==0 and
4603** unixMutexHeld() is true when reading or writing any other field
4604** in this structure.
drhbee6f4e2010-05-01 17:57:36 +00004605**
4606** To avoid deadlocks, mutex and mutexBuf are always released in the
4607** reverse order that they are acquired. mutexBuf is always acquired
4608** first and released last. This invariant is check by asserting
4609** sqlite3_mutex_notheld() on mutex whenever mutexBuf is acquired or
4610** released.
drhf2424c52010-04-26 00:04:55 +00004611*/
drh7b694402010-04-29 15:17:48 +00004612struct unixShmFile {
4613 struct unixFileId fid; /* Unique file identifier */
4614 sqlite3_mutex *mutex; /* Mutex to access this object */
4615 sqlite3_mutex *mutexBuf; /* Mutex to access zBuf[] */
drh7b694402010-04-29 15:17:48 +00004616 char *zFilename; /* Name of the file */
drh7b694402010-04-29 15:17:48 +00004617 int h; /* Open file descriptor */
drh5530b762010-04-30 14:39:50 +00004618 int szMap; /* Size of the mapping of file into memory */
4619 char *pMMapBuf; /* Where currently mmapped(). NULL if unmapped */
drh7b694402010-04-29 15:17:48 +00004620 int nRef; /* Number of unixShm objects pointing to this */
4621 unixShm *pFirst; /* All unixShm objects pointing to this */
4622 unixShmFile *pNext; /* Next in list of all unixShmFile objects */
4623#ifdef SQLITE_DEBUG
4624 u8 exclMask; /* Mask of exclusive locks held */
4625 u8 sharedMask; /* Mask of shared locks held */
4626 u8 nextShmId; /* Next available unixShm.id value */
4627#endif
drhf2424c52010-04-26 00:04:55 +00004628};
4629
4630/*
drh7b694402010-04-29 15:17:48 +00004631** A global array of all unixShmFile objects.
4632**
4633** The unixMutexHeld() must be true while reading or writing this list.
drhf2424c52010-04-26 00:04:55 +00004634*/
drh7b694402010-04-29 15:17:48 +00004635static unixShmFile *unixShmFileList = 0;
4636
4637/*
4638** Structure used internally by this VFS to record the state of an
4639** open shared memory connection.
4640**
4641** unixShm.pFile->mutex must be held while reading or writing the
4642** unixShm.pNext and unixShm.locks[] elements.
4643**
4644** The unixShm.pFile element is initialized when the object is created
4645** and is read-only thereafter.
4646*/
4647struct unixShm {
4648 unixShmFile *pFile; /* The underlying unixShmFile object */
4649 unixShm *pNext; /* Next unixShm with the same unixShmFile */
4650 u8 lockState; /* Current lock state */
drh7b694402010-04-29 15:17:48 +00004651 u8 hasMutex; /* True if holding the unixShmFile mutex */
4652 u8 hasMutexBuf; /* True if holding pFile->mutexBuf */
drh7b694402010-04-29 15:17:48 +00004653 u8 sharedMask; /* Mask of shared locks held */
4654 u8 exclMask; /* Mask of exclusive locks held */
4655#ifdef SQLITE_DEBUG
4656 u8 id; /* Id of this connection with its unixShmFile */
4657#endif
4658};
drhf2424c52010-04-26 00:04:55 +00004659
4660/*
4661** Size increment by which shared memory grows
4662*/
4663#define SQLITE_UNIX_SHM_INCR 4096
4664
4665/*
drh7b694402010-04-29 15:17:48 +00004666** Constants used for locking
4667*/
4668#define UNIX_SHM_BASE 32 /* Byte offset of the first lock byte */
drh4bc79de2010-05-05 18:20:07 +00004669#define UNIX_SHM_DMS 0x01 /* Mask for Dead-Man-Switch lock */
drh7b694402010-04-29 15:17:48 +00004670#define UNIX_SHM_A 0x10 /* Mask for region locks... */
4671#define UNIX_SHM_B 0x20
4672#define UNIX_SHM_C 0x40
4673#define UNIX_SHM_D 0x80
4674
4675#ifdef SQLITE_DEBUG
4676/*
4677** Return a pointer to a nul-terminated string in static memory that
4678** describes a locking mask. The string is of the form "MSABCD" with
4679** each character representing a lock. "M" for MUTEX, "S" for DMS,
4680** and "A" through "D" for the region locks. If a lock is held, the
4681** letter is shown. If the lock is not held, the letter is converted
4682** to ".".
4683**
4684** This routine is for debugging purposes only and does not appear
4685** in a production build.
4686*/
4687static const char *unixShmLockString(u8 mask){
4688 static char zBuf[48];
4689 static int iBuf = 0;
4690 char *z;
4691
4692 z = &zBuf[iBuf];
4693 iBuf += 8;
4694 if( iBuf>=sizeof(zBuf) ) iBuf = 0;
4695
drh4bc79de2010-05-05 18:20:07 +00004696 z[0] = (mask & UNIX_SHM_DMS) ? 'S' : '.';
4697 z[1] = (mask & UNIX_SHM_A) ? 'A' : '.';
4698 z[2] = (mask & UNIX_SHM_B) ? 'B' : '.';
4699 z[3] = (mask & UNIX_SHM_C) ? 'C' : '.';
4700 z[4] = (mask & UNIX_SHM_D) ? 'D' : '.';
4701 z[5] = 0;
drh7b694402010-04-29 15:17:48 +00004702 return z;
4703}
4704#endif /* SQLITE_DEBUG */
4705
4706/*
4707** Apply posix advisory locks for all bytes identified in lockMask.
4708**
4709** lockMask might contain multiple bits but all bits are guaranteed
4710** to be contiguous.
4711**
drh4bc79de2010-05-05 18:20:07 +00004712** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
drh7b694402010-04-29 15:17:48 +00004713** otherwise.
4714*/
drh31cbbba2010-04-29 16:40:51 +00004715static int unixShmSystemLock(
drh7b694402010-04-29 15:17:48 +00004716 unixShmFile *pFile, /* Apply locks to this open shared-memory segment */
4717 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
4718 u8 lockMask /* Which bytes to lock or unlock */
4719){
4720 struct flock f; /* The posix advisory locking structure */
4721 int lockOp; /* The opcode for fcntl() */
4722 int i; /* Offset into the locking byte range */
4723 int rc; /* Result code form fcntl() */
4724 u8 mask; /* Mask of bits in lockMask */
4725
drh31cbbba2010-04-29 16:40:51 +00004726 /* Access to the unixShmFile object is serialized by the caller */
drh79e6c782010-04-30 02:13:26 +00004727 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
drh31cbbba2010-04-29 16:40:51 +00004728
drh7b694402010-04-29 15:17:48 +00004729 /* Initialize the locking parameters */
4730 memset(&f, 0, sizeof(f));
4731 f.l_type = lockType;
4732 f.l_whence = SEEK_SET;
drh4bc79de2010-05-05 18:20:07 +00004733 if( lockMask==UNIX_SHM_C && lockType!=F_UNLCK ){
drh7b694402010-04-29 15:17:48 +00004734 lockOp = F_SETLKW;
drhd7490842010-04-30 15:54:46 +00004735 OSTRACE(("SHM-LOCK requesting blocking lock\n"));
drh7b694402010-04-29 15:17:48 +00004736 }else{
4737 lockOp = F_SETLK;
4738 }
4739
4740 /* Find the first bit in lockMask that is set */
4741 for(i=0, mask=0x01; mask!=0 && (lockMask&mask)==0; mask <<= 1, i++){}
4742 assert( mask!=0 );
4743 f.l_start = i+UNIX_SHM_BASE;
4744 f.l_len = 1;
4745
4746 /* Extend the locking range for each additional bit that is set */
4747 mask <<= 1;
4748 while( mask!=0 && (lockMask & mask)!=0 ){
4749 f.l_len++;
drh79e6c782010-04-30 02:13:26 +00004750 mask <<= 1;
drh7b694402010-04-29 15:17:48 +00004751 }
4752
4753 /* Verify that all bits set in lockMask are contiguous */
4754 assert( mask==0 || (lockMask & ~(mask | (mask-1)))==0 );
4755
4756 /* Acquire the system-level lock */
drh79e6c782010-04-30 02:13:26 +00004757 rc = fcntl(pFile->h, lockOp, &f);
4758 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drh7b694402010-04-29 15:17:48 +00004759
4760 /* Update the global lock state and do debug tracing */
4761#ifdef SQLITE_DEBUG
4762 OSTRACE(("SHM-LOCK "));
4763 if( rc==SQLITE_OK ){
4764 if( lockType==F_UNLCK ){
4765 OSTRACE(("unlock ok"));
4766 pFile->exclMask &= ~lockMask;
4767 pFile->sharedMask &= ~lockMask;
4768 }else if( lockType==F_RDLCK ){
4769 OSTRACE(("read-lock ok"));
4770 pFile->exclMask &= ~lockMask;
4771 pFile->sharedMask |= lockMask;
4772 }else{
4773 assert( lockType==F_WRLCK );
4774 OSTRACE(("write-lock ok"));
4775 pFile->exclMask |= lockMask;
4776 pFile->sharedMask &= ~lockMask;
4777 }
4778 }else{
4779 if( lockType==F_UNLCK ){
4780 OSTRACE(("unlock failed"));
4781 }else if( lockType==F_RDLCK ){
4782 OSTRACE(("read-lock failed"));
4783 }else{
4784 assert( lockType==F_WRLCK );
4785 OSTRACE(("write-lock failed"));
4786 }
4787 }
drhd7490842010-04-30 15:54:46 +00004788 OSTRACE((" - change requested %s - afterwards %s:%s\n",
drh7b694402010-04-29 15:17:48 +00004789 unixShmLockString(lockMask),
4790 unixShmLockString(pFile->sharedMask),
4791 unixShmLockString(pFile->exclMask)));
4792#endif
4793
4794 return rc;
4795}
4796
4797/*
4798** For connection p, unlock all of the locks identified by the unlockMask
4799** parameter.
4800*/
4801static int unixShmUnlock(
4802 unixShmFile *pFile, /* The underlying shared-memory file */
4803 unixShm *p, /* The connection to be unlocked */
4804 u8 unlockMask /* Mask of locks to be unlocked */
4805){
4806 int rc; /* Result code */
4807 unixShm *pX; /* For looping over all sibling connections */
4808 u8 allMask; /* Union of locks held by connections other than "p" */
4809
drh31cbbba2010-04-29 16:40:51 +00004810 /* Access to the unixShmFile object is serialized by the caller */
4811 assert( sqlite3_mutex_held(pFile->mutex) );
4812
drh7b694402010-04-29 15:17:48 +00004813 /* Compute locks held by sibling connections */
drhd7490842010-04-30 15:54:46 +00004814 allMask = 0;
drh7b694402010-04-29 15:17:48 +00004815 for(pX=pFile->pFirst; pX; pX=pX->pNext){
4816 if( pX==p ) continue;
dan4c97b532010-04-30 09:52:17 +00004817 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
drh7b694402010-04-29 15:17:48 +00004818 allMask |= pX->sharedMask;
4819 }
4820
4821 /* Unlock the system-level locks */
4822 if( (unlockMask & allMask)!=unlockMask ){
drh31cbbba2010-04-29 16:40:51 +00004823 rc = unixShmSystemLock(pFile, F_UNLCK, unlockMask & ~allMask);
drh7b694402010-04-29 15:17:48 +00004824 }else{
4825 rc = SQLITE_OK;
4826 }
4827
4828 /* Undo the local locks */
4829 if( rc==SQLITE_OK ){
4830 p->exclMask &= ~unlockMask;
4831 p->sharedMask &= ~unlockMask;
4832 }
4833 return rc;
4834}
4835
4836/*
4837** Get reader locks for connection p on all locks in the readMask parameter.
4838*/
4839static int unixShmSharedLock(
4840 unixShmFile *pFile, /* The underlying shared-memory file */
4841 unixShm *p, /* The connection to get the shared locks */
4842 u8 readMask /* Mask of shared locks to be acquired */
4843){
4844 int rc; /* Result code */
4845 unixShm *pX; /* For looping over all sibling connections */
4846 u8 allShared; /* Union of locks held by connections other than "p" */
4847
drh31cbbba2010-04-29 16:40:51 +00004848 /* Access to the unixShmFile object is serialized by the caller */
4849 assert( sqlite3_mutex_held(pFile->mutex) );
4850
drh7b694402010-04-29 15:17:48 +00004851 /* Find out which shared locks are already held by sibling connections.
4852 ** If any sibling already holds an exclusive lock, go ahead and return
4853 ** SQLITE_BUSY.
4854 */
drhd7490842010-04-30 15:54:46 +00004855 allShared = 0;
drh7b694402010-04-29 15:17:48 +00004856 for(pX=pFile->pFirst; pX; pX=pX->pNext){
4857 if( pX==p ) continue;
4858 if( (pX->exclMask & readMask)!=0 ) return SQLITE_BUSY;
4859 allShared |= pX->sharedMask;
4860 }
4861
4862 /* Get shared locks at the system level, if necessary */
4863 if( (~allShared) & readMask ){
drh31cbbba2010-04-29 16:40:51 +00004864 rc = unixShmSystemLock(pFile, F_RDLCK, readMask);
drh7b694402010-04-29 15:17:48 +00004865 }else{
4866 rc = SQLITE_OK;
4867 }
4868
4869 /* Get the local shared locks */
4870 if( rc==SQLITE_OK ){
4871 p->sharedMask |= readMask;
4872 }
4873 return rc;
4874}
4875
4876/*
4877** For connection p, get an exclusive lock on all locks identified in
4878** the writeMask parameter.
4879*/
4880static int unixShmExclusiveLock(
4881 unixShmFile *pFile, /* The underlying shared-memory file */
4882 unixShm *p, /* The connection to get the exclusive locks */
4883 u8 writeMask /* Mask of exclusive locks to be acquired */
4884){
4885 int rc; /* Result code */
4886 unixShm *pX; /* For looping over all sibling connections */
4887
drh31cbbba2010-04-29 16:40:51 +00004888 /* Access to the unixShmFile object is serialized by the caller */
4889 assert( sqlite3_mutex_held(pFile->mutex) );
4890
drh7b694402010-04-29 15:17:48 +00004891 /* Make sure no sibling connections hold locks that will block this
4892 ** lock. If any do, return SQLITE_BUSY right away.
4893 */
4894 for(pX=pFile->pFirst; pX; pX=pX->pNext){
4895 if( pX==p ) continue;
4896 if( (pX->exclMask & writeMask)!=0 ) return SQLITE_BUSY;
4897 if( (pX->sharedMask & writeMask)!=0 ) return SQLITE_BUSY;
4898 }
4899
4900 /* Get the exclusive locks at the system level. Then if successful
4901 ** also mark the local connection as being locked.
4902 */
drh31cbbba2010-04-29 16:40:51 +00004903 rc = unixShmSystemLock(pFile, F_WRLCK, writeMask);
drh7b694402010-04-29 15:17:48 +00004904 if( rc==SQLITE_OK ){
4905 p->sharedMask &= ~writeMask;
4906 p->exclMask |= writeMask;
4907 }
4908 return rc;
4909}
4910
4911/*
4912** Purge the unixShmFileList list of all entries with unixShmFile.nRef==0.
4913**
4914** This is not a VFS shared-memory method; it is a utility function called
4915** by VFS shared-memory methods.
4916*/
4917static void unixShmPurge(void){
4918 unixShmFile **pp;
4919 unixShmFile *p;
4920 assert( unixMutexHeld() );
4921 pp = &unixShmFileList;
4922 while( (p = *pp)!=0 ){
4923 if( p->nRef==0 ){
4924 if( p->mutex ) sqlite3_mutex_free(p->mutex);
4925 if( p->mutexBuf ) sqlite3_mutex_free(p->mutexBuf);
drh7b694402010-04-29 15:17:48 +00004926 if( p->h>=0 ) close(p->h);
4927 *pp = p->pNext;
4928 sqlite3_free(p);
4929 }else{
4930 pp = &p->pNext;
4931 }
4932 }
4933}
4934
4935/*
drh2d536e12010-05-01 20:17:30 +00004936** Open a shared-memory area. This particular implementation uses
4937** mmapped files.
4938**
4939** zName is a filename used to identify the shared-memory area. The
4940** implementation does not (and perhaps should not) use this name
4941** directly, but rather use it as a template for finding an appropriate
4942** name for the shared-memory storage. In this implementation, the
4943** string "-index" is appended to zName and used as the name of the
4944** mmapped file.
drh7b694402010-04-29 15:17:48 +00004945**
4946** When opening a new shared-memory file, if no other instances of that
4947** file are currently open, in this process or in other processes, then
4948** the file must be truncated to zero length or have its header cleared.
drhf2424c52010-04-26 00:04:55 +00004949*/
4950static int unixShmOpen(
4951 sqlite3_vfs *pVfs, /* The VFS */
drhe874d9e2010-05-07 20:02:23 +00004952 const char *zName, /* Name of the corresponding database file */
drhf2424c52010-04-26 00:04:55 +00004953 sqlite3_shm **pShm /* Write the unixShm object created here */
4954){
drh31cbbba2010-04-29 16:40:51 +00004955 struct unixShm *p = 0; /* The connection to be opened */
4956 struct unixShmFile *pFile = 0; /* The underlying mmapped file */
4957 int rc; /* Result code */
4958 struct unixFileId fid; /* Unix file identifier */
drh2d536e12010-05-01 20:17:30 +00004959 struct unixShmFile *pNew; /* Newly allocated pFile */
drh31cbbba2010-04-29 16:40:51 +00004960 struct stat sStat; /* Result from stat() an fstat() */
drh2d536e12010-05-01 20:17:30 +00004961 int nName; /* Size of zName in bytes */
drhf2424c52010-04-26 00:04:55 +00004962
drh2d536e12010-05-01 20:17:30 +00004963 /* Allocate space for the new sqlite3_shm object. Also speculatively
4964 ** allocate space for a new unixShmFile and filename.
4965 */
drhf2424c52010-04-26 00:04:55 +00004966 p = sqlite3_malloc( sizeof(*p) );
drhf2424c52010-04-26 00:04:55 +00004967 if( p==0 ) return SQLITE_NOMEM;
4968 memset(p, 0, sizeof(*p));
drh2d536e12010-05-01 20:17:30 +00004969 nName = strlen(zName);
drhe874d9e2010-05-07 20:02:23 +00004970 pNew = sqlite3_malloc( sizeof(*pFile) + nName + 15 );
drh2d536e12010-05-01 20:17:30 +00004971 if( pNew==0 ){
dan76ed3bc2010-05-03 17:18:24 +00004972 sqlite3_free(p);
4973 return SQLITE_NOMEM;
drh2d536e12010-05-01 20:17:30 +00004974 }
4975 memset(pNew, 0, sizeof(*pNew));
4976 pNew->zFilename = (char*)&pNew[1];
drhe874d9e2010-05-07 20:02:23 +00004977 sqlite3_snprintf(nName+10, pNew->zFilename, "%s-wal-index", zName);
drhf2424c52010-04-26 00:04:55 +00004978
drh31cbbba2010-04-29 16:40:51 +00004979 /* Look to see if there is an existing unixShmFile that can be used.
4980 ** If no matching unixShmFile currently exists, create a new one.
4981 */
drh7b694402010-04-29 15:17:48 +00004982 unixEnterMutex();
drh2d536e12010-05-01 20:17:30 +00004983 rc = stat(pNew->zFilename, &sStat);
drh7b694402010-04-29 15:17:48 +00004984 if( rc==0 ){
4985 memset(&fid, 0, sizeof(fid));
4986 fid.dev = sStat.st_dev;
4987 fid.ino = sStat.st_ino;
4988 for(pFile = unixShmFileList; pFile; pFile=pFile->pNext){
4989 if( memcmp(&pFile->fid, &fid, sizeof(fid))==0 ) break;
4990 }
4991 }
drh2d536e12010-05-01 20:17:30 +00004992 if( pFile ){
4993 sqlite3_free(pNew);
4994 }else{
4995 pFile = pNew;
4996 pNew = 0;
drh7b694402010-04-29 15:17:48 +00004997 pFile->h = -1;
4998 pFile->pNext = unixShmFileList;
4999 unixShmFileList = pFile;
5000
5001 pFile->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
5002 if( pFile->mutex==0 ){
5003 rc = SQLITE_NOMEM;
5004 goto shm_open_err;
5005 }
5006 pFile->mutexBuf = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
5007 if( pFile->mutexBuf==0 ){
5008 rc = SQLITE_NOMEM;
5009 goto shm_open_err;
5010 }
drh7b694402010-04-29 15:17:48 +00005011
drh2d536e12010-05-01 20:17:30 +00005012 pFile->h = open(pFile->zFilename, O_RDWR|O_CREAT, 0664);
drh7b694402010-04-29 15:17:48 +00005013 if( pFile->h<0 ){
dan87bfb512010-04-30 11:43:28 +00005014 rc = SQLITE_CANTOPEN_BKPT;
drh7b694402010-04-29 15:17:48 +00005015 goto shm_open_err;
5016 }
5017
5018 rc = fstat(pFile->h, &sStat);
5019 if( rc ){
dan87bfb512010-04-30 11:43:28 +00005020 rc = SQLITE_CANTOPEN_BKPT;
drh7b694402010-04-29 15:17:48 +00005021 goto shm_open_err;
5022 }
5023 pFile->fid.dev = sStat.st_dev;
5024 pFile->fid.ino = sStat.st_ino;
drh31cbbba2010-04-29 16:40:51 +00005025
5026 /* Check to see if another process is holding the dead-man switch.
5027 ** If not, truncate the file to zero length.
5028 */
drh31cbbba2010-04-29 16:40:51 +00005029 if( unixShmSystemLock(pFile, F_WRLCK, UNIX_SHM_DMS)==SQLITE_OK ){
5030 if( ftruncate(pFile->h, 0) ){
5031 rc = SQLITE_IOERR;
drh7b694402010-04-29 15:17:48 +00005032 }
5033 }
drhd7490842010-04-30 15:54:46 +00005034 if( rc==SQLITE_OK ){
5035 rc = unixShmSystemLock(pFile, F_RDLCK, UNIX_SHM_DMS);
5036 }
drhd7490842010-04-30 15:54:46 +00005037 if( rc ) goto shm_open_err;
drhf2424c52010-04-26 00:04:55 +00005038 }
5039
drh31cbbba2010-04-29 16:40:51 +00005040 /* Make the new connection a child of the unixShmFile */
drh7b694402010-04-29 15:17:48 +00005041 p->pFile = pFile;
5042 p->pNext = pFile->pFirst;
5043#ifdef SQLITE_DEBUG
5044 p->id = pFile->nextShmId++;
5045#endif
5046 pFile->pFirst = p;
5047 pFile->nRef++;
5048 *pShm = (sqlite3_shm*)p;
5049 unixLeaveMutex();
drhf2424c52010-04-26 00:04:55 +00005050 return SQLITE_OK;
5051
drh31cbbba2010-04-29 16:40:51 +00005052 /* Jump here on any error */
drhf2424c52010-04-26 00:04:55 +00005053shm_open_err:
dan76ed3bc2010-05-03 17:18:24 +00005054 unixShmPurge(); /* This call frees pFile if required */
drh7b694402010-04-29 15:17:48 +00005055 sqlite3_free(p);
drh2d536e12010-05-01 20:17:30 +00005056 sqlite3_free(pNew);
drhf2424c52010-04-26 00:04:55 +00005057 *pShm = 0;
drh7b694402010-04-29 15:17:48 +00005058 unixLeaveMutex();
drhf2424c52010-04-26 00:04:55 +00005059 return rc;
5060}
5061
5062/*
drh2d536e12010-05-01 20:17:30 +00005063** Close a connection to shared-memory. Delete the underlying
5064** storage if deleteFlag is true.
drh7b694402010-04-29 15:17:48 +00005065*/
drh1fbe0f22010-05-03 16:30:27 +00005066static int unixShmClose(
5067 sqlite3_vfs *pVfs, /* The VFS */
5068 sqlite3_shm *pSharedMem, /* The shared-memory to be closed */
5069 int deleteFlag /* Delete after closing if true */
5070){
drh7b694402010-04-29 15:17:48 +00005071 unixShm *p; /* The connection to be closed */
5072 unixShmFile *pFile; /* The underlying shared-memory file */
5073 unixShm **pp; /* For looping over sibling connections */
drh7b694402010-04-29 15:17:48 +00005074
drh1fbe0f22010-05-03 16:30:27 +00005075 UNUSED_PARAMETER(pVfs);
drh7ed91f22010-04-29 22:34:07 +00005076 if( pSharedMem==0 ) return SQLITE_OK;
drh7b694402010-04-29 15:17:48 +00005077 p = (struct unixShm*)pSharedMem;
5078 pFile = p->pFile;
5079
5080 /* Verify that the connection being closed holds no locks */
5081 assert( p->exclMask==0 );
5082 assert( p->sharedMask==0 );
5083
drh7b694402010-04-29 15:17:48 +00005084 /* Remove connection p from the set of connections associated with pFile */
5085 sqlite3_mutex_enter(pFile->mutex);
5086 for(pp=&pFile->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
5087 *pp = p->pNext;
drh7b694402010-04-29 15:17:48 +00005088
5089 /* Free the connection p */
5090 sqlite3_free(p);
5091 sqlite3_mutex_leave(pFile->mutex);
5092
5093 /* If pFile->nRef has reached 0, then close the underlying
5094 ** shared-memory file, too */
dane93808d2010-04-30 10:06:09 +00005095 unixEnterMutex();
5096 assert( pFile->nRef>0 );
5097 pFile->nRef--;
5098 if( pFile->nRef==0 ){
drh2d536e12010-05-01 20:17:30 +00005099 if( deleteFlag ) unlink(pFile->zFilename);
drh7b694402010-04-29 15:17:48 +00005100 unixShmPurge();
5101 }
dane93808d2010-04-30 10:06:09 +00005102 unixLeaveMutex();
5103
drh7b694402010-04-29 15:17:48 +00005104 return SQLITE_OK;
5105}
5106
5107/*
drh5530b762010-04-30 14:39:50 +00005108** Query and/or changes the size of the underlying storage for
5109** a shared-memory segment. The reqSize parameter is the new size
5110** of the underlying storage, or -1 to do just a query. The size
5111** of the underlying storage (after resizing if resizing occurs) is
5112** written into pNewSize.
drhaf75c862010-04-27 11:49:27 +00005113**
drh5530b762010-04-30 14:39:50 +00005114** This routine does not (necessarily) change the size of the mapping
5115** of the underlying storage into memory. Use xShmGet() to change
5116** the mapping size.
5117**
5118** The reqSize parameter is the minimum size requested. The implementation
5119** is free to expand the storage to some larger amount if it chooses.
drhf2424c52010-04-26 00:04:55 +00005120*/
5121static int unixShmSize(
drh1fbe0f22010-05-03 16:30:27 +00005122 sqlite3_vfs *pVfs, /* The VFS */
drhf2424c52010-04-26 00:04:55 +00005123 sqlite3_shm *pSharedMem, /* Pointer returned by unixShmOpen() */
5124 int reqSize, /* Requested size. -1 for query only */
drh5530b762010-04-30 14:39:50 +00005125 int *pNewSize /* Write new size here */
5126){
5127 unixShm *p = (unixShm*)pSharedMem;
5128 unixShmFile *pFile = p->pFile;
5129 int rc = SQLITE_OK;
5130 struct stat sStat;
5131
drh1fbe0f22010-05-03 16:30:27 +00005132 UNUSED_PARAMETER(pVfs);
5133
drh5530b762010-04-30 14:39:50 +00005134 if( reqSize>=0 ){
5135 reqSize = (reqSize + SQLITE_UNIX_SHM_INCR - 1)/SQLITE_UNIX_SHM_INCR;
5136 reqSize *= SQLITE_UNIX_SHM_INCR;
5137 rc = ftruncate(pFile->h, reqSize);
5138 }
5139 if( fstat(pFile->h, &sStat)==0 ){
5140 *pNewSize = (int)sStat.st_size;
5141 }else{
5142 *pNewSize = 0;
5143 rc = SQLITE_IOERR;
5144 }
5145 return rc;
5146}
5147
5148
5149/*
5150** Map the shared storage into memory. The minimum size of the
5151** mapping should be reqMapSize if reqMapSize is positive. If
5152** reqMapSize is zero or negative, the implementation can choose
5153** whatever mapping size is convenient.
5154**
5155** *ppBuf is made to point to the memory which is a mapping of the
drh77b95a32010-05-01 17:50:37 +00005156** underlying storage. A mutex is acquired to prevent other threads
5157** from running while *ppBuf is in use in order to prevent other threads
5158** remapping *ppBuf out from under this thread. The unixShmRelease()
5159** call will release the mutex. However, if the lock state is CHECKPOINT,
5160** the mutex is not acquired because CHECKPOINT will never remap the
5161** buffer. RECOVER might remap, though, so CHECKPOINT will acquire
5162** the mutex if and when it promotes to RECOVER.
5163**
5164** RECOVER needs to be atomic. The same mutex that prevents *ppBuf from
5165** being remapped also prevents more than one thread from being in
5166** RECOVER at a time. But, RECOVER sometimes wants to remap itself.
5167** To prevent RECOVER from losing its lock while remapping, the
5168** mutex is not released by unixShmRelease() when in RECOVER.
drh5530b762010-04-30 14:39:50 +00005169**
5170** *pNewMapSize is set to the size of the mapping.
5171**
5172** *ppBuf and *pNewMapSize might be NULL and zero if no space has
5173** yet been allocated to the underlying storage.
5174*/
5175static int unixShmGet(
drh1fbe0f22010-05-03 16:30:27 +00005176 sqlite3_vfs *pVfs, /* The VFS */
drh5530b762010-04-30 14:39:50 +00005177 sqlite3_shm *pSharedMem, /* Pointer returned by unixShmOpen() */
5178 int reqMapSize, /* Requested size of mapping. -1 means don't care */
5179 int *pNewMapSize, /* Write new size of mapping here */
5180 void **ppBuf /* Write mapping buffer origin here */
drhf2424c52010-04-26 00:04:55 +00005181){
drh7b694402010-04-29 15:17:48 +00005182 unixShm *p = (unixShm*)pSharedMem;
5183 unixShmFile *pFile = p->pFile;
drhf2424c52010-04-26 00:04:55 +00005184 int rc = SQLITE_OK;
5185
drh77b95a32010-05-01 17:50:37 +00005186 if( p->lockState!=SQLITE_SHM_CHECKPOINT && p->hasMutexBuf==0 ){
drhbee6f4e2010-05-01 17:57:36 +00005187 assert( sqlite3_mutex_notheld(pFile->mutex) );
drh6dea3242010-04-30 17:47:51 +00005188 sqlite3_mutex_enter(pFile->mutexBuf);
5189 p->hasMutexBuf = 1;
5190 }
drh7b694402010-04-29 15:17:48 +00005191 sqlite3_mutex_enter(pFile->mutex);
drh5530b762010-04-30 14:39:50 +00005192 if( pFile->szMap==0 || reqMapSize>pFile->szMap ){
5193 int actualSize;
drh1fbe0f22010-05-03 16:30:27 +00005194 if( unixShmSize(pVfs, pSharedMem, -1, &actualSize)==SQLITE_OK
drh5530b762010-04-30 14:39:50 +00005195 && reqMapSize<actualSize
5196 ){
5197 reqMapSize = actualSize;
drhf2424c52010-04-26 00:04:55 +00005198 }
drh5530b762010-04-30 14:39:50 +00005199 if( pFile->pMMapBuf ){
5200 munmap(pFile->pMMapBuf, pFile->szMap);
5201 }
5202 pFile->pMMapBuf = mmap(0, reqMapSize, PROT_READ|PROT_WRITE, MAP_SHARED,
5203 pFile->h, 0);
5204 pFile->szMap = pFile->pMMapBuf ? reqMapSize : 0;
drhf2424c52010-04-26 00:04:55 +00005205 }
drh5530b762010-04-30 14:39:50 +00005206 *pNewMapSize = pFile->szMap;
drh7b694402010-04-29 15:17:48 +00005207 *ppBuf = pFile->pMMapBuf;
5208 sqlite3_mutex_leave(pFile->mutex);
drhf2424c52010-04-26 00:04:55 +00005209 return rc;
5210}
5211
5212/*
drhaf75c862010-04-27 11:49:27 +00005213** Release the lock held on the shared memory segment to that other
5214** threads are free to resize it if necessary.
drh77b95a32010-05-01 17:50:37 +00005215**
5216** If the lock is not currently held, this routine is a harmless no-op.
5217**
5218** If the shared-memory object is in lock state RECOVER, then we do not
5219** really want to release the lock, so in that case too, this routine
5220** is a no-op.
drhaf75c862010-04-27 11:49:27 +00005221*/
drh1fbe0f22010-05-03 16:30:27 +00005222static int unixShmRelease(sqlite3_vfs *pVfs, sqlite3_shm *pSharedMem){
drh7b694402010-04-29 15:17:48 +00005223 unixShm *p = (unixShm*)pSharedMem;
drh1fbe0f22010-05-03 16:30:27 +00005224 UNUSED_PARAMETER(pVfs);
drh77b95a32010-05-01 17:50:37 +00005225 if( p->hasMutexBuf && p->lockState!=SQLITE_SHM_RECOVER ){
drhe874d9e2010-05-07 20:02:23 +00005226 assert( sqlite3_mutex_notheld(p->pFile->mutex) );
5227 sqlite3_mutex_leave(p->pFile->mutexBuf);
drh6dea3242010-04-30 17:47:51 +00005228 p->hasMutexBuf = 0;
5229 }
drhaf75c862010-04-27 11:49:27 +00005230 return SQLITE_OK;
5231}
5232
drh400df2e2010-04-30 16:48:19 +00005233/*
5234** Symbolic names for LOCK states used for debugging.
5235*/
5236#ifdef SQLITE_DEBUG
5237static const char *azLkName[] = {
5238 "UNLOCK",
5239 "READ",
5240 "READ_FULL",
5241 "WRITE",
5242 "PENDING",
5243 "CHECKPOINT",
5244 "RECOVER"
5245};
5246#endif
drh7b694402010-04-29 15:17:48 +00005247
5248
drhaf75c862010-04-27 11:49:27 +00005249/*
drh7b694402010-04-29 15:17:48 +00005250** Change the lock state for a shared-memory segment.
drhf2424c52010-04-26 00:04:55 +00005251*/
5252static int unixShmLock(
drh1fbe0f22010-05-03 16:30:27 +00005253 sqlite3_vfs *pVfs, /* The VFS */
drhf2424c52010-04-26 00:04:55 +00005254 sqlite3_shm *pSharedMem, /* Pointer from unixShmOpen() */
drh7b694402010-04-29 15:17:48 +00005255 int desiredLock, /* One of SQLITE_SHM_xxxxx locking states */
5256 int *pGotLock /* The lock you actually got */
drhf2424c52010-04-26 00:04:55 +00005257){
drh7b694402010-04-29 15:17:48 +00005258 unixShm *p = (unixShm*)pSharedMem;
5259 unixShmFile *pFile = p->pFile;
5260 int rc = SQLITE_PROTOCOL;
5261
drh1fbe0f22010-05-03 16:30:27 +00005262 UNUSED_PARAMETER(pVfs);
5263
drh7b694402010-04-29 15:17:48 +00005264 /* Note that SQLITE_SHM_READ_FULL and SQLITE_SHM_PENDING are never
5265 ** directly requested; they are side effects from requesting
5266 ** SQLITE_SHM_READ and SQLITE_SHM_CHECKPOINT, respectively.
5267 */
drhccd13d12010-05-05 19:09:49 +00005268 assert( desiredLock==SQLITE_SHM_UNLOCK
drh7b694402010-04-29 15:17:48 +00005269 || desiredLock==SQLITE_SHM_READ
5270 || desiredLock==SQLITE_SHM_WRITE
5271 || desiredLock==SQLITE_SHM_CHECKPOINT
5272 || desiredLock==SQLITE_SHM_RECOVER );
5273
5274 /* Return directly if this is just a lock state query, or if
5275 ** the connection is already in the desired locking state.
5276 */
drhccd13d12010-05-05 19:09:49 +00005277 if( desiredLock==p->lockState
drh7b694402010-04-29 15:17:48 +00005278 || (desiredLock==SQLITE_SHM_READ && p->lockState==SQLITE_SHM_READ_FULL)
5279 ){
drh400df2e2010-04-30 16:48:19 +00005280 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s and got %s\n",
5281 p->id, getpid(), azLkName[desiredLock], azLkName[p->lockState]));
drh7ed91f22010-04-29 22:34:07 +00005282 if( pGotLock ) *pGotLock = p->lockState;
drh7b694402010-04-29 15:17:48 +00005283 return SQLITE_OK;
5284 }
5285
drh400df2e2010-04-30 16:48:19 +00005286 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s->%s\n",
5287 p->id, getpid(), azLkName[p->lockState], azLkName[desiredLock]));
drh77b95a32010-05-01 17:50:37 +00005288
5289 if( desiredLock==SQLITE_SHM_RECOVER && !p->hasMutexBuf ){
drhbee6f4e2010-05-01 17:57:36 +00005290 assert( sqlite3_mutex_notheld(pFile->mutex) );
drh77b95a32010-05-01 17:50:37 +00005291 sqlite3_mutex_enter(pFile->mutexBuf);
5292 p->hasMutexBuf = 1;
5293 }
drh7b694402010-04-29 15:17:48 +00005294 sqlite3_mutex_enter(pFile->mutex);
5295 switch( desiredLock ){
5296 case SQLITE_SHM_UNLOCK: {
5297 assert( p->lockState!=SQLITE_SHM_RECOVER );
5298 unixShmUnlock(pFile, p, UNIX_SHM_A|UNIX_SHM_B|UNIX_SHM_C|UNIX_SHM_D);
5299 rc = SQLITE_OK;
5300 p->lockState = SQLITE_SHM_UNLOCK;
5301 break;
5302 }
5303 case SQLITE_SHM_READ: {
5304 if( p->lockState==SQLITE_SHM_UNLOCK ){
5305 int nAttempt;
5306 rc = SQLITE_BUSY;
5307 assert( p->lockState==SQLITE_SHM_UNLOCK );
5308 for(nAttempt=0; nAttempt<5 && rc==SQLITE_BUSY; nAttempt++){
5309 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A|UNIX_SHM_B);
5310 if( rc==SQLITE_BUSY ){
5311 rc = unixShmSharedLock(pFile, p, UNIX_SHM_D);
5312 if( rc==SQLITE_OK ){
drh4bc79de2010-05-05 18:20:07 +00005313 p->lockState = SQLITE_SHM_READ_FULL;
drh7b694402010-04-29 15:17:48 +00005314 }
5315 }else{
5316 unixShmUnlock(pFile, p, UNIX_SHM_B);
drh4bc79de2010-05-05 18:20:07 +00005317 p->lockState = SQLITE_SHM_READ;
drh7b694402010-04-29 15:17:48 +00005318 }
5319 }
drhccd13d12010-05-05 19:09:49 +00005320 }else{
5321 assert( p->lockState==SQLITE_SHM_WRITE
5322 || p->lockState==SQLITE_SHM_RECOVER );
dan78daa5a2010-04-30 16:38:59 +00005323 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A);
drh7b694402010-04-29 15:17:48 +00005324 unixShmUnlock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
drh4bc79de2010-05-05 18:20:07 +00005325 p->lockState = SQLITE_SHM_READ;
drh7b694402010-04-29 15:17:48 +00005326 }
5327 break;
5328 }
5329 case SQLITE_SHM_WRITE: {
5330 assert( p->lockState==SQLITE_SHM_READ
5331 || p->lockState==SQLITE_SHM_READ_FULL );
5332 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
5333 if( rc==SQLITE_OK ){
5334 p->lockState = SQLITE_SHM_WRITE;
5335 }
5336 break;
5337 }
5338 case SQLITE_SHM_CHECKPOINT: {
5339 assert( p->lockState==SQLITE_SHM_UNLOCK
5340 || p->lockState==SQLITE_SHM_PENDING
dan65be0d82010-05-06 18:48:27 +00005341 );
drh7b694402010-04-29 15:17:48 +00005342 if( p->lockState==SQLITE_SHM_UNLOCK ){
5343 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_B|UNIX_SHM_C);
5344 if( rc==SQLITE_OK ){
5345 p->lockState = SQLITE_SHM_PENDING;
5346 }
5347 }
5348 if( p->lockState==SQLITE_SHM_PENDING ){
5349 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_A);
5350 if( rc==SQLITE_OK ){
5351 p->lockState = SQLITE_SHM_CHECKPOINT;
5352 }
5353 }
5354 break;
5355 }
5356 default: {
5357 assert( desiredLock==SQLITE_SHM_RECOVER );
5358 assert( p->lockState==SQLITE_SHM_READ
5359 || p->lockState==SQLITE_SHM_READ_FULL
dan65be0d82010-05-06 18:48:27 +00005360 );
drh77b95a32010-05-01 17:50:37 +00005361 assert( sqlite3_mutex_held(pFile->mutexBuf) );
drh4bc79de2010-05-05 18:20:07 +00005362 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C);
drh7b694402010-04-29 15:17:48 +00005363 if( rc==SQLITE_OK ){
5364 p->lockState = SQLITE_SHM_RECOVER;
5365 }
5366 break;
5367 }
5368 }
5369 sqlite3_mutex_leave(pFile->mutex);
drh400df2e2010-04-30 16:48:19 +00005370 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %s\n",
5371 p->id, getpid(), azLkName[p->lockState]));
drh7ed91f22010-04-29 22:34:07 +00005372 if( pGotLock ) *pGotLock = p->lockState;
drh7b694402010-04-29 15:17:48 +00005373 return rc;
drhf2424c52010-04-26 00:04:55 +00005374}
5375
dan5cf53532010-05-01 16:40:20 +00005376#else
5377# define unixShmOpen 0
5378# define unixShmSize 0
5379# define unixShmGet 0
5380# define unixShmRelease 0
5381# define unixShmLock 0
5382# define unixShmClose 0
dan5cf53532010-05-01 16:40:20 +00005383#endif /* #ifndef SQLITE_OMIT_WAL */
drhf2424c52010-04-26 00:04:55 +00005384
5385/*
drh734c9862008-11-28 15:37:20 +00005386************************ End of sqlite3_vfs methods ***************************
5387******************************************************************************/
5388
drh715ff302008-12-03 22:32:44 +00005389/******************************************************************************
5390************************** Begin Proxy Locking ********************************
5391**
5392** Proxy locking is a "uber-locking-method" in this sense: It uses the
5393** other locking methods on secondary lock files. Proxy locking is a
5394** meta-layer over top of the primitive locking implemented above. For
5395** this reason, the division that implements of proxy locking is deferred
5396** until late in the file (here) after all of the other I/O methods have
5397** been defined - so that the primitive locking methods are available
5398** as services to help with the implementation of proxy locking.
5399**
5400****
5401**
5402** The default locking schemes in SQLite use byte-range locks on the
5403** database file to coordinate safe, concurrent access by multiple readers
5404** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5405** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5406** as POSIX read & write locks over fixed set of locations (via fsctl),
5407** on AFP and SMB only exclusive byte-range locks are available via fsctl
5408** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5409** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5410** address in the shared range is taken for a SHARED lock, the entire
5411** shared range is taken for an EXCLUSIVE lock):
5412**
5413** PENDING_BYTE 0x40000000
5414** RESERVED_BYTE 0x40000001
5415** SHARED_RANGE 0x40000002 -> 0x40000200
5416**
5417** This works well on the local file system, but shows a nearly 100x
5418** slowdown in read performance on AFP because the AFP client disables
5419** the read cache when byte-range locks are present. Enabling the read
5420** cache exposes a cache coherency problem that is present on all OS X
5421** supported network file systems. NFS and AFP both observe the
5422** close-to-open semantics for ensuring cache coherency
5423** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5424** address the requirements for concurrent database access by multiple
5425** readers and writers
5426** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5427**
5428** To address the performance and cache coherency issues, proxy file locking
5429** changes the way database access is controlled by limiting access to a
5430** single host at a time and moving file locks off of the database file
5431** and onto a proxy file on the local file system.
5432**
5433**
5434** Using proxy locks
5435** -----------------
5436**
5437** C APIs
5438**
5439** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5440** <proxy_path> | ":auto:");
5441** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5442**
5443**
5444** SQL pragmas
5445**
5446** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5447** PRAGMA [database.]lock_proxy_file
5448**
5449** Specifying ":auto:" means that if there is a conch file with a matching
5450** host ID in it, the proxy path in the conch file will be used, otherwise
5451** a proxy path based on the user's temp dir
5452** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5453** actual proxy file name is generated from the name and path of the
5454** database file. For example:
5455**
5456** For database path "/Users/me/foo.db"
5457** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5458**
5459** Once a lock proxy is configured for a database connection, it can not
5460** be removed, however it may be switched to a different proxy path via
5461** the above APIs (assuming the conch file is not being held by another
5462** connection or process).
5463**
5464**
5465** How proxy locking works
5466** -----------------------
5467**
5468** Proxy file locking relies primarily on two new supporting files:
5469**
5470** * conch file to limit access to the database file to a single host
5471** at a time
5472**
5473** * proxy file to act as a proxy for the advisory locks normally
5474** taken on the database
5475**
5476** The conch file - to use a proxy file, sqlite must first "hold the conch"
5477** by taking an sqlite-style shared lock on the conch file, reading the
5478** contents and comparing the host's unique host ID (see below) and lock
5479** proxy path against the values stored in the conch. The conch file is
5480** stored in the same directory as the database file and the file name
5481** is patterned after the database file name as ".<databasename>-conch".
5482** If the conch file does not exist, or it's contents do not match the
5483** host ID and/or proxy path, then the lock is escalated to an exclusive
5484** lock and the conch file contents is updated with the host ID and proxy
5485** path and the lock is downgraded to a shared lock again. If the conch
5486** is held by another process (with a shared lock), the exclusive lock
5487** will fail and SQLITE_BUSY is returned.
5488**
5489** The proxy file - a single-byte file used for all advisory file locks
5490** normally taken on the database file. This allows for safe sharing
5491** of the database file for multiple readers and writers on the same
5492** host (the conch ensures that they all use the same local lock file).
5493**
drh715ff302008-12-03 22:32:44 +00005494** Requesting the lock proxy does not immediately take the conch, it is
5495** only taken when the first request to lock database file is made.
5496** This matches the semantics of the traditional locking behavior, where
5497** opening a connection to a database file does not take a lock on it.
5498** The shared lock and an open file descriptor are maintained until
5499** the connection to the database is closed.
5500**
5501** The proxy file and the lock file are never deleted so they only need
5502** to be created the first time they are used.
5503**
5504** Configuration options
5505** ---------------------
5506**
5507** SQLITE_PREFER_PROXY_LOCKING
5508**
5509** Database files accessed on non-local file systems are
5510** automatically configured for proxy locking, lock files are
5511** named automatically using the same logic as
5512** PRAGMA lock_proxy_file=":auto:"
5513**
5514** SQLITE_PROXY_DEBUG
5515**
5516** Enables the logging of error messages during host id file
5517** retrieval and creation
5518**
drh715ff302008-12-03 22:32:44 +00005519** LOCKPROXYDIR
5520**
5521** Overrides the default directory used for lock proxy files that
5522** are named automatically via the ":auto:" setting
5523**
5524** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5525**
5526** Permissions to use when creating a directory for storing the
5527** lock proxy files, only used when LOCKPROXYDIR is not set.
5528**
5529**
5530** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5531** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5532** force proxy locking to be used for every database file opened, and 0
5533** will force automatic proxy locking to be disabled for all database
5534** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5535** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5536*/
5537
5538/*
5539** Proxy locking is only available on MacOSX
5540*/
drhd2cb50b2009-01-09 21:41:17 +00005541#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005542
drh715ff302008-12-03 22:32:44 +00005543/*
5544** The proxyLockingContext has the path and file structures for the remote
5545** and local proxy files in it
5546*/
5547typedef struct proxyLockingContext proxyLockingContext;
5548struct proxyLockingContext {
5549 unixFile *conchFile; /* Open conch file */
5550 char *conchFilePath; /* Name of the conch file */
5551 unixFile *lockProxy; /* Open proxy lock file */
5552 char *lockProxyPath; /* Name of the proxy lock file */
5553 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005554 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005555 void *oldLockingContext; /* Original lockingcontext to restore on close */
5556 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5557};
5558
drh7ed97b92010-01-20 13:07:21 +00005559/*
5560** The proxy lock file path for the database at dbPath is written into lPath,
5561** which must point to valid, writable memory large enough for a maxLen length
5562** file path.
drh715ff302008-12-03 22:32:44 +00005563*/
drh715ff302008-12-03 22:32:44 +00005564static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5565 int len;
5566 int dbLen;
5567 int i;
5568
5569#ifdef LOCKPROXYDIR
5570 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5571#else
5572# ifdef _CS_DARWIN_USER_TEMP_DIR
5573 {
drh7ed97b92010-01-20 13:07:21 +00005574 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
5575 OSTRACE4("GETLOCKPATH failed %s errno=%d pid=%d\n",
5576 lPath, errno, getpid());
5577 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005578 }
drh7ed97b92010-01-20 13:07:21 +00005579 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005580 }
5581# else
5582 len = strlcpy(lPath, "/tmp/", maxLen);
5583# endif
5584#endif
5585
5586 if( lPath[len-1]!='/' ){
5587 len = strlcat(lPath, "/", maxLen);
5588 }
5589
5590 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005591 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00005592 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
5593 char c = dbPath[i];
5594 lPath[i+len] = (c=='/')?'_':c;
5595 }
5596 lPath[i+len]='\0';
5597 strlcat(lPath, ":auto:", maxLen);
drh7ed97b92010-01-20 13:07:21 +00005598 OSTRACE3("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid());
drh715ff302008-12-03 22:32:44 +00005599 return SQLITE_OK;
5600}
5601
drh7ed97b92010-01-20 13:07:21 +00005602/*
5603 ** Creates the lock file and any missing directories in lockPath
5604 */
5605static int proxyCreateLockPath(const char *lockPath){
5606 int i, len;
5607 char buf[MAXPATHLEN];
5608 int start = 0;
5609
5610 assert(lockPath!=NULL);
5611 /* try to create all the intermediate directories */
5612 len = (int)strlen(lockPath);
5613 buf[0] = lockPath[0];
5614 for( i=1; i<len; i++ ){
5615 if( lockPath[i] == '/' && (i - start > 0) ){
5616 /* only mkdir if leaf dir != "." or "/" or ".." */
5617 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5618 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5619 buf[i]='\0';
5620 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5621 int err=errno;
5622 if( err!=EEXIST ) {
5623 OSTRACE5("CREATELOCKPATH FAILED creating %s, "
5624 "'%s' proxy lock path=%s pid=%d\n",
5625 buf, strerror(err), lockPath, getpid());
5626 return err;
5627 }
5628 }
5629 }
5630 start=i+1;
5631 }
5632 buf[i] = lockPath[i];
5633 }
5634 OSTRACE3("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid());
5635 return 0;
5636}
5637
drh715ff302008-12-03 22:32:44 +00005638/*
5639** Create a new VFS file descriptor (stored in memory obtained from
5640** sqlite3_malloc) and open the file named "path" in the file descriptor.
5641**
5642** The caller is responsible not only for closing the file descriptor
5643** but also for freeing the memory associated with the file descriptor.
5644*/
drh7ed97b92010-01-20 13:07:21 +00005645static int proxyCreateUnixFile(
5646 const char *path, /* path for the new unixFile */
5647 unixFile **ppFile, /* unixFile created and returned by ref */
5648 int islockfile /* if non zero missing dirs will be created */
5649) {
5650 int fd = -1;
5651 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005652 unixFile *pNew;
5653 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005654 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005655 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005656 int terrno = 0;
5657 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005658
drh7ed97b92010-01-20 13:07:21 +00005659 /* 1. first try to open/create the file
5660 ** 2. if that fails, and this is a lock file (not-conch), try creating
5661 ** the parent directories and then try again.
5662 ** 3. if that fails, try to open the file read-only
5663 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5664 */
5665 pUnused = findReusableFd(path, openFlags);
5666 if( pUnused ){
5667 fd = pUnused->fd;
5668 }else{
5669 pUnused = sqlite3_malloc(sizeof(*pUnused));
5670 if( !pUnused ){
5671 return SQLITE_NOMEM;
5672 }
5673 }
5674 if( fd<0 ){
5675 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5676 terrno = errno;
5677 if( fd<0 && errno==ENOENT && islockfile ){
5678 if( proxyCreateLockPath(path) == SQLITE_OK ){
5679 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5680 }
5681 }
5682 }
5683 if( fd<0 ){
5684 openFlags = O_RDONLY;
5685 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5686 terrno = errno;
5687 }
5688 if( fd<0 ){
5689 if( islockfile ){
5690 return SQLITE_BUSY;
5691 }
5692 switch (terrno) {
5693 case EACCES:
5694 return SQLITE_PERM;
5695 case EIO:
5696 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5697 default:
drh9978c972010-02-23 17:36:32 +00005698 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005699 }
5700 }
5701
5702 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5703 if( pNew==NULL ){
5704 rc = SQLITE_NOMEM;
5705 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005706 }
5707 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005708 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005709 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005710 pUnused->fd = fd;
5711 pUnused->flags = openFlags;
5712 pNew->pUnused = pUnused;
5713
5714 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5715 if( rc==SQLITE_OK ){
5716 *ppFile = pNew;
5717 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005718 }
drh7ed97b92010-01-20 13:07:21 +00005719end_create_proxy:
5720 close(fd); /* silently leak fd if error, we're already in error */
5721 sqlite3_free(pNew);
5722 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005723 return rc;
5724}
5725
drh7ed97b92010-01-20 13:07:21 +00005726#ifdef SQLITE_TEST
5727/* simulate multiple hosts by creating unique hostid file paths */
5728int sqlite3_hostid_num = 0;
5729#endif
5730
5731#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5732
5733/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5734** bytes of writable memory.
5735*/
5736static int proxyGetHostID(unsigned char *pHostID, int *pError){
5737 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5738
5739 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5740 memset(pHostID, 0, PROXY_HOSTIDLEN);
5741 if( gethostuuid(pHostID, &timeout) ){
5742 int err = errno;
5743 if( pError ){
5744 *pError = err;
5745 }
5746 return SQLITE_IOERR;
5747 }
5748#ifdef SQLITE_TEST
5749 /* simulate multiple hosts by creating unique hostid file paths */
5750 if( sqlite3_hostid_num != 0){
5751 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5752 }
5753#endif
5754
5755 return SQLITE_OK;
5756}
5757
5758/* The conch file contains the header, host id and lock file path
5759 */
5760#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5761#define PROXY_HEADERLEN 1 /* conch file header length */
5762#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5763#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5764
5765/*
5766** Takes an open conch file, copies the contents to a new path and then moves
5767** it back. The newly created file's file descriptor is assigned to the
5768** conch file structure and finally the original conch file descriptor is
5769** closed. Returns zero if successful.
5770*/
5771static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5772 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5773 unixFile *conchFile = pCtx->conchFile;
5774 char tPath[MAXPATHLEN];
5775 char buf[PROXY_MAXCONCHLEN];
5776 char *cPath = pCtx->conchFilePath;
5777 size_t readLen = 0;
5778 size_t pathLen = 0;
5779 char errmsg[64] = "";
5780 int fd = -1;
5781 int rc = -1;
5782
5783 /* create a new path by replace the trailing '-conch' with '-break' */
5784 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5785 if( pathLen>MAXPATHLEN || pathLen<6 ||
5786 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5787 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5788 goto end_breaklock;
5789 }
5790 /* read the conch content */
5791 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5792 if( readLen<PROXY_PATHINDEX ){
5793 sprintf(errmsg, "read error (len %d)", (int)readLen);
5794 goto end_breaklock;
5795 }
5796 /* write it out to the temporary break file */
5797 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5798 if( fd<0 ){
5799 sprintf(errmsg, "create failed (%d)", errno);
5800 goto end_breaklock;
5801 }
5802 if( pwrite(fd, buf, readLen, 0) != readLen ){
5803 sprintf(errmsg, "write failed (%d)", errno);
5804 goto end_breaklock;
5805 }
5806 if( rename(tPath, cPath) ){
5807 sprintf(errmsg, "rename failed (%d)", errno);
5808 goto end_breaklock;
5809 }
5810 rc = 0;
5811 fprintf(stderr, "broke stale lock on %s\n", cPath);
5812 close(conchFile->h);
5813 conchFile->h = fd;
5814 conchFile->openFlags = O_RDWR | O_CREAT;
5815
5816end_breaklock:
5817 if( rc ){
5818 if( fd>=0 ){
5819 unlink(tPath);
5820 close(fd);
5821 }
5822 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5823 }
5824 return rc;
5825}
5826
5827/* Take the requested lock on the conch file and break a stale lock if the
5828** host id matches.
5829*/
5830static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5831 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5832 unixFile *conchFile = pCtx->conchFile;
5833 int rc = SQLITE_OK;
5834 int nTries = 0;
5835 struct timespec conchModTime;
5836
5837 do {
5838 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5839 nTries ++;
5840 if( rc==SQLITE_BUSY ){
5841 /* If the lock failed (busy):
5842 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5843 * 2nd try: fail if the mod time changed or host id is different, wait
5844 * 10 sec and try again
5845 * 3rd try: break the lock unless the mod time has changed.
5846 */
5847 struct stat buf;
5848 if( fstat(conchFile->h, &buf) ){
5849 pFile->lastErrno = errno;
5850 return SQLITE_IOERR_LOCK;
5851 }
5852
5853 if( nTries==1 ){
5854 conchModTime = buf.st_mtimespec;
5855 usleep(500000); /* wait 0.5 sec and try the lock again*/
5856 continue;
5857 }
5858
5859 assert( nTries>1 );
5860 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5861 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5862 return SQLITE_BUSY;
5863 }
5864
5865 if( nTries==2 ){
5866 char tBuf[PROXY_MAXCONCHLEN];
5867 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5868 if( len<0 ){
5869 pFile->lastErrno = errno;
5870 return SQLITE_IOERR_LOCK;
5871 }
5872 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5873 /* don't break the lock if the host id doesn't match */
5874 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5875 return SQLITE_BUSY;
5876 }
5877 }else{
5878 /* don't break the lock on short read or a version mismatch */
5879 return SQLITE_BUSY;
5880 }
5881 usleep(10000000); /* wait 10 sec and try the lock again */
5882 continue;
5883 }
5884
5885 assert( nTries==3 );
5886 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5887 rc = SQLITE_OK;
5888 if( lockType==EXCLUSIVE_LOCK ){
5889 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5890 }
5891 if( !rc ){
5892 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5893 }
5894 }
5895 }
5896 } while( rc==SQLITE_BUSY && nTries<3 );
5897
5898 return rc;
5899}
5900
5901/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005902** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5903** lockPath means that the lockPath in the conch file will be used if the
5904** host IDs match, or a new lock path will be generated automatically
5905** and written to the conch file.
5906*/
5907static int proxyTakeConch(unixFile *pFile){
5908 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5909
drh7ed97b92010-01-20 13:07:21 +00005910 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005911 return SQLITE_OK;
5912 }else{
5913 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005914 uuid_t myHostID;
5915 int pError = 0;
5916 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005917 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005918 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005919 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005920 int createConch = 0;
5921 int hostIdMatch = 0;
5922 int readLen = 0;
5923 int tryOldLockPath = 0;
5924 int forceNewLockPath = 0;
5925
drh715ff302008-12-03 22:32:44 +00005926 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5927 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
5928
drh7ed97b92010-01-20 13:07:21 +00005929 rc = proxyGetHostID(myHostID, &pError);
5930 if( (rc&0xff)==SQLITE_IOERR ){
5931 pFile->lastErrno = pError;
5932 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005933 }
drh7ed97b92010-01-20 13:07:21 +00005934 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005935 if( rc!=SQLITE_OK ){
5936 goto end_takeconch;
5937 }
drh7ed97b92010-01-20 13:07:21 +00005938 /* read the existing conch file */
5939 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5940 if( readLen<0 ){
5941 /* I/O error: lastErrno set by seekAndRead */
5942 pFile->lastErrno = conchFile->lastErrno;
5943 rc = SQLITE_IOERR_READ;
5944 goto end_takeconch;
5945 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5946 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5947 /* a short read or version format mismatch means we need to create a new
5948 ** conch file.
5949 */
5950 createConch = 1;
5951 }
5952 /* if the host id matches and the lock path already exists in the conch
5953 ** we'll try to use the path there, if we can't open that path, we'll
5954 ** retry with a new auto-generated path
5955 */
5956 do { /* in case we need to try again for an :auto: named lock file */
5957
5958 if( !createConch && !forceNewLockPath ){
5959 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5960 PROXY_HOSTIDLEN);
5961 /* if the conch has data compare the contents */
5962 if( !pCtx->lockProxyPath ){
5963 /* for auto-named local lock file, just check the host ID and we'll
5964 ** use the local lock file path that's already in there
5965 */
5966 if( hostIdMatch ){
5967 size_t pathLen = (readLen - PROXY_PATHINDEX);
5968
5969 if( pathLen>=MAXPATHLEN ){
5970 pathLen=MAXPATHLEN-1;
5971 }
5972 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5973 lockPath[pathLen] = 0;
5974 tempLockPath = lockPath;
5975 tryOldLockPath = 1;
5976 /* create a copy of the lock path if the conch is taken */
5977 goto end_takeconch;
5978 }
5979 }else if( hostIdMatch
5980 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5981 readLen-PROXY_PATHINDEX)
5982 ){
5983 /* conch host and lock path match */
5984 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005985 }
drh7ed97b92010-01-20 13:07:21 +00005986 }
5987
5988 /* if the conch isn't writable and doesn't match, we can't take it */
5989 if( (conchFile->openFlags&O_RDWR) == 0 ){
5990 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005991 goto end_takeconch;
5992 }
drh7ed97b92010-01-20 13:07:21 +00005993
5994 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005995 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005996 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5997 tempLockPath = lockPath;
5998 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005999 }
drh7ed97b92010-01-20 13:07:21 +00006000
6001 /* update conch with host and path (this will fail if other process
6002 ** has a shared lock already), if the host id matches, use the big
6003 ** stick.
drh715ff302008-12-03 22:32:44 +00006004 */
drh7ed97b92010-01-20 13:07:21 +00006005 futimes(conchFile->h, NULL);
6006 if( hostIdMatch && !createConch ){
6007 if( conchFile->pLock && conchFile->pLock->cnt>1 ){
6008 /* We are trying for an exclusive lock but another thread in this
6009 ** same process is still holding a shared lock. */
6010 rc = SQLITE_BUSY;
6011 } else {
6012 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006013 }
drh715ff302008-12-03 22:32:44 +00006014 }else{
drh7ed97b92010-01-20 13:07:21 +00006015 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006016 }
drh7ed97b92010-01-20 13:07:21 +00006017 if( rc==SQLITE_OK ){
6018 char writeBuffer[PROXY_MAXCONCHLEN];
6019 int writeSize = 0;
6020
6021 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6022 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6023 if( pCtx->lockProxyPath!=NULL ){
6024 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6025 }else{
6026 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6027 }
6028 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
6029 ftruncate(conchFile->h, writeSize);
6030 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6031 fsync(conchFile->h);
6032 /* If we created a new conch file (not just updated the contents of a
6033 ** valid conch file), try to match the permissions of the database
6034 */
6035 if( rc==SQLITE_OK && createConch ){
6036 struct stat buf;
6037 int err = fstat(pFile->h, &buf);
6038 if( err==0 ){
6039 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6040 S_IROTH|S_IWOTH);
6041 /* try to match the database file R/W permissions, ignore failure */
6042#ifndef SQLITE_PROXY_DEBUG
6043 fchmod(conchFile->h, cmode);
6044#else
6045 if( fchmod(conchFile->h, cmode)!=0 ){
6046 int code = errno;
6047 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6048 cmode, code, strerror(code));
6049 } else {
6050 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6051 }
6052 }else{
6053 int code = errno;
6054 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6055 err, code, strerror(code));
6056#endif
6057 }
drh715ff302008-12-03 22:32:44 +00006058 }
6059 }
drh7ed97b92010-01-20 13:07:21 +00006060 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6061
6062 end_takeconch:
6063 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
6064 if( rc==SQLITE_OK && pFile->openFlags ){
6065 if( pFile->h>=0 ){
6066#ifdef STRICT_CLOSE_ERROR
6067 if( close(pFile->h) ){
6068 pFile->lastErrno = errno;
6069 return SQLITE_IOERR_CLOSE;
6070 }
6071#else
6072 close(pFile->h); /* silently leak fd if fail */
6073#endif
6074 }
6075 pFile->h = -1;
6076 int fd = open(pCtx->dbPath, pFile->openFlags,
6077 SQLITE_DEFAULT_FILE_PERMISSIONS);
6078 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
6079 if( fd>=0 ){
6080 pFile->h = fd;
6081 }else{
drh9978c972010-02-23 17:36:32 +00006082 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006083 during locking */
6084 }
6085 }
6086 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6087 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6088 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6089 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6090 /* we couldn't create the proxy lock file with the old lock file path
6091 ** so try again via auto-naming
6092 */
6093 forceNewLockPath = 1;
6094 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006095 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006096 }
6097 }
6098 if( rc==SQLITE_OK ){
6099 /* Need to make a copy of path if we extracted the value
6100 ** from the conch file or the path was allocated on the stack
6101 */
6102 if( tempLockPath ){
6103 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6104 if( !pCtx->lockProxyPath ){
6105 rc = SQLITE_NOMEM;
6106 }
6107 }
6108 }
6109 if( rc==SQLITE_OK ){
6110 pCtx->conchHeld = 1;
6111
6112 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6113 afpLockingContext *afpCtx;
6114 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6115 afpCtx->dbPath = pCtx->lockProxyPath;
6116 }
6117 } else {
6118 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6119 }
6120 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
6121 return rc;
6122 } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006123 }
6124}
6125
6126/*
6127** If pFile holds a lock on a conch file, then release that lock.
6128*/
6129static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006130 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006131 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6132 unixFile *conchFile; /* Name of the conch file */
6133
6134 pCtx = (proxyLockingContext *)pFile->lockingContext;
6135 conchFile = pCtx->conchFile;
6136 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
6137 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6138 getpid());
drh7ed97b92010-01-20 13:07:21 +00006139 if( pCtx->conchHeld>0 ){
6140 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6141 }
drh715ff302008-12-03 22:32:44 +00006142 pCtx->conchHeld = 0;
drh715ff302008-12-03 22:32:44 +00006143 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
6144 (rc==SQLITE_OK ? "ok" : "failed"));
6145 return rc;
6146}
6147
6148/*
6149** Given the name of a database file, compute the name of its conch file.
6150** Store the conch filename in memory obtained from sqlite3_malloc().
6151** Make *pConchPath point to the new name. Return SQLITE_OK on success
6152** or SQLITE_NOMEM if unable to obtain memory.
6153**
6154** The caller is responsible for ensuring that the allocated memory
6155** space is eventually freed.
6156**
6157** *pConchPath is set to NULL if a memory allocation error occurs.
6158*/
6159static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6160 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006161 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006162 char *conchPath; /* buffer in which to construct conch name */
6163
6164 /* Allocate space for the conch filename and initialize the name to
6165 ** the name of the original database file. */
6166 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6167 if( conchPath==0 ){
6168 return SQLITE_NOMEM;
6169 }
6170 memcpy(conchPath, dbPath, len+1);
6171
6172 /* now insert a "." before the last / character */
6173 for( i=(len-1); i>=0; i-- ){
6174 if( conchPath[i]=='/' ){
6175 i++;
6176 break;
6177 }
6178 }
6179 conchPath[i]='.';
6180 while ( i<len ){
6181 conchPath[i+1]=dbPath[i];
6182 i++;
6183 }
6184
6185 /* append the "-conch" suffix to the file */
6186 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006187 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006188
6189 return SQLITE_OK;
6190}
6191
6192
6193/* Takes a fully configured proxy locking-style unix file and switches
6194** the local lock file path
6195*/
6196static int switchLockProxyPath(unixFile *pFile, const char *path) {
6197 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6198 char *oldPath = pCtx->lockProxyPath;
6199 int rc = SQLITE_OK;
6200
6201 if( pFile->locktype!=NO_LOCK ){
6202 return SQLITE_BUSY;
6203 }
6204
6205 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6206 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6207 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6208 return SQLITE_OK;
6209 }else{
6210 unixFile *lockProxy = pCtx->lockProxy;
6211 pCtx->lockProxy=NULL;
6212 pCtx->conchHeld = 0;
6213 if( lockProxy!=NULL ){
6214 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6215 if( rc ) return rc;
6216 sqlite3_free(lockProxy);
6217 }
6218 sqlite3_free(oldPath);
6219 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6220 }
6221
6222 return rc;
6223}
6224
6225/*
6226** pFile is a file that has been opened by a prior xOpen call. dbPath
6227** is a string buffer at least MAXPATHLEN+1 characters in size.
6228**
6229** This routine find the filename associated with pFile and writes it
6230** int dbPath.
6231*/
6232static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006233#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006234 if( pFile->pMethod == &afpIoMethods ){
6235 /* afp style keeps a reference to the db path in the filePath field
6236 ** of the struct */
drhea678832008-12-10 19:26:22 +00006237 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006238 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6239 } else
drh715ff302008-12-03 22:32:44 +00006240#endif
6241 if( pFile->pMethod == &dotlockIoMethods ){
6242 /* dot lock style uses the locking context to store the dot lock
6243 ** file path */
6244 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6245 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6246 }else{
6247 /* all other styles use the locking context to store the db file path */
6248 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006249 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006250 }
6251 return SQLITE_OK;
6252}
6253
6254/*
6255** Takes an already filled in unix file and alters it so all file locking
6256** will be performed on the local proxy lock file. The following fields
6257** are preserved in the locking context so that they can be restored and
6258** the unix structure properly cleaned up at close time:
6259** ->lockingContext
6260** ->pMethod
6261*/
6262static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6263 proxyLockingContext *pCtx;
6264 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6265 char *lockPath=NULL;
6266 int rc = SQLITE_OK;
6267
6268 if( pFile->locktype!=NO_LOCK ){
6269 return SQLITE_BUSY;
6270 }
6271 proxyGetDbPathForUnixFile(pFile, dbPath);
6272 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6273 lockPath=NULL;
6274 }else{
6275 lockPath=(char *)path;
6276 }
6277
6278 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6279 (lockPath ? lockPath : ":auto:"), getpid());
6280
6281 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6282 if( pCtx==0 ){
6283 return SQLITE_NOMEM;
6284 }
6285 memset(pCtx, 0, sizeof(*pCtx));
6286
6287 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6288 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006289 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6290 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6291 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6292 ** (c) the file system is read-only, then enable no-locking access.
6293 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6294 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6295 */
6296 struct statfs fsInfo;
6297 struct stat conchInfo;
6298 int goLockless = 0;
6299
6300 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6301 int err = errno;
6302 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6303 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6304 }
6305 }
6306 if( goLockless ){
6307 pCtx->conchHeld = -1; /* read only FS/ lockless */
6308 rc = SQLITE_OK;
6309 }
6310 }
drh715ff302008-12-03 22:32:44 +00006311 }
6312 if( rc==SQLITE_OK && lockPath ){
6313 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6314 }
6315
6316 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006317 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6318 if( pCtx->dbPath==NULL ){
6319 rc = SQLITE_NOMEM;
6320 }
6321 }
6322 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006323 /* all memory is allocated, proxys are created and assigned,
6324 ** switch the locking context and pMethod then return.
6325 */
drh715ff302008-12-03 22:32:44 +00006326 pCtx->oldLockingContext = pFile->lockingContext;
6327 pFile->lockingContext = pCtx;
6328 pCtx->pOldMethod = pFile->pMethod;
6329 pFile->pMethod = &proxyIoMethods;
6330 }else{
6331 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006332 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006333 sqlite3_free(pCtx->conchFile);
6334 }
drh7ed97b92010-01-20 13:07:21 +00006335 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006336 sqlite3_free(pCtx->conchFilePath);
6337 sqlite3_free(pCtx);
6338 }
6339 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
6340 (rc==SQLITE_OK ? "ok" : "failed"));
6341 return rc;
6342}
6343
6344
6345/*
6346** This routine handles sqlite3_file_control() calls that are specific
6347** to proxy locking.
6348*/
6349static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6350 switch( op ){
6351 case SQLITE_GET_LOCKPROXYFILE: {
6352 unixFile *pFile = (unixFile*)id;
6353 if( pFile->pMethod == &proxyIoMethods ){
6354 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6355 proxyTakeConch(pFile);
6356 if( pCtx->lockProxyPath ){
6357 *(const char **)pArg = pCtx->lockProxyPath;
6358 }else{
6359 *(const char **)pArg = ":auto: (not held)";
6360 }
6361 } else {
6362 *(const char **)pArg = NULL;
6363 }
6364 return SQLITE_OK;
6365 }
6366 case SQLITE_SET_LOCKPROXYFILE: {
6367 unixFile *pFile = (unixFile*)id;
6368 int rc = SQLITE_OK;
6369 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6370 if( pArg==NULL || (const char *)pArg==0 ){
6371 if( isProxyStyle ){
6372 /* turn off proxy locking - not supported */
6373 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6374 }else{
6375 /* turn off proxy locking - already off - NOOP */
6376 rc = SQLITE_OK;
6377 }
6378 }else{
6379 const char *proxyPath = (const char *)pArg;
6380 if( isProxyStyle ){
6381 proxyLockingContext *pCtx =
6382 (proxyLockingContext*)pFile->lockingContext;
6383 if( !strcmp(pArg, ":auto:")
6384 || (pCtx->lockProxyPath &&
6385 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6386 ){
6387 rc = SQLITE_OK;
6388 }else{
6389 rc = switchLockProxyPath(pFile, proxyPath);
6390 }
6391 }else{
6392 /* turn on proxy file locking */
6393 rc = proxyTransformUnixFile(pFile, proxyPath);
6394 }
6395 }
6396 return rc;
6397 }
6398 default: {
6399 assert( 0 ); /* The call assures that only valid opcodes are sent */
6400 }
6401 }
6402 /*NOTREACHED*/
6403 return SQLITE_ERROR;
6404}
6405
6406/*
6407** Within this division (the proxying locking implementation) the procedures
6408** above this point are all utilities. The lock-related methods of the
6409** proxy-locking sqlite3_io_method object follow.
6410*/
6411
6412
6413/*
6414** This routine checks if there is a RESERVED lock held on the specified
6415** file by this or any other process. If such a lock is held, set *pResOut
6416** to a non-zero value otherwise *pResOut is set to zero. The return value
6417** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6418*/
6419static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6420 unixFile *pFile = (unixFile*)id;
6421 int rc = proxyTakeConch(pFile);
6422 if( rc==SQLITE_OK ){
6423 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006424 if( pCtx->conchHeld>0 ){
6425 unixFile *proxy = pCtx->lockProxy;
6426 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6427 }else{ /* conchHeld < 0 is lockless */
6428 pResOut=0;
6429 }
drh715ff302008-12-03 22:32:44 +00006430 }
6431 return rc;
6432}
6433
6434/*
6435** Lock the file with the lock specified by parameter locktype - one
6436** of the following:
6437**
6438** (1) SHARED_LOCK
6439** (2) RESERVED_LOCK
6440** (3) PENDING_LOCK
6441** (4) EXCLUSIVE_LOCK
6442**
6443** Sometimes when requesting one lock state, additional lock states
6444** are inserted in between. The locking might fail on one of the later
6445** transitions leaving the lock state different from what it started but
6446** still short of its goal. The following chart shows the allowed
6447** transitions and the inserted intermediate states:
6448**
6449** UNLOCKED -> SHARED
6450** SHARED -> RESERVED
6451** SHARED -> (PENDING) -> EXCLUSIVE
6452** RESERVED -> (PENDING) -> EXCLUSIVE
6453** PENDING -> EXCLUSIVE
6454**
6455** This routine will only increase a lock. Use the sqlite3OsUnlock()
6456** routine to lower a locking level.
6457*/
6458static int proxyLock(sqlite3_file *id, int locktype) {
6459 unixFile *pFile = (unixFile*)id;
6460 int rc = proxyTakeConch(pFile);
6461 if( rc==SQLITE_OK ){
6462 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006463 if( pCtx->conchHeld>0 ){
6464 unixFile *proxy = pCtx->lockProxy;
6465 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
6466 pFile->locktype = proxy->locktype;
6467 }else{
6468 /* conchHeld < 0 is lockless */
6469 }
drh715ff302008-12-03 22:32:44 +00006470 }
6471 return rc;
6472}
6473
6474
6475/*
6476** Lower the locking level on file descriptor pFile to locktype. locktype
6477** must be either NO_LOCK or SHARED_LOCK.
6478**
6479** If the locking level of the file descriptor is already at or below
6480** the requested locking level, this routine is a no-op.
6481*/
6482static int proxyUnlock(sqlite3_file *id, int locktype) {
6483 unixFile *pFile = (unixFile*)id;
6484 int rc = proxyTakeConch(pFile);
6485 if( rc==SQLITE_OK ){
6486 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006487 if( pCtx->conchHeld>0 ){
6488 unixFile *proxy = pCtx->lockProxy;
6489 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
6490 pFile->locktype = proxy->locktype;
6491 }else{
6492 /* conchHeld < 0 is lockless */
6493 }
drh715ff302008-12-03 22:32:44 +00006494 }
6495 return rc;
6496}
6497
6498/*
6499** Close a file that uses proxy locks.
6500*/
6501static int proxyClose(sqlite3_file *id) {
6502 if( id ){
6503 unixFile *pFile = (unixFile*)id;
6504 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6505 unixFile *lockProxy = pCtx->lockProxy;
6506 unixFile *conchFile = pCtx->conchFile;
6507 int rc = SQLITE_OK;
6508
6509 if( lockProxy ){
6510 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6511 if( rc ) return rc;
6512 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6513 if( rc ) return rc;
6514 sqlite3_free(lockProxy);
6515 pCtx->lockProxy = 0;
6516 }
6517 if( conchFile ){
6518 if( pCtx->conchHeld ){
6519 rc = proxyReleaseConch(pFile);
6520 if( rc ) return rc;
6521 }
6522 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6523 if( rc ) return rc;
6524 sqlite3_free(conchFile);
6525 }
6526 sqlite3_free(pCtx->lockProxyPath);
6527 sqlite3_free(pCtx->conchFilePath);
6528 sqlite3_free(pCtx->dbPath);
6529 /* restore the original locking context and pMethod then close it */
6530 pFile->lockingContext = pCtx->oldLockingContext;
6531 pFile->pMethod = pCtx->pOldMethod;
6532 sqlite3_free(pCtx);
6533 return pFile->pMethod->xClose(id);
6534 }
6535 return SQLITE_OK;
6536}
6537
6538
6539
drhd2cb50b2009-01-09 21:41:17 +00006540#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006541/*
6542** The proxy locking style is intended for use with AFP filesystems.
6543** And since AFP is only supported on MacOSX, the proxy locking is also
6544** restricted to MacOSX.
6545**
6546**
6547******************* End of the proxy lock implementation **********************
6548******************************************************************************/
6549
drh734c9862008-11-28 15:37:20 +00006550/*
danielk1977e339d652008-06-28 11:23:00 +00006551** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006552**
6553** This routine registers all VFS implementations for unix-like operating
6554** systems. This routine, and the sqlite3_os_end() routine that follows,
6555** should be the only routines in this file that are visible from other
6556** files.
drh6b9d6dd2008-12-03 19:34:47 +00006557**
6558** This routine is called once during SQLite initialization and by a
6559** single thread. The memory allocation and mutex subsystems have not
6560** necessarily been initialized when this routine is called, and so they
6561** should not be used.
drh153c62c2007-08-24 03:51:33 +00006562*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006563int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006564 /*
6565 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006566 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6567 ** to the "finder" function. (pAppData is a pointer to a pointer because
6568 ** silly C90 rules prohibit a void* from being cast to a function pointer
6569 ** and so we have to go through the intermediate pointer to avoid problems
6570 ** when compiling with -pedantic-errors on GCC.)
6571 **
6572 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006573 ** finder-function. The finder-function returns a pointer to the
6574 ** sqlite_io_methods object that implements the desired locking
6575 ** behaviors. See the division above that contains the IOMETHODS
6576 ** macro for addition information on finder-functions.
6577 **
6578 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6579 ** object. But the "autolockIoFinder" available on MacOSX does a little
6580 ** more than that; it looks at the filesystem type that hosts the
6581 ** database file and tries to choose an locking method appropriate for
6582 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006583 */
drh7708e972008-11-29 00:56:52 +00006584 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006585 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006586 sizeof(unixFile), /* szOsFile */ \
6587 MAX_PATHNAME, /* mxPathname */ \
6588 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006589 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006590 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006591 unixOpen, /* xOpen */ \
6592 unixDelete, /* xDelete */ \
6593 unixAccess, /* xAccess */ \
6594 unixFullPathname, /* xFullPathname */ \
6595 unixDlOpen, /* xDlOpen */ \
6596 unixDlError, /* xDlError */ \
6597 unixDlSym, /* xDlSym */ \
6598 unixDlClose, /* xDlClose */ \
6599 unixRandomness, /* xRandomness */ \
6600 unixSleep, /* xSleep */ \
6601 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006602 unixGetLastError, /* xGetLastError */ \
6603 unixShmOpen, /* xShmOpen */ \
6604 unixShmSize, /* xShmSize */ \
drh5530b762010-04-30 14:39:50 +00006605 unixShmGet, /* xShmGet */ \
drhaf75c862010-04-27 11:49:27 +00006606 unixShmRelease, /* xShmRelease */ \
drhf2424c52010-04-26 00:04:55 +00006607 unixShmLock, /* xShmLock */ \
6608 unixShmClose, /* xShmClose */ \
drhf2424c52010-04-26 00:04:55 +00006609 0, /* xRename */ \
drhb7e8ea22010-05-03 14:32:30 +00006610 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006611 }
6612
drh6b9d6dd2008-12-03 19:34:47 +00006613 /*
6614 ** All default VFSes for unix are contained in the following array.
6615 **
6616 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6617 ** by the SQLite core when the VFS is registered. So the following
6618 ** array cannot be const.
6619 */
danielk1977e339d652008-06-28 11:23:00 +00006620 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006621#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006622 UNIXVFS("unix", autolockIoFinder ),
6623#else
6624 UNIXVFS("unix", posixIoFinder ),
6625#endif
6626 UNIXVFS("unix-none", nolockIoFinder ),
6627 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006628#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006629 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006630#endif
6631#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006632 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006633#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006634 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006635#endif
chw78a13182009-04-07 05:35:03 +00006636#endif
drhd2cb50b2009-01-09 21:41:17 +00006637#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006638 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006639 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006640 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006641#endif
drh153c62c2007-08-24 03:51:33 +00006642 };
drh6b9d6dd2008-12-03 19:34:47 +00006643 unsigned int i; /* Loop counter */
6644
6645 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006646 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006647 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006648 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006649 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006650}
danielk1977e339d652008-06-28 11:23:00 +00006651
6652/*
drh6b9d6dd2008-12-03 19:34:47 +00006653** Shutdown the operating system interface.
6654**
6655** Some operating systems might need to do some cleanup in this routine,
6656** to release dynamically allocated objects. But not on unix.
6657** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006658*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006659int sqlite3_os_end(void){
6660 return SQLITE_OK;
6661}
drhdce8bdb2007-08-16 13:01:44 +00006662
danielk197729bafea2008-06-26 10:41:19 +00006663#endif /* SQLITE_OS_UNIX */