blob: 719f16c87184eb1cf08add68cbf59c52b909816a [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().
drh734c9862008-11-28 15:37:20 +000045**
danielk197764a54c52009-03-30 07:39:35 +000046** $Id: os_unix.c,v 1.248 2009/03/30 07:39:35 danielk1977 Exp $
drhbbd42a62004-05-22 17:41:58 +000047*/
drhbbd42a62004-05-22 17:41:58 +000048#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000049#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000050
danielk1977e339d652008-06-28 11:23:00 +000051/*
drh6b9d6dd2008-12-03 19:34:47 +000052** There are various methods for file locking used for concurrency
53** control:
danielk1977e339d652008-06-28 11:23:00 +000054**
drh734c9862008-11-28 15:37:20 +000055** 1. POSIX locking (the default),
56** 2. No locking,
57** 3. Dot-file locking,
58** 4. flock() locking,
59** 5. AFP locking (OSX only),
60** 6. Named POSIX semaphores (VXWorks only),
61** 7. proxy locking. (OSX only)
62**
63** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
64** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
65** selection of the appropriate locking style based on the filesystem
66** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000067*/
drh40bbb0a2008-09-23 10:23:26 +000068#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000069# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000070# define SQLITE_ENABLE_LOCKING_STYLE 1
71# else
72# define SQLITE_ENABLE_LOCKING_STYLE 0
73# endif
74#endif
drhbfe66312006-10-03 17:40:40 +000075
drh9cbe6352005-11-29 03:13:21 +000076/*
drh6c7d5c52008-11-21 20:32:33 +000077** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000078** vxworks, or 0 otherwise.
79*/
drh6c7d5c52008-11-21 20:32:33 +000080#ifndef OS_VXWORKS
81# if defined(__RTP__) || defined(_WRS_KERNEL)
82# define OS_VXWORKS 1
83# else
84# define OS_VXWORKS 0
85# endif
danielk1977397d65f2008-11-19 11:35:39 +000086#endif
87
88/*
drh9cbe6352005-11-29 03:13:21 +000089** These #defines should enable >2GB file support on Posix if the
90** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000091** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000092**
93** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
94** on the compiler command line. This is necessary if you are compiling
95** on a recent machine (ex: RedHat 7.2) but you want your code to work
96** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
97** without this option, LFS is enable. But LFS does not exist in the kernel
98** in RedHat 6.0, so the code won't work. Hence, for maximum binary
99** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000100**
101** The previous paragraph was written in 2005. (This paragraph is written
102** on 2008-11-28.) These days, all Linux kernels support large files, so
103** you should probably leave LFS enabled. But some embedded platforms might
104** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000105*/
106#ifndef SQLITE_DISABLE_LFS
107# define _LARGE_FILE 1
108# ifndef _FILE_OFFSET_BITS
109# define _FILE_OFFSET_BITS 64
110# endif
111# define _LARGEFILE_SOURCE 1
112#endif
drhbbd42a62004-05-22 17:41:58 +0000113
drh9cbe6352005-11-29 03:13:21 +0000114/*
115** standard include files.
116*/
117#include <sys/types.h>
118#include <sys/stat.h>
119#include <fcntl.h>
120#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000122#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000123#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000124
drh40bbb0a2008-09-23 10:23:26 +0000125#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000127# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <semaphore.h>
129# include <limits.h>
130# else
drh9b35ea62008-11-29 02:20:26 +0000131# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# include <sys/param.h>
133# include <sys/mount.h>
134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
137/*
drhf1a221e2006-01-15 17:27:17 +0000138** If we are to be thread-safe, include the pthreads header and define
139** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000140*/
drhd677b3d2007-08-20 22:48:41 +0000141#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000142# include <pthread.h>
143# define SQLITE_UNIX_THREADS 1
144#endif
145
146/*
147** Default permissions when creating a new file
148*/
149#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
150# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
151#endif
152
danielk1977b4b47412007-08-17 15:53:36 +0000153/*
aswiftaebf4132008-11-21 00:10:35 +0000154 ** Default permissions when creating auto proxy dir
155 */
156#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
157# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
158#endif
159
160/*
danielk1977b4b47412007-08-17 15:53:36 +0000161** Maximum supported path-length.
162*/
163#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000164
drh734c9862008-11-28 15:37:20 +0000165/*
drh734c9862008-11-28 15:37:20 +0000166** Only set the lastErrno if the error code is a real error and not
167** a normal expected return code of SQLITE_BUSY or SQLITE_OK
168*/
169#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
170
drh9cbe6352005-11-29 03:13:21 +0000171
172/*
drh9b35ea62008-11-29 02:20:26 +0000173** The unixFile structure is subclass of sqlite3_file specific to the unix
174** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000175*/
drh054889e2005-11-30 03:20:31 +0000176typedef struct unixFile unixFile;
177struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000178 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000179 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
180 struct unixLockInfo *pLock; /* Info about locks on this inode */
181 int h; /* The file descriptor */
182 int dirfd; /* File descriptor for the directory */
183 unsigned char locktype; /* The type of lock held on this fd */
184 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000185 void *lockingContext; /* Locking style specific state */
drh08c6d442009-02-09 17:34:07 +0000186#if SQLITE_ENABLE_LOCKING_STYLE
187 int openFlags; /* The flags specified at open() */
188#endif
drh734c9862008-11-28 15:37:20 +0000189#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000190 pthread_t tid; /* The thread that "owns" this unixFile */
191#endif
192#if OS_VXWORKS
193 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000194 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000195#endif
drh8f941bc2009-01-14 23:03:40 +0000196#ifndef NDEBUG
197 /* The next group of variables are used to track whether or not the
198 ** transaction counter in bytes 24-27 of database files are updated
199 ** whenever any part of the database changes. An assertion fault will
200 ** occur if a file is updated without also updating the transaction
201 ** counter. This test is made to avoid new problems similar to the
202 ** one described by ticket #3584.
203 */
204 unsigned char transCntrChng; /* True if the transaction counter changed */
205 unsigned char dbUpdate; /* True if any part of database file changed */
206 unsigned char inNormalWrite; /* True if in a normal write operation */
drh08c6d442009-02-09 17:34:07 +0000207
208 /* If true, that means we are dealing with a database file that has
209 ** a range of locking bytes from PENDING_BYTE through PENDING_BYTE+511
210 ** which should never be read or written. Asserts() will verify this */
211 unsigned char isLockable; /* True if file might be locked */
drh8f941bc2009-01-14 23:03:40 +0000212#endif
danielk1977967a4a12007-08-20 14:23:44 +0000213#ifdef SQLITE_TEST
214 /* In test mode, increase the size of this structure a bit so that
215 ** it is larger than the struct CrashFile defined in test6.c.
216 */
217 char aPadding[32];
218#endif
drh9cbe6352005-11-29 03:13:21 +0000219};
220
drh0ccebe72005-06-07 22:22:50 +0000221/*
drh198bf392006-01-06 21:52:49 +0000222** Include code that is common to all os_*.c files
223*/
224#include "os_common.h"
225
226/*
drh0ccebe72005-06-07 22:22:50 +0000227** Define various macros that are missing from some systems.
228*/
drhbbd42a62004-05-22 17:41:58 +0000229#ifndef O_LARGEFILE
230# define O_LARGEFILE 0
231#endif
232#ifdef SQLITE_DISABLE_LFS
233# undef O_LARGEFILE
234# define O_LARGEFILE 0
235#endif
236#ifndef O_NOFOLLOW
237# define O_NOFOLLOW 0
238#endif
239#ifndef O_BINARY
240# define O_BINARY 0
241#endif
242
243/*
244** The DJGPP compiler environment looks mostly like Unix, but it
245** lacks the fcntl() system call. So redefine fcntl() to be something
246** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000247** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000248*/
249#ifdef __DJGPP__
250# define fcntl(A,B,C) 0
251#endif
252
253/*
drh2b4b5962005-06-15 17:47:55 +0000254** The threadid macro resolves to the thread-id or to 0. Used for
255** testing and debugging only.
256*/
drhd677b3d2007-08-20 22:48:41 +0000257#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000258#define threadid pthread_self()
259#else
260#define threadid 0
261#endif
262
danielk197713adf8a2004-06-03 16:08:41 +0000263
drh107886a2008-11-21 22:21:50 +0000264/*
265** Helper functions to obtain and relinquish the global mutex.
266*/
267static void unixEnterMutex(void){
268 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
269}
270static void unixLeaveMutex(void){
271 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
272}
273
drh734c9862008-11-28 15:37:20 +0000274
275#ifdef SQLITE_DEBUG
276/*
277** Helper function for printing out trace information from debugging
278** binaries. This returns the string represetation of the supplied
279** integer lock-type.
280*/
281static const char *locktypeName(int locktype){
282 switch( locktype ){
283 case NO_LOCK: return "NONE";
284 case SHARED_LOCK: return "SHARED";
285 case RESERVED_LOCK: return "RESERVED";
286 case PENDING_LOCK: return "PENDING";
287 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
288 }
289 return "ERROR";
290}
291#endif
292
293#ifdef SQLITE_LOCK_TRACE
294/*
295** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000296**
drh734c9862008-11-28 15:37:20 +0000297** This routine is used for troubleshooting locks on multithreaded
298** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
299** command-line option on the compiler. This code is normally
300** turned off.
301*/
302static int lockTrace(int fd, int op, struct flock *p){
303 char *zOpName, *zType;
304 int s;
305 int savedErrno;
306 if( op==F_GETLK ){
307 zOpName = "GETLK";
308 }else if( op==F_SETLK ){
309 zOpName = "SETLK";
310 }else{
311 s = fcntl(fd, op, p);
312 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
313 return s;
314 }
315 if( p->l_type==F_RDLCK ){
316 zType = "RDLCK";
317 }else if( p->l_type==F_WRLCK ){
318 zType = "WRLCK";
319 }else if( p->l_type==F_UNLCK ){
320 zType = "UNLCK";
321 }else{
322 assert( 0 );
323 }
324 assert( p->l_whence==SEEK_SET );
325 s = fcntl(fd, op, p);
326 savedErrno = errno;
327 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
328 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
329 (int)p->l_pid, s);
330 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
331 struct flock l2;
332 l2 = *p;
333 fcntl(fd, F_GETLK, &l2);
334 if( l2.l_type==F_RDLCK ){
335 zType = "RDLCK";
336 }else if( l2.l_type==F_WRLCK ){
337 zType = "WRLCK";
338 }else if( l2.l_type==F_UNLCK ){
339 zType = "UNLCK";
340 }else{
341 assert( 0 );
342 }
343 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
344 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
345 }
346 errno = savedErrno;
347 return s;
348}
349#define fcntl lockTrace
350#endif /* SQLITE_LOCK_TRACE */
351
352
353
354/*
355** This routine translates a standard POSIX errno code into something
356** useful to the clients of the sqlite3 functions. Specifically, it is
357** intended to translate a variety of "try again" errors into SQLITE_BUSY
358** and a variety of "please close the file descriptor NOW" errors into
359** SQLITE_IOERR
360**
361** Errors during initialization of locks, or file system support for locks,
362** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
363*/
364static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
365 switch (posixError) {
366 case 0:
367 return SQLITE_OK;
368
369 case EAGAIN:
370 case ETIMEDOUT:
371 case EBUSY:
372 case EINTR:
373 case ENOLCK:
374 /* random NFS retry error, unless during file system support
375 * introspection, in which it actually means what it says */
376 return SQLITE_BUSY;
377
378 case EACCES:
379 /* EACCES is like EAGAIN during locking operations, but not any other time*/
380 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
381 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
382 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
383 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
384 return SQLITE_BUSY;
385 }
386 /* else fall through */
387 case EPERM:
388 return SQLITE_PERM;
389
390 case EDEADLK:
391 return SQLITE_IOERR_BLOCKED;
392
393#if EOPNOTSUPP!=ENOTSUP
394 case EOPNOTSUPP:
395 /* something went terribly awry, unless during file system support
396 * introspection, in which it actually means what it says */
397#endif
398#ifdef ENOTSUP
399 case ENOTSUP:
400 /* invalid fd, unless during file system support introspection, in which
401 * it actually means what it says */
402#endif
403 case EIO:
404 case EBADF:
405 case EINVAL:
406 case ENOTCONN:
407 case ENODEV:
408 case ENXIO:
409 case ENOENT:
410 case ESTALE:
411 case ENOSYS:
412 /* these should force the client to close the file and reconnect */
413
414 default:
415 return sqliteIOErr;
416 }
417}
418
419
420
421/******************************************************************************
422****************** Begin Unique File ID Utility Used By VxWorks ***************
423**
424** On most versions of unix, we can get a unique ID for a file by concatenating
425** the device number and the inode number. But this does not work on VxWorks.
426** On VxWorks, a unique file id must be based on the canonical filename.
427**
428** A pointer to an instance of the following structure can be used as a
429** unique file ID in VxWorks. Each instance of this structure contains
430** a copy of the canonical filename. There is also a reference count.
431** The structure is reclaimed when the number of pointers to it drops to
432** zero.
433**
434** There are never very many files open at one time and lookups are not
435** a performance-critical path, so it is sufficient to put these
436** structures on a linked list.
437*/
438struct vxworksFileId {
439 struct vxworksFileId *pNext; /* Next in a list of them all */
440 int nRef; /* Number of references to this one */
441 int nName; /* Length of the zCanonicalName[] string */
442 char *zCanonicalName; /* Canonical filename */
443};
444
445#if OS_VXWORKS
446/*
drh9b35ea62008-11-29 02:20:26 +0000447** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000448** variable:
449*/
450static struct vxworksFileId *vxworksFileList = 0;
451
452/*
453** Simplify a filename into its canonical form
454** by making the following changes:
455**
456** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000457** * convert /./ into just /
458** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000459**
460** Changes are made in-place. Return the new name length.
461**
462** The original filename is in z[0..n-1]. Return the number of
463** characters in the simplified name.
464*/
465static int vxworksSimplifyName(char *z, int n){
466 int i, j;
467 while( n>1 && z[n-1]=='/' ){ n--; }
468 for(i=j=0; i<n; i++){
469 if( z[i]=='/' ){
470 if( z[i+1]=='/' ) continue;
471 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
472 i += 1;
473 continue;
474 }
475 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
476 while( j>0 && z[j-1]!='/' ){ j--; }
477 if( j>0 ){ j--; }
478 i += 2;
479 continue;
480 }
481 }
482 z[j++] = z[i];
483 }
484 z[j] = 0;
485 return j;
486}
487
488/*
489** Find a unique file ID for the given absolute pathname. Return
490** a pointer to the vxworksFileId object. This pointer is the unique
491** file ID.
492**
493** The nRef field of the vxworksFileId object is incremented before
494** the object is returned. A new vxworksFileId object is created
495** and added to the global list if necessary.
496**
497** If a memory allocation error occurs, return NULL.
498*/
499static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
500 struct vxworksFileId *pNew; /* search key and new file ID */
501 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
502 int n; /* Length of zAbsoluteName string */
503
504 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000505 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000506 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
507 if( pNew==0 ) return 0;
508 pNew->zCanonicalName = (char*)&pNew[1];
509 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
510 n = vxworksSimplifyName(pNew->zCanonicalName, n);
511
512 /* Search for an existing entry that matching the canonical name.
513 ** If found, increment the reference count and return a pointer to
514 ** the existing file ID.
515 */
516 unixEnterMutex();
517 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
518 if( pCandidate->nName==n
519 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
520 ){
521 sqlite3_free(pNew);
522 pCandidate->nRef++;
523 unixLeaveMutex();
524 return pCandidate;
525 }
526 }
527
528 /* No match was found. We will make a new file ID */
529 pNew->nRef = 1;
530 pNew->nName = n;
531 pNew->pNext = vxworksFileList;
532 vxworksFileList = pNew;
533 unixLeaveMutex();
534 return pNew;
535}
536
537/*
538** Decrement the reference count on a vxworksFileId object. Free
539** the object when the reference count reaches zero.
540*/
541static void vxworksReleaseFileId(struct vxworksFileId *pId){
542 unixEnterMutex();
543 assert( pId->nRef>0 );
544 pId->nRef--;
545 if( pId->nRef==0 ){
546 struct vxworksFileId **pp;
547 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
548 assert( *pp==pId );
549 *pp = pId->pNext;
550 sqlite3_free(pId);
551 }
552 unixLeaveMutex();
553}
554#endif /* OS_VXWORKS */
555/*************** End of Unique File ID Utility Used By VxWorks ****************
556******************************************************************************/
557
558
559/******************************************************************************
560*************************** Posix Advisory Locking ****************************
561**
drh9b35ea62008-11-29 02:20:26 +0000562** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000563** section 6.5.2.2 lines 483 through 490 specify that when a process
564** sets or clears a lock, that operation overrides any prior locks set
565** by the same process. It does not explicitly say so, but this implies
566** that it overrides locks set by the same process using a different
567** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000568**
569** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000570** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
571**
572** Suppose ./file1 and ./file2 are really the same file (because
573** one is a hard or symbolic link to the other) then if you set
574** an exclusive lock on fd1, then try to get an exclusive lock
575** on fd2, it works. I would have expected the second lock to
576** fail since there was already a lock on the file due to fd1.
577** But not so. Since both locks came from the same process, the
578** second overrides the first, even though they were on different
579** file descriptors opened on different file names.
580**
drh734c9862008-11-28 15:37:20 +0000581** This means that we cannot use POSIX locks to synchronize file access
582** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000583** to synchronize access for threads in separate processes, but not
584** threads within the same process.
585**
586** To work around the problem, SQLite has to manage file locks internally
587** on its own. Whenever a new database is opened, we have to find the
588** specific inode of the database file (the inode is determined by the
589** st_dev and st_ino fields of the stat structure that fstat() fills in)
590** and check for locks already existing on that inode. When locks are
591** created or removed, we have to look at our own internal record of the
592** locks to see if another thread has previously set a lock on that same
593** inode.
594**
drh9b35ea62008-11-29 02:20:26 +0000595** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
596** For VxWorks, we have to use the alternative unique ID system based on
597** canonical filename and implemented in the previous division.)
598**
danielk1977ad94b582007-08-20 06:44:22 +0000599** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000600** descriptor. It is now a structure that holds the integer file
601** descriptor and a pointer to a structure that describes the internal
602** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000603** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000604** point to the same locking structure. The locking structure keeps
605** a reference count (so we will know when to delete it) and a "cnt"
606** field that tells us its internal lock status. cnt==0 means the
607** file is unlocked. cnt==-1 means the file has an exclusive lock.
608** cnt>0 means there are cnt shared locks on the file.
609**
610** Any attempt to lock or unlock a file first checks the locking
611** structure. The fcntl() system call is only invoked to set a
612** POSIX lock if the internal lock structure transitions between
613** a locked and an unlocked state.
614**
drh734c9862008-11-28 15:37:20 +0000615** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000616**
617** If you close a file descriptor that points to a file that has locks,
618** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000619** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000620** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000621** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000622** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000623** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000624** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000625** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000626** be closed and that list is walked (and cleared) when the last lock
627** clears.
628**
drh9b35ea62008-11-29 02:20:26 +0000629** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000630**
drh9b35ea62008-11-29 02:20:26 +0000631** Many older versions of linux use the LinuxThreads library which is
632** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000633** A cannot be modified or overridden by a different thread B.
634** Only thread A can modify the lock. Locking behavior is correct
635** if the appliation uses the newer Native Posix Thread Library (NPTL)
636** on linux - with NPTL a lock created by thread A can override locks
637** in thread B. But there is no way to know at compile-time which
638** threading library is being used. So there is no way to know at
639** compile-time whether or not thread A can override locks on thread B.
640** We have to do a run-time check to discover the behavior of the
641** current process.
drh5fdae772004-06-29 03:29:00 +0000642**
drh734c9862008-11-28 15:37:20 +0000643** On systems where thread A is unable to modify locks created by
644** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000645** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000646** structure to record this information. And on those systems it
647** is illegal to begin a transaction in one thread and finish it
648** in another. For this latter restriction, there is no work-around.
649** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000650*/
651
652/*
drh6c7d5c52008-11-21 20:32:33 +0000653** Set or check the unixFile.tid field. This field is set when an unixFile
654** is first opened. All subsequent uses of the unixFile verify that the
655** same thread is operating on the unixFile. Some operating systems do
656** not allow locks to be overridden by other threads and that restriction
657** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000658** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000659**
660** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
661** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000662** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000663** or if no locks are held. But the unixFile.pLock field needs to be
664** recomputed because its key includes the thread-id. See the
665** transferOwnership() function below for additional information
666*/
drh734c9862008-11-28 15:37:20 +0000667#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000668# define SET_THREADID(X) (X)->tid = pthread_self()
669# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
670 !pthread_equal((X)->tid, pthread_self()))
671#else
672# define SET_THREADID(X)
673# define CHECK_THREADID(X) 0
674#endif
675
676/*
drhbbd42a62004-05-22 17:41:58 +0000677** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000678** to locate a particular unixOpenCnt structure given its inode. This
679** is the same as the unixLockKey except that the thread ID is omitted.
680*/
681struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000682 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000683#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000684 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000685#else
drh107886a2008-11-21 22:21:50 +0000686 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000687#endif
688};
689
690/*
691** An instance of the following structure serves as the key used
692** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000693**
drh734c9862008-11-28 15:37:20 +0000694** If threads cannot override each others locks (LinuxThreads), then we
695** set the unixLockKey.tid field to the thread ID. If threads can override
696** each others locks (Posix and NPTL) then tid is always set to zero.
697** tid is omitted if we compile without threading support or on an OS
698** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000699*/
drh6c7d5c52008-11-21 20:32:33 +0000700struct unixLockKey {
701 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000702#if SQLITE_THREADSAFE && defined(__linux__)
703 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000704#endif
drhbbd42a62004-05-22 17:41:58 +0000705};
706
707/*
708** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000709** inode. Or, on LinuxThreads, there is one of these structures for
710** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000711**
danielk1977ad94b582007-08-20 06:44:22 +0000712** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000713** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000714** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000715*/
drh6c7d5c52008-11-21 20:32:33 +0000716struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000717 struct unixLockKey lockKey; /* The lookup key */
718 int cnt; /* Number of SHARED locks held */
719 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
720 int nRef; /* Number of pointers to this structure */
721 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
722 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000723};
724
725/*
726** An instance of the following structure is allocated for each open
727** inode. This structure keeps track of the number of locks on that
728** inode. If a close is attempted against an inode that is holding
729** locks, the close is deferred until all locks clear by adding the
730** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000731**
732** TODO: Consider changing this so that there is only a single file
733** descriptor for each open file, even when it is opened multiple times.
734** The close() system call would only occur when the last database
735** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000736*/
drh6c7d5c52008-11-21 20:32:33 +0000737struct unixOpenCnt {
738 struct unixFileId fileId; /* The lookup key */
739 int nRef; /* Number of pointers to this structure */
740 int nLock; /* Number of outstanding locks */
741 int nPending; /* Number of pending close() operations */
742 int *aPending; /* Malloced space holding fd's awaiting a close() */
743#if OS_VXWORKS
744 sem_t *pSem; /* Named POSIX semaphore */
chw97185482008-11-17 08:05:31 +0000745 char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
746#endif
drh6c7d5c52008-11-21 20:32:33 +0000747 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000748};
749
drhda0e7682008-07-30 15:27:54 +0000750/*
drh9b35ea62008-11-29 02:20:26 +0000751** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
752** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000753** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000754** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000755*/
drh6c7d5c52008-11-21 20:32:33 +0000756static struct unixLockInfo *lockList = 0;
757static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000758
drh5fdae772004-06-29 03:29:00 +0000759/*
drh9b35ea62008-11-29 02:20:26 +0000760** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000761** locks.
762**
drh9b35ea62008-11-29 02:20:26 +0000763** 0: No. Threads cannot override each others locks. (LinuxThreads)
764** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000765** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000766**
drh5062d3a2006-01-31 23:03:35 +0000767** On some systems, we know at compile-time if threads can override each
768** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
769** will be set appropriately. On other systems, we have to check at
770** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
771** undefined.
772**
drhf1a221e2006-01-15 17:27:17 +0000773** This variable normally has file scope only. But during testing, we make
774** it a global so that the test code can change its value in order to verify
775** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000776*/
drh715ff302008-12-03 22:32:44 +0000777#if SQLITE_THREADSAFE && defined(__linux__)
778# ifndef SQLITE_THREAD_OVERRIDE_LOCK
779# define SQLITE_THREAD_OVERRIDE_LOCK -1
780# endif
781# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000782int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000783# else
drh5062d3a2006-01-31 23:03:35 +0000784static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000785# endif
drh029b44b2006-01-15 00:13:15 +0000786#endif
drh5fdae772004-06-29 03:29:00 +0000787
788/*
789** This structure holds information passed into individual test
790** threads by the testThreadLockingBehavior() routine.
791*/
792struct threadTestData {
793 int fd; /* File to be locked */
794 struct flock lock; /* The locking operation */
795 int result; /* Result of the locking operation */
796};
797
drh6c7d5c52008-11-21 20:32:33 +0000798#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000799/*
danielk197741a6a612008-11-11 18:34:35 +0000800** This function is used as the main routine for a thread launched by
801** testThreadLockingBehavior(). It tests whether the shared-lock obtained
802** by the main thread in testThreadLockingBehavior() conflicts with a
803** hypothetical write-lock obtained by this thread on the same file.
804**
805** The write-lock is not actually acquired, as this is not possible if
806** the file is open in read-only mode (see ticket #3472).
807*/
drh5fdae772004-06-29 03:29:00 +0000808static void *threadLockingTest(void *pArg){
809 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000810 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000811 return pArg;
812}
drh6c7d5c52008-11-21 20:32:33 +0000813#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000814
drh6c7d5c52008-11-21 20:32:33 +0000815
816#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000817/*
818** This procedure attempts to determine whether or not threads
819** can override each others locks then sets the
820** threadsOverrideEachOthersLocks variable appropriately.
821*/
danielk19774d5238f2006-01-27 06:32:00 +0000822static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000823 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000824 int rc;
825 struct threadTestData d;
826 struct flock l;
827 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000828
829 fd = dup(fd_orig);
830 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000831 memset(&l, 0, sizeof(l));
832 l.l_type = F_RDLCK;
833 l.l_len = 1;
834 l.l_start = 0;
835 l.l_whence = SEEK_SET;
836 rc = fcntl(fd_orig, F_SETLK, &l);
837 if( rc!=0 ) return;
838 memset(&d, 0, sizeof(d));
839 d.fd = fd;
840 d.lock = l;
841 d.lock.l_type = F_WRLCK;
842 pthread_create(&t, 0, threadLockingTest, &d);
843 pthread_join(t, 0);
drh5fdae772004-06-29 03:29:00 +0000844 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000845 if( d.result!=0 ) return;
846 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000847}
drh6c7d5c52008-11-21 20:32:33 +0000848#endif /* SQLITE_THERADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000849
drhbbd42a62004-05-22 17:41:58 +0000850/*
drh6c7d5c52008-11-21 20:32:33 +0000851** Release a unixLockInfo structure previously allocated by findLockInfo().
852*/
853static void releaseLockInfo(struct unixLockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000854 if( pLock ){
855 pLock->nRef--;
856 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000857 if( pLock->pPrev ){
858 assert( pLock->pPrev->pNext==pLock );
859 pLock->pPrev->pNext = pLock->pNext;
860 }else{
861 assert( lockList==pLock );
862 lockList = pLock->pNext;
863 }
864 if( pLock->pNext ){
865 assert( pLock->pNext->pPrev==pLock );
866 pLock->pNext->pPrev = pLock->pPrev;
867 }
danielk1977e339d652008-06-28 11:23:00 +0000868 sqlite3_free(pLock);
869 }
drhbbd42a62004-05-22 17:41:58 +0000870 }
871}
872
873/*
drh6c7d5c52008-11-21 20:32:33 +0000874** Release a unixOpenCnt structure previously allocated by findLockInfo().
drhbbd42a62004-05-22 17:41:58 +0000875*/
drh6c7d5c52008-11-21 20:32:33 +0000876static void releaseOpenCnt(struct unixOpenCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000877 if( pOpen ){
878 pOpen->nRef--;
879 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000880 if( pOpen->pPrev ){
881 assert( pOpen->pPrev->pNext==pOpen );
882 pOpen->pPrev->pNext = pOpen->pNext;
883 }else{
884 assert( openList==pOpen );
885 openList = pOpen->pNext;
886 }
887 if( pOpen->pNext ){
888 assert( pOpen->pNext->pPrev==pOpen );
889 pOpen->pNext->pPrev = pOpen->pPrev;
890 }
891 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000892 sqlite3_free(pOpen);
893 }
drhbbd42a62004-05-22 17:41:58 +0000894 }
895}
896
drh6c7d5c52008-11-21 20:32:33 +0000897/*
898** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
899** describes that file descriptor. Create new ones if necessary. The
900** return values might be uninitialized if an error occurs.
901**
902** Return an appropriate error code.
903*/
904static int findLockInfo(
905 unixFile *pFile, /* Unix file with file desc used in the key */
906 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
907 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
908){
909 int rc; /* System call return code */
910 int fd; /* The file descriptor for pFile */
911 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
912 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
913 struct stat statbuf; /* Low-level file information */
914 struct unixLockInfo *pLock; /* Candidate unixLockInfo object */
915 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
916
917 /* Get low-level information about the file that we can used to
918 ** create a unique name for the file.
919 */
920 fd = pFile->h;
921 rc = fstat(fd, &statbuf);
922 if( rc!=0 ){
923 pFile->lastErrno = errno;
924#ifdef EOVERFLOW
925 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
926#endif
927 return SQLITE_IOERR;
928 }
929
drheb0d74f2009-02-03 15:27:02 +0000930#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000931 /* On OS X on an msdos filesystem, the inode number is reported
932 ** incorrectly for zero-size files. See ticket #3260. To work
933 ** around this problem (we consider it a bug in OS X, not SQLite)
934 ** we always increase the file size to 1 by writing a single byte
935 ** prior to accessing the inode number. The one byte written is
936 ** an ASCII 'S' character which also happens to be the first byte
937 ** in the header of every SQLite database. In this way, if there
938 ** is a race condition such that another thread has already populated
939 ** the first page of the database, no damage is done.
940 */
941 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000942 rc = write(fd, "S", 1);
943 if( rc!=1 ){
944 return SQLITE_IOERR;
945 }
drh6c7d5c52008-11-21 20:32:33 +0000946 rc = fstat(fd, &statbuf);
947 if( rc!=0 ){
948 pFile->lastErrno = errno;
949 return SQLITE_IOERR;
950 }
951 }
drheb0d74f2009-02-03 15:27:02 +0000952#endif
drh6c7d5c52008-11-21 20:32:33 +0000953
954 memset(&lockKey, 0, sizeof(lockKey));
955 lockKey.fid.dev = statbuf.st_dev;
956#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000957 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000958#else
959 lockKey.fid.ino = statbuf.st_ino;
960#endif
drh734c9862008-11-28 15:37:20 +0000961#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000962 if( threadsOverrideEachOthersLocks<0 ){
963 testThreadLockingBehavior(fd);
964 }
965 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
966#endif
967 fileId = lockKey.fid;
968 if( ppLock!=0 ){
969 pLock = lockList;
970 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
971 pLock = pLock->pNext;
972 }
973 if( pLock==0 ){
974 pLock = sqlite3_malloc( sizeof(*pLock) );
975 if( pLock==0 ){
976 rc = SQLITE_NOMEM;
977 goto exit_findlockinfo;
978 }
979 pLock->lockKey = lockKey;
980 pLock->nRef = 1;
981 pLock->cnt = 0;
982 pLock->locktype = 0;
983 pLock->pNext = lockList;
984 pLock->pPrev = 0;
985 if( lockList ) lockList->pPrev = pLock;
986 lockList = pLock;
987 }else{
988 pLock->nRef++;
989 }
990 *ppLock = pLock;
991 }
992 if( ppOpen!=0 ){
993 pOpen = openList;
994 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
995 pOpen = pOpen->pNext;
996 }
997 if( pOpen==0 ){
998 pOpen = sqlite3_malloc( sizeof(*pOpen) );
999 if( pOpen==0 ){
1000 releaseLockInfo(pLock);
1001 rc = SQLITE_NOMEM;
1002 goto exit_findlockinfo;
1003 }
1004 pOpen->fileId = fileId;
1005 pOpen->nRef = 1;
1006 pOpen->nLock = 0;
1007 pOpen->nPending = 0;
1008 pOpen->aPending = 0;
1009 pOpen->pNext = openList;
1010 pOpen->pPrev = 0;
1011 if( openList ) openList->pPrev = pOpen;
1012 openList = pOpen;
1013#if OS_VXWORKS
1014 pOpen->pSem = NULL;
1015 pOpen->aSemName[0] = '\0';
1016#endif
1017 }else{
1018 pOpen->nRef++;
1019 }
1020 *ppOpen = pOpen;
1021 }
1022
1023exit_findlockinfo:
1024 return rc;
1025}
drh6c7d5c52008-11-21 20:32:33 +00001026
drh7708e972008-11-29 00:56:52 +00001027/*
1028** If we are currently in a different thread than the thread that the
1029** unixFile argument belongs to, then transfer ownership of the unixFile
1030** over to the current thread.
1031**
1032** A unixFile is only owned by a thread on systems that use LinuxThreads.
1033**
1034** Ownership transfer is only allowed if the unixFile is currently unlocked.
1035** If the unixFile is locked and an ownership is wrong, then return
1036** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1037*/
1038#if SQLITE_THREADSAFE && defined(__linux__)
1039static int transferOwnership(unixFile *pFile){
1040 int rc;
1041 pthread_t hSelf;
1042 if( threadsOverrideEachOthersLocks ){
1043 /* Ownership transfers not needed on this system */
1044 return SQLITE_OK;
1045 }
1046 hSelf = pthread_self();
1047 if( pthread_equal(pFile->tid, hSelf) ){
1048 /* We are still in the same thread */
1049 OSTRACE1("No-transfer, same thread\n");
1050 return SQLITE_OK;
1051 }
1052 if( pFile->locktype!=NO_LOCK ){
1053 /* We cannot change ownership while we are holding a lock! */
1054 return SQLITE_MISUSE;
1055 }
1056 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1057 pFile->h, pFile->tid, hSelf);
1058 pFile->tid = hSelf;
1059 if (pFile->pLock != NULL) {
1060 releaseLockInfo(pFile->pLock);
1061 rc = findLockInfo(pFile, &pFile->pLock, 0);
1062 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1063 locktypeName(pFile->locktype),
1064 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1065 return rc;
1066 } else {
1067 return SQLITE_OK;
1068 }
1069}
1070#else /* if not SQLITE_THREADSAFE */
1071 /* On single-threaded builds, ownership transfer is a no-op */
1072# define transferOwnership(X) SQLITE_OK
1073#endif /* SQLITE_THREADSAFE */
1074
aswift5b1a2562008-08-22 00:22:35 +00001075
1076/*
danielk197713adf8a2004-06-03 16:08:41 +00001077** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001078** file by this or any other process. If such a lock is held, set *pResOut
1079** to a non-zero value otherwise *pResOut is set to zero. The return value
1080** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001081*/
danielk1977861f7452008-06-05 11:39:11 +00001082static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001083 int rc = SQLITE_OK;
1084 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001085 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001086
danielk1977861f7452008-06-05 11:39:11 +00001087 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1088
drh054889e2005-11-30 03:20:31 +00001089 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001090 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001091
1092 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001093 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001094 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001095 }
1096
drh2ac3ee92004-06-07 16:27:46 +00001097 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001098 */
danielk197709480a92009-02-09 05:32:32 +00001099#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001100 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001101 struct flock lock;
1102 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001103 lock.l_start = RESERVED_BYTE;
1104 lock.l_len = 1;
1105 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001106 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1107 int tErrno = errno;
1108 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1109 pFile->lastErrno = tErrno;
1110 } else if( lock.l_type!=F_UNLCK ){
1111 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001112 }
1113 }
danielk197709480a92009-02-09 05:32:32 +00001114#endif
danielk197713adf8a2004-06-03 16:08:41 +00001115
drh6c7d5c52008-11-21 20:32:33 +00001116 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001117 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001118
aswift5b1a2562008-08-22 00:22:35 +00001119 *pResOut = reserved;
1120 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001121}
1122
1123/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001124** Lock the file with the lock specified by parameter locktype - one
1125** of the following:
1126**
drh2ac3ee92004-06-07 16:27:46 +00001127** (1) SHARED_LOCK
1128** (2) RESERVED_LOCK
1129** (3) PENDING_LOCK
1130** (4) EXCLUSIVE_LOCK
1131**
drhb3e04342004-06-08 00:47:47 +00001132** Sometimes when requesting one lock state, additional lock states
1133** are inserted in between. The locking might fail on one of the later
1134** transitions leaving the lock state different from what it started but
1135** still short of its goal. The following chart shows the allowed
1136** transitions and the inserted intermediate states:
1137**
1138** UNLOCKED -> SHARED
1139** SHARED -> RESERVED
1140** SHARED -> (PENDING) -> EXCLUSIVE
1141** RESERVED -> (PENDING) -> EXCLUSIVE
1142** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001143**
drha6abd042004-06-09 17:37:22 +00001144** This routine will only increase a lock. Use the sqlite3OsUnlock()
1145** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001146*/
danielk197762079062007-08-15 17:08:46 +00001147static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001148 /* The following describes the implementation of the various locks and
1149 ** lock transitions in terms of the POSIX advisory shared and exclusive
1150 ** lock primitives (called read-locks and write-locks below, to avoid
1151 ** confusion with SQLite lock names). The algorithms are complicated
1152 ** slightly in order to be compatible with windows systems simultaneously
1153 ** accessing the same database file, in case that is ever required.
1154 **
1155 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1156 ** byte', each single bytes at well known offsets, and the 'shared byte
1157 ** range', a range of 510 bytes at a well known offset.
1158 **
1159 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1160 ** byte'. If this is successful, a random byte from the 'shared byte
1161 ** range' is read-locked and the lock on the 'pending byte' released.
1162 **
danielk197790ba3bd2004-06-25 08:32:25 +00001163 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1164 ** A RESERVED lock is implemented by grabbing a write-lock on the
1165 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001166 **
1167 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001168 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1169 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1170 ** obtained, but existing SHARED locks are allowed to persist. A process
1171 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1172 ** This property is used by the algorithm for rolling back a journal file
1173 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001174 **
danielk197790ba3bd2004-06-25 08:32:25 +00001175 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1176 ** implemented by obtaining a write-lock on the entire 'shared byte
1177 ** range'. Since all other locks require a read-lock on one of the bytes
1178 ** within this range, this ensures that no other locks are held on the
1179 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001180 **
1181 ** The reason a single byte cannot be used instead of the 'shared byte
1182 ** range' is that some versions of windows do not support read-locks. By
1183 ** locking a random byte from a range, concurrent SHARED locks may exist
1184 ** even if the locking primitive used is always a write-lock.
1185 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001186 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001187 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001188 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001189 struct flock lock;
1190 int s;
1191
drh054889e2005-11-30 03:20:31 +00001192 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001193 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001194 locktypeName(locktype), locktypeName(pFile->locktype),
1195 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001196
1197 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001198 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001199 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001200 */
drh054889e2005-11-30 03:20:31 +00001201 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001202 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001203 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001204 return SQLITE_OK;
1205 }
1206
drhb3e04342004-06-08 00:47:47 +00001207 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001208 */
drh054889e2005-11-30 03:20:31 +00001209 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001210 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001211 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001212
drh054889e2005-11-30 03:20:31 +00001213 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001214 */
drh6c7d5c52008-11-21 20:32:33 +00001215 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001216
drh029b44b2006-01-15 00:13:15 +00001217 /* Make sure the current thread owns the pFile.
1218 */
1219 rc = transferOwnership(pFile);
1220 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001221 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001222 return rc;
1223 }
drh64b1bea2006-01-15 02:30:57 +00001224 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001225
danielk1977ad94b582007-08-20 06:44:22 +00001226 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001227 ** handle that precludes the requested lock, return BUSY.
1228 */
drh054889e2005-11-30 03:20:31 +00001229 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001230 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001231 ){
1232 rc = SQLITE_BUSY;
1233 goto end_lock;
1234 }
1235
1236 /* If a SHARED lock is requested, and some thread using this PID already
1237 ** has a SHARED or RESERVED lock, then increment reference counts and
1238 ** return SQLITE_OK.
1239 */
1240 if( locktype==SHARED_LOCK &&
1241 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1242 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001243 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001244 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001245 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001246 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001247 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001248 goto end_lock;
1249 }
1250
danielk197713adf8a2004-06-03 16:08:41 +00001251 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001252
danielk19779a1d0ab2004-06-01 14:09:28 +00001253 lock.l_whence = SEEK_SET;
1254
drh3cde3bb2004-06-12 02:17:14 +00001255 /* A PENDING lock is needed before acquiring a SHARED lock and before
1256 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1257 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001258 */
drh3cde3bb2004-06-12 02:17:14 +00001259 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001260 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001261 ){
danielk1977489468c2004-06-28 08:25:47 +00001262 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001263 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001264 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001265 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001266 int tErrno = errno;
1267 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1268 if( IS_LOCK_ERROR(rc) ){
1269 pFile->lastErrno = tErrno;
1270 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001271 goto end_lock;
1272 }
drh3cde3bb2004-06-12 02:17:14 +00001273 }
1274
1275
1276 /* If control gets to this point, then actually go ahead and make
1277 ** operating system calls for the specified lock.
1278 */
1279 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001280 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001281 assert( pLock->cnt==0 );
1282 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001283
drh2ac3ee92004-06-07 16:27:46 +00001284 /* Now get the read-lock */
1285 lock.l_start = SHARED_FIRST;
1286 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001287 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1288 tErrno = errno;
1289 }
drh2ac3ee92004-06-07 16:27:46 +00001290 /* Drop the temporary PENDING lock */
1291 lock.l_start = PENDING_BYTE;
1292 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001293 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001294 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001295 if( s != -1 ){
1296 /* This could happen with a network mount */
1297 tErrno = errno;
1298 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1299 if( IS_LOCK_ERROR(rc) ){
1300 pFile->lastErrno = tErrno;
1301 }
1302 goto end_lock;
1303 }
drh2b4b5962005-06-15 17:47:55 +00001304 }
drhe2396a12007-03-29 20:19:58 +00001305 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001306 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1307 if( IS_LOCK_ERROR(rc) ){
1308 pFile->lastErrno = tErrno;
1309 }
drhbbd42a62004-05-22 17:41:58 +00001310 }else{
drh054889e2005-11-30 03:20:31 +00001311 pFile->locktype = SHARED_LOCK;
1312 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001313 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001314 }
drh3cde3bb2004-06-12 02:17:14 +00001315 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1316 /* We are trying for an exclusive lock but another thread in this
1317 ** same process is still holding a shared lock. */
1318 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001319 }else{
drh3cde3bb2004-06-12 02:17:14 +00001320 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001321 ** assumed that there is a SHARED or greater lock on the file
1322 ** already.
1323 */
drh054889e2005-11-30 03:20:31 +00001324 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001325 lock.l_type = F_WRLCK;
1326 switch( locktype ){
1327 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001328 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001329 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001330 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001331 lock.l_start = SHARED_FIRST;
1332 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001333 break;
1334 default:
1335 assert(0);
1336 }
drh054889e2005-11-30 03:20:31 +00001337 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001338 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001339 int tErrno = errno;
1340 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1341 if( IS_LOCK_ERROR(rc) ){
1342 pFile->lastErrno = tErrno;
1343 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001344 }
drhbbd42a62004-05-22 17:41:58 +00001345 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001346
drh8f941bc2009-01-14 23:03:40 +00001347
1348#ifndef NDEBUG
1349 /* Set up the transaction-counter change checking flags when
1350 ** transitioning from a SHARED to a RESERVED lock. The change
1351 ** from SHARED to RESERVED marks the beginning of a normal
1352 ** write operation (not a hot journal rollback).
1353 */
1354 if( rc==SQLITE_OK
1355 && pFile->locktype<=SHARED_LOCK
1356 && locktype==RESERVED_LOCK
1357 ){
1358 pFile->transCntrChng = 0;
1359 pFile->dbUpdate = 0;
1360 pFile->inNormalWrite = 1;
1361 }
1362#endif
1363
1364
danielk1977ecb2a962004-06-02 06:30:16 +00001365 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001366 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001367 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001368 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001369 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001370 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001371 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001372
1373end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001374 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001375 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001376 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001377 return rc;
1378}
1379
1380/*
drh054889e2005-11-30 03:20:31 +00001381** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001382** must be either NO_LOCK or SHARED_LOCK.
1383**
1384** If the locking level of the file descriptor is already at or below
1385** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001386*/
danielk197762079062007-08-15 17:08:46 +00001387static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001388 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001389 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001390 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001391 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001392 int h;
drha6abd042004-06-09 17:37:22 +00001393
drh054889e2005-11-30 03:20:31 +00001394 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001395 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001396 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001397
1398 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001399 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001400 return SQLITE_OK;
1401 }
drhf1a221e2006-01-15 17:27:17 +00001402 if( CHECK_THREADID(pFile) ){
1403 return SQLITE_MISUSE;
1404 }
drh6c7d5c52008-11-21 20:32:33 +00001405 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001406 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001407 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001408 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001409 if( pFile->locktype>SHARED_LOCK ){
1410 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001411 SimulateIOErrorBenign(1);
1412 SimulateIOError( h=(-1) )
1413 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001414
1415#ifndef NDEBUG
1416 /* When reducing a lock such that other processes can start
1417 ** reading the database file again, make sure that the
1418 ** transaction counter was updated if any part of the database
1419 ** file changed. If the transaction counter is not updated,
1420 ** other connections to the same file might not realize that
1421 ** the file has changed and hence might not know to flush their
1422 ** cache. The use of a stale cache can lead to database corruption.
1423 */
1424 assert( pFile->inNormalWrite==0
1425 || pFile->dbUpdate==0
1426 || pFile->transCntrChng==1 );
1427 pFile->inNormalWrite = 0;
1428#endif
1429
1430
drh9c105bb2004-10-02 20:38:28 +00001431 if( locktype==SHARED_LOCK ){
1432 lock.l_type = F_RDLCK;
1433 lock.l_whence = SEEK_SET;
1434 lock.l_start = SHARED_FIRST;
1435 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001436 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001437 int tErrno = errno;
1438 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1439 if( IS_LOCK_ERROR(rc) ){
1440 pFile->lastErrno = tErrno;
1441 }
danielk197709480a92009-02-09 05:32:32 +00001442 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001443 }
1444 }
drhbbd42a62004-05-22 17:41:58 +00001445 lock.l_type = F_UNLCK;
1446 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001447 lock.l_start = PENDING_BYTE;
1448 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001449 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001450 pLock->locktype = SHARED_LOCK;
1451 }else{
aswift5b1a2562008-08-22 00:22:35 +00001452 int tErrno = errno;
1453 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1454 if( IS_LOCK_ERROR(rc) ){
1455 pFile->lastErrno = tErrno;
1456 }
drhcd731cf2009-03-28 23:23:02 +00001457 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001458 }
drhbbd42a62004-05-22 17:41:58 +00001459 }
drha6abd042004-06-09 17:37:22 +00001460 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001461 struct unixOpenCnt *pOpen;
danielk197764a54c52009-03-30 07:39:35 +00001462 int rc2 = SQLITE_OK;
danielk1977ecb2a962004-06-02 06:30:16 +00001463
drha6abd042004-06-09 17:37:22 +00001464 /* Decrement the shared lock counter. Release the lock using an
1465 ** OS call only when all threads in this same process have released
1466 ** the lock.
1467 */
1468 pLock->cnt--;
1469 if( pLock->cnt==0 ){
1470 lock.l_type = F_UNLCK;
1471 lock.l_whence = SEEK_SET;
1472 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001473 SimulateIOErrorBenign(1);
1474 SimulateIOError( h=(-1) )
1475 SimulateIOErrorBenign(0);
1476 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001477 pLock->locktype = NO_LOCK;
1478 }else{
aswift5b1a2562008-08-22 00:22:35 +00001479 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001480 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001481 if( IS_LOCK_ERROR(rc) ){
1482 pFile->lastErrno = tErrno;
1483 }
drhf48f9ca2009-03-28 23:47:10 +00001484 pLock->locktype = NO_LOCK;
1485 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001486 }
drha6abd042004-06-09 17:37:22 +00001487 }
1488
drhbbd42a62004-05-22 17:41:58 +00001489 /* Decrement the count of locks against this same file. When the
1490 ** count reaches zero, close any other file descriptors whose close
1491 ** was deferred because of outstanding locks.
1492 */
danielk197764a54c52009-03-30 07:39:35 +00001493 pOpen = pFile->pOpen;
1494 pOpen->nLock--;
1495 assert( pOpen->nLock>=0 );
1496 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1497 int i;
1498 for(i=0; i<pOpen->nPending; i++){
1499 /* close pending fds, but if closing fails don't free the array
1500 ** assign -1 to the successfully closed descriptors and record the
1501 ** error. The next attempt to unlock will try again. */
1502 if( pOpen->aPending[i] < 0 ) continue;
1503 if( close(pOpen->aPending[i]) ){
1504 pFile->lastErrno = errno;
1505 rc2 = SQLITE_IOERR_CLOSE;
1506 }else{
1507 pOpen->aPending[i] = -1;
aswiftaebf4132008-11-21 00:10:35 +00001508 }
drhbbd42a62004-05-22 17:41:58 +00001509 }
danielk197764a54c52009-03-30 07:39:35 +00001510 if( rc2==SQLITE_OK ){
1511 sqlite3_free(pOpen->aPending);
1512 pOpen->nPending = 0;
1513 pOpen->aPending = 0;
1514 }
1515 }
1516 if( rc==SQLITE_OK ){
1517 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001518 }
1519 }
aswift5b1a2562008-08-22 00:22:35 +00001520
1521end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001522 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001523 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001524 return rc;
drhbbd42a62004-05-22 17:41:58 +00001525}
1526
1527/*
danielk1977e339d652008-06-28 11:23:00 +00001528** This function performs the parts of the "close file" operation
1529** common to all locking schemes. It closes the directory and file
1530** handles, if they are valid, and sets all fields of the unixFile
1531** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001532**
1533** It is *not* necessary to hold the mutex when this routine is called,
1534** even on VxWorks. A mutex will be acquired on VxWorks by the
1535** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001536*/
1537static int closeUnixFile(sqlite3_file *id){
1538 unixFile *pFile = (unixFile*)id;
1539 if( pFile ){
1540 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001541 int err = close(pFile->dirfd);
1542 if( err ){
1543 pFile->lastErrno = errno;
1544 return SQLITE_IOERR_DIR_CLOSE;
1545 }else{
1546 pFile->dirfd=-1;
1547 }
danielk1977e339d652008-06-28 11:23:00 +00001548 }
1549 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001550 int err = close(pFile->h);
1551 if( err ){
1552 pFile->lastErrno = errno;
1553 return SQLITE_IOERR_CLOSE;
1554 }
danielk1977e339d652008-06-28 11:23:00 +00001555 }
drh6c7d5c52008-11-21 20:32:33 +00001556#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001557 if( pFile->pId ){
1558 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001559 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001560 }
drh107886a2008-11-21 22:21:50 +00001561 vxworksReleaseFileId(pFile->pId);
1562 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001563 }
1564#endif
danielk1977e339d652008-06-28 11:23:00 +00001565 OSTRACE2("CLOSE %-3d\n", pFile->h);
1566 OpenCounter(-1);
1567 memset(pFile, 0, sizeof(unixFile));
1568 }
1569 return SQLITE_OK;
1570}
1571
1572/*
danielk1977e3026632004-06-22 11:29:02 +00001573** Close a file.
1574*/
danielk197762079062007-08-15 17:08:46 +00001575static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001576 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001577 if( id ){
1578 unixFile *pFile = (unixFile *)id;
1579 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001580 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001581 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001582 /* If there are outstanding locks, do not actually close the file just
1583 ** yet because that would clear those locks. Instead, add the file
1584 ** descriptor to pOpen->aPending. It will be automatically closed when
1585 ** the last lock is cleared.
1586 */
1587 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001588 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001589 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001590 if( aNew==0 ){
1591 /* If a malloc fails, just leak the file descriptor */
1592 }else{
1593 pOpen->aPending = aNew;
1594 pOpen->aPending[pOpen->nPending] = pFile->h;
1595 pOpen->nPending++;
1596 pFile->h = -1;
1597 }
danielk1977e3026632004-06-22 11:29:02 +00001598 }
danielk1977e339d652008-06-28 11:23:00 +00001599 releaseLockInfo(pFile->pLock);
1600 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001601 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001602 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001603 }
aswiftaebf4132008-11-21 00:10:35 +00001604 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001605}
1606
drh734c9862008-11-28 15:37:20 +00001607/************** End of the posix advisory lock implementation *****************
1608******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001609
drh734c9862008-11-28 15:37:20 +00001610/******************************************************************************
1611****************************** No-op Locking **********************************
1612**
1613** Of the various locking implementations available, this is by far the
1614** simplest: locking is ignored. No attempt is made to lock the database
1615** file for reading or writing.
1616**
1617** This locking mode is appropriate for use on read-only databases
1618** (ex: databases that are burned into CD-ROM, for example.) It can
1619** also be used if the application employs some external mechanism to
1620** prevent simultaneous access of the same database by two or more
1621** database connections. But there is a serious risk of database
1622** corruption if this locking mode is used in situations where multiple
1623** database connections are accessing the same database file at the same
1624** time and one or more of those connections are writing.
1625*/
drhbfe66312006-10-03 17:40:40 +00001626
drh734c9862008-11-28 15:37:20 +00001627static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1628 UNUSED_PARAMETER(NotUsed);
1629 *pResOut = 0;
1630 return SQLITE_OK;
1631}
drh734c9862008-11-28 15:37:20 +00001632static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1633 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1634 return SQLITE_OK;
1635}
drh734c9862008-11-28 15:37:20 +00001636static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1637 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1638 return SQLITE_OK;
1639}
1640
1641/*
drh9b35ea62008-11-29 02:20:26 +00001642** Close the file.
drh734c9862008-11-28 15:37:20 +00001643*/
1644static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001645 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001646}
1647
1648/******************* End of the no-op lock implementation *********************
1649******************************************************************************/
1650
1651/******************************************************************************
1652************************* Begin dot-file Locking ******************************
1653**
1654** The dotfile locking implementation uses the existing of separate lock
1655** files in order to control access to the database. This works on just
1656** about every filesystem imaginable. But there are serious downsides:
1657**
1658** (1) There is zero concurrency. A single reader blocks all other
1659** connections from reading or writing the database.
1660**
1661** (2) An application crash or power loss can leave stale lock files
1662** sitting around that need to be cleared manually.
1663**
1664** Nevertheless, a dotlock is an appropriate locking mode for use if no
1665** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001666**
1667** Dotfile locking works by creating a file in the same directory as the
1668** database and with the same name but with a ".lock" extension added.
1669** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1670** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001671*/
1672
1673/*
1674** The file suffix added to the data base filename in order to create the
1675** lock file.
1676*/
1677#define DOTLOCK_SUFFIX ".lock"
1678
drh7708e972008-11-29 00:56:52 +00001679/*
1680** This routine checks if there is a RESERVED lock held on the specified
1681** file by this or any other process. If such a lock is held, set *pResOut
1682** to a non-zero value otherwise *pResOut is set to zero. The return value
1683** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1684**
1685** In dotfile locking, either a lock exists or it does not. So in this
1686** variation of CheckReservedLock(), *pResOut is set to true if any lock
1687** is held on the file and false if the file is unlocked.
1688*/
drh734c9862008-11-28 15:37:20 +00001689static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1690 int rc = SQLITE_OK;
1691 int reserved = 0;
1692 unixFile *pFile = (unixFile*)id;
1693
1694 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1695
1696 assert( pFile );
1697
1698 /* Check if a thread in this process holds such a lock */
1699 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001700 /* Either this connection or some other connection in the same process
1701 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001702 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001703 }else{
1704 /* The lock is held if and only if the lockfile exists */
1705 const char *zLockFile = (const char*)pFile->lockingContext;
1706 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001707 }
1708 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001709 *pResOut = reserved;
1710 return rc;
1711}
1712
drh7708e972008-11-29 00:56:52 +00001713/*
1714** Lock the file with the lock specified by parameter locktype - one
1715** of the following:
1716**
1717** (1) SHARED_LOCK
1718** (2) RESERVED_LOCK
1719** (3) PENDING_LOCK
1720** (4) EXCLUSIVE_LOCK
1721**
1722** Sometimes when requesting one lock state, additional lock states
1723** are inserted in between. The locking might fail on one of the later
1724** transitions leaving the lock state different from what it started but
1725** still short of its goal. The following chart shows the allowed
1726** transitions and the inserted intermediate states:
1727**
1728** UNLOCKED -> SHARED
1729** SHARED -> RESERVED
1730** SHARED -> (PENDING) -> EXCLUSIVE
1731** RESERVED -> (PENDING) -> EXCLUSIVE
1732** PENDING -> EXCLUSIVE
1733**
1734** This routine will only increase a lock. Use the sqlite3OsUnlock()
1735** routine to lower a locking level.
1736**
1737** With dotfile locking, we really only support state (4): EXCLUSIVE.
1738** But we track the other locking levels internally.
1739*/
drh734c9862008-11-28 15:37:20 +00001740static int dotlockLock(sqlite3_file *id, int locktype) {
1741 unixFile *pFile = (unixFile*)id;
1742 int fd;
1743 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001744 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001745
drh7708e972008-11-29 00:56:52 +00001746
1747 /* If we have any lock, then the lock file already exists. All we have
1748 ** to do is adjust our internal record of the lock level.
1749 */
1750 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001751 pFile->locktype = locktype;
1752#if !OS_VXWORKS
1753 /* Always update the timestamp on the old file */
1754 utimes(zLockFile, NULL);
1755#endif
drh7708e972008-11-29 00:56:52 +00001756 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001757 }
1758
1759 /* grab an exclusive lock */
1760 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1761 if( fd<0 ){
1762 /* failed to open/create the file, someone else may have stolen the lock */
1763 int tErrno = errno;
1764 if( EEXIST == tErrno ){
1765 rc = SQLITE_BUSY;
1766 } else {
1767 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1768 if( IS_LOCK_ERROR(rc) ){
1769 pFile->lastErrno = tErrno;
1770 }
1771 }
drh7708e972008-11-29 00:56:52 +00001772 return rc;
drh734c9862008-11-28 15:37:20 +00001773 }
1774 if( close(fd) ){
1775 pFile->lastErrno = errno;
1776 rc = SQLITE_IOERR_CLOSE;
1777 }
1778
1779 /* got it, set the type and return ok */
1780 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001781 return rc;
1782}
1783
drh7708e972008-11-29 00:56:52 +00001784/*
1785** Lower the locking level on file descriptor pFile to locktype. locktype
1786** must be either NO_LOCK or SHARED_LOCK.
1787**
1788** If the locking level of the file descriptor is already at or below
1789** the requested locking level, this routine is a no-op.
1790**
1791** When the locking level reaches NO_LOCK, delete the lock file.
1792*/
drh734c9862008-11-28 15:37:20 +00001793static int dotlockUnlock(sqlite3_file *id, int locktype) {
1794 unixFile *pFile = (unixFile*)id;
1795 char *zLockFile = (char *)pFile->lockingContext;
1796
1797 assert( pFile );
1798 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1799 pFile->locktype, getpid());
1800 assert( locktype<=SHARED_LOCK );
1801
1802 /* no-op if possible */
1803 if( pFile->locktype==locktype ){
1804 return SQLITE_OK;
1805 }
drh7708e972008-11-29 00:56:52 +00001806
1807 /* To downgrade to shared, simply update our internal notion of the
1808 ** lock state. No need to mess with the file on disk.
1809 */
1810 if( locktype==SHARED_LOCK ){
1811 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001812 return SQLITE_OK;
1813 }
1814
drh7708e972008-11-29 00:56:52 +00001815 /* To fully unlock the database, delete the lock file */
1816 assert( locktype==NO_LOCK );
1817 if( unlink(zLockFile) ){
drh734c9862008-11-28 15:37:20 +00001818 int rc, tErrno = errno;
1819 if( ENOENT != tErrno ){
1820 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1821 }
1822 if( IS_LOCK_ERROR(rc) ){
1823 pFile->lastErrno = tErrno;
1824 }
1825 return rc;
1826 }
1827 pFile->locktype = NO_LOCK;
1828 return SQLITE_OK;
1829}
1830
1831/*
drh9b35ea62008-11-29 02:20:26 +00001832** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001833*/
1834static int dotlockClose(sqlite3_file *id) {
1835 int rc;
1836 if( id ){
1837 unixFile *pFile = (unixFile*)id;
1838 dotlockUnlock(id, NO_LOCK);
1839 sqlite3_free(pFile->lockingContext);
1840 }
drh734c9862008-11-28 15:37:20 +00001841 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001842 return rc;
1843}
1844/****************** End of the dot-file lock implementation *******************
1845******************************************************************************/
1846
1847/******************************************************************************
1848************************** Begin flock Locking ********************************
1849**
1850** Use the flock() system call to do file locking.
1851**
drh6b9d6dd2008-12-03 19:34:47 +00001852** flock() locking is like dot-file locking in that the various
1853** fine-grain locking levels supported by SQLite are collapsed into
1854** a single exclusive lock. In other words, SHARED, RESERVED, and
1855** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1856** still works when you do this, but concurrency is reduced since
1857** only a single process can be reading the database at a time.
1858**
drh734c9862008-11-28 15:37:20 +00001859** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1860** compiling for VXWORKS.
1861*/
1862#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001863
drh6b9d6dd2008-12-03 19:34:47 +00001864/*
1865** This routine checks if there is a RESERVED lock held on the specified
1866** file by this or any other process. If such a lock is held, set *pResOut
1867** to a non-zero value otherwise *pResOut is set to zero. The return value
1868** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1869*/
drh734c9862008-11-28 15:37:20 +00001870static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1871 int rc = SQLITE_OK;
1872 int reserved = 0;
1873 unixFile *pFile = (unixFile*)id;
1874
1875 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1876
1877 assert( pFile );
1878
1879 /* Check if a thread in this process holds such a lock */
1880 if( pFile->locktype>SHARED_LOCK ){
1881 reserved = 1;
1882 }
1883
1884 /* Otherwise see if some other process holds it. */
1885 if( !reserved ){
1886 /* attempt to get the lock */
1887 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1888 if( !lrc ){
1889 /* got the lock, unlock it */
1890 lrc = flock(pFile->h, LOCK_UN);
1891 if ( lrc ) {
1892 int tErrno = errno;
1893 /* unlock failed with an error */
1894 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1895 if( IS_LOCK_ERROR(lrc) ){
1896 pFile->lastErrno = tErrno;
1897 rc = lrc;
1898 }
1899 }
1900 } else {
1901 int tErrno = errno;
1902 reserved = 1;
1903 /* someone else might have it reserved */
1904 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1905 if( IS_LOCK_ERROR(lrc) ){
1906 pFile->lastErrno = tErrno;
1907 rc = lrc;
1908 }
1909 }
1910 }
1911 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1912
1913#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1914 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1915 rc = SQLITE_OK;
1916 reserved=1;
1917 }
1918#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1919 *pResOut = reserved;
1920 return rc;
1921}
1922
drh6b9d6dd2008-12-03 19:34:47 +00001923/*
1924** Lock the file with the lock specified by parameter locktype - one
1925** of the following:
1926**
1927** (1) SHARED_LOCK
1928** (2) RESERVED_LOCK
1929** (3) PENDING_LOCK
1930** (4) EXCLUSIVE_LOCK
1931**
1932** Sometimes when requesting one lock state, additional lock states
1933** are inserted in between. The locking might fail on one of the later
1934** transitions leaving the lock state different from what it started but
1935** still short of its goal. The following chart shows the allowed
1936** transitions and the inserted intermediate states:
1937**
1938** UNLOCKED -> SHARED
1939** SHARED -> RESERVED
1940** SHARED -> (PENDING) -> EXCLUSIVE
1941** RESERVED -> (PENDING) -> EXCLUSIVE
1942** PENDING -> EXCLUSIVE
1943**
1944** flock() only really support EXCLUSIVE locks. We track intermediate
1945** lock states in the sqlite3_file structure, but all locks SHARED or
1946** above are really EXCLUSIVE locks and exclude all other processes from
1947** access the file.
1948**
1949** This routine will only increase a lock. Use the sqlite3OsUnlock()
1950** routine to lower a locking level.
1951*/
drh734c9862008-11-28 15:37:20 +00001952static int flockLock(sqlite3_file *id, int locktype) {
1953 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001954 unixFile *pFile = (unixFile*)id;
1955
1956 assert( pFile );
1957
1958 /* if we already have a lock, it is exclusive.
1959 ** Just adjust level and punt on outta here. */
1960 if (pFile->locktype > NO_LOCK) {
1961 pFile->locktype = locktype;
1962 return SQLITE_OK;
1963 }
1964
1965 /* grab an exclusive lock */
1966
1967 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1968 int tErrno = errno;
1969 /* didn't get, must be busy */
1970 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1971 if( IS_LOCK_ERROR(rc) ){
1972 pFile->lastErrno = tErrno;
1973 }
1974 } else {
1975 /* got it, set the type and return ok */
1976 pFile->locktype = locktype;
1977 }
1978 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1979 rc==SQLITE_OK ? "ok" : "failed");
1980#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1981 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1982 rc = SQLITE_BUSY;
1983 }
1984#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1985 return rc;
1986}
1987
drh6b9d6dd2008-12-03 19:34:47 +00001988
1989/*
1990** Lower the locking level on file descriptor pFile to locktype. locktype
1991** must be either NO_LOCK or SHARED_LOCK.
1992**
1993** If the locking level of the file descriptor is already at or below
1994** the requested locking level, this routine is a no-op.
1995*/
drh734c9862008-11-28 15:37:20 +00001996static int flockUnlock(sqlite3_file *id, int locktype) {
1997 unixFile *pFile = (unixFile*)id;
1998
1999 assert( pFile );
2000 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2001 pFile->locktype, getpid());
2002 assert( locktype<=SHARED_LOCK );
2003
2004 /* no-op if possible */
2005 if( pFile->locktype==locktype ){
2006 return SQLITE_OK;
2007 }
2008
2009 /* shared can just be set because we always have an exclusive */
2010 if (locktype==SHARED_LOCK) {
2011 pFile->locktype = locktype;
2012 return SQLITE_OK;
2013 }
2014
2015 /* no, really, unlock. */
2016 int rc = flock(pFile->h, LOCK_UN);
2017 if (rc) {
2018 int r, tErrno = errno;
2019 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2020 if( IS_LOCK_ERROR(r) ){
2021 pFile->lastErrno = tErrno;
2022 }
2023#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2024 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2025 r = SQLITE_BUSY;
2026 }
2027#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2028
2029 return r;
2030 } else {
2031 pFile->locktype = NO_LOCK;
2032 return SQLITE_OK;
2033 }
2034}
2035
2036/*
2037** Close a file.
2038*/
2039static int flockClose(sqlite3_file *id) {
2040 if( id ){
2041 flockUnlock(id, NO_LOCK);
2042 }
2043 return closeUnixFile(id);
2044}
2045
2046#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2047
2048/******************* End of the flock lock implementation *********************
2049******************************************************************************/
2050
2051/******************************************************************************
2052************************ Begin Named Semaphore Locking ************************
2053**
2054** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002055**
2056** Semaphore locking is like dot-lock and flock in that it really only
2057** supports EXCLUSIVE locking. Only a single process can read or write
2058** the database file at a time. This reduces potential concurrency, but
2059** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002060*/
2061#if OS_VXWORKS
2062
drh6b9d6dd2008-12-03 19:34:47 +00002063/*
2064** This routine checks if there is a RESERVED lock held on the specified
2065** file by this or any other process. If such a lock is held, set *pResOut
2066** to a non-zero value otherwise *pResOut is set to zero. The return value
2067** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2068*/
drh734c9862008-11-28 15:37:20 +00002069static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2070 int rc = SQLITE_OK;
2071 int reserved = 0;
2072 unixFile *pFile = (unixFile*)id;
2073
2074 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2075
2076 assert( pFile );
2077
2078 /* Check if a thread in this process holds such a lock */
2079 if( pFile->locktype>SHARED_LOCK ){
2080 reserved = 1;
2081 }
2082
2083 /* Otherwise see if some other process holds it. */
2084 if( !reserved ){
2085 sem_t *pSem = pFile->pOpen->pSem;
2086 struct stat statBuf;
2087
2088 if( sem_trywait(pSem)==-1 ){
2089 int tErrno = errno;
2090 if( EAGAIN != tErrno ){
2091 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2092 pFile->lastErrno = tErrno;
2093 } else {
2094 /* someone else has the lock when we are in NO_LOCK */
2095 reserved = (pFile->locktype < SHARED_LOCK);
2096 }
2097 }else{
2098 /* we could have it if we want it */
2099 sem_post(pSem);
2100 }
2101 }
2102 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2103
2104 *pResOut = reserved;
2105 return rc;
2106}
2107
drh6b9d6dd2008-12-03 19:34:47 +00002108/*
2109** Lock the file with the lock specified by parameter locktype - one
2110** of the following:
2111**
2112** (1) SHARED_LOCK
2113** (2) RESERVED_LOCK
2114** (3) PENDING_LOCK
2115** (4) EXCLUSIVE_LOCK
2116**
2117** Sometimes when requesting one lock state, additional lock states
2118** are inserted in between. The locking might fail on one of the later
2119** transitions leaving the lock state different from what it started but
2120** still short of its goal. The following chart shows the allowed
2121** transitions and the inserted intermediate states:
2122**
2123** UNLOCKED -> SHARED
2124** SHARED -> RESERVED
2125** SHARED -> (PENDING) -> EXCLUSIVE
2126** RESERVED -> (PENDING) -> EXCLUSIVE
2127** PENDING -> EXCLUSIVE
2128**
2129** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2130** lock states in the sqlite3_file structure, but all locks SHARED or
2131** above are really EXCLUSIVE locks and exclude all other processes from
2132** access the file.
2133**
2134** This routine will only increase a lock. Use the sqlite3OsUnlock()
2135** routine to lower a locking level.
2136*/
drh734c9862008-11-28 15:37:20 +00002137static int semLock(sqlite3_file *id, int locktype) {
2138 unixFile *pFile = (unixFile*)id;
2139 int fd;
2140 sem_t *pSem = pFile->pOpen->pSem;
2141 int rc = SQLITE_OK;
2142
2143 /* if we already have a lock, it is exclusive.
2144 ** Just adjust level and punt on outta here. */
2145 if (pFile->locktype > NO_LOCK) {
2146 pFile->locktype = locktype;
2147 rc = SQLITE_OK;
2148 goto sem_end_lock;
2149 }
2150
2151 /* lock semaphore now but bail out when already locked. */
2152 if( sem_trywait(pSem)==-1 ){
2153 rc = SQLITE_BUSY;
2154 goto sem_end_lock;
2155 }
2156
2157 /* got it, set the type and return ok */
2158 pFile->locktype = locktype;
2159
2160 sem_end_lock:
2161 return rc;
2162}
2163
drh6b9d6dd2008-12-03 19:34:47 +00002164/*
2165** Lower the locking level on file descriptor pFile to locktype. locktype
2166** must be either NO_LOCK or SHARED_LOCK.
2167**
2168** If the locking level of the file descriptor is already at or below
2169** the requested locking level, this routine is a no-op.
2170*/
drh734c9862008-11-28 15:37:20 +00002171static int semUnlock(sqlite3_file *id, int locktype) {
2172 unixFile *pFile = (unixFile*)id;
2173 sem_t *pSem = pFile->pOpen->pSem;
2174
2175 assert( pFile );
2176 assert( pSem );
2177 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2178 pFile->locktype, getpid());
2179 assert( locktype<=SHARED_LOCK );
2180
2181 /* no-op if possible */
2182 if( pFile->locktype==locktype ){
2183 return SQLITE_OK;
2184 }
2185
2186 /* shared can just be set because we always have an exclusive */
2187 if (locktype==SHARED_LOCK) {
2188 pFile->locktype = locktype;
2189 return SQLITE_OK;
2190 }
2191
2192 /* no, really unlock. */
2193 if ( sem_post(pSem)==-1 ) {
2194 int rc, tErrno = errno;
2195 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2196 if( IS_LOCK_ERROR(rc) ){
2197 pFile->lastErrno = tErrno;
2198 }
2199 return rc;
2200 }
2201 pFile->locktype = NO_LOCK;
2202 return SQLITE_OK;
2203}
2204
2205/*
2206 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002207 */
drh734c9862008-11-28 15:37:20 +00002208static int semClose(sqlite3_file *id) {
2209 if( id ){
2210 unixFile *pFile = (unixFile*)id;
2211 semUnlock(id, NO_LOCK);
2212 assert( pFile );
2213 unixEnterMutex();
2214 releaseLockInfo(pFile->pLock);
2215 releaseOpenCnt(pFile->pOpen);
2216 closeUnixFile(id);
2217 unixLeaveMutex();
2218 }
2219 return SQLITE_OK;
2220}
2221
2222#endif /* OS_VXWORKS */
2223/*
2224** Named semaphore locking is only available on VxWorks.
2225**
2226*************** End of the named semaphore lock implementation ****************
2227******************************************************************************/
2228
2229
2230/******************************************************************************
2231*************************** Begin AFP Locking *********************************
2232**
2233** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2234** on Apple Macintosh computers - both OS9 and OSX.
2235**
2236** Third-party implementations of AFP are available. But this code here
2237** only works on OSX.
2238*/
2239
drhd2cb50b2009-01-09 21:41:17 +00002240#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002241/*
2242** The afpLockingContext structure contains all afp lock specific state
2243*/
drhbfe66312006-10-03 17:40:40 +00002244typedef struct afpLockingContext afpLockingContext;
2245struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002246 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002247 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002248};
2249
2250struct ByteRangeLockPB2
2251{
2252 unsigned long long offset; /* offset to first byte to lock */
2253 unsigned long long length; /* nbr of bytes to lock */
2254 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2255 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2256 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2257 int fd; /* file desc to assoc this lock with */
2258};
2259
drhfd131da2007-08-07 17:13:03 +00002260#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002261
drh6b9d6dd2008-12-03 19:34:47 +00002262/*
2263** This is a utility for setting or clearing a bit-range lock on an
2264** AFP filesystem.
2265**
2266** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2267*/
2268static int afpSetLock(
2269 const char *path, /* Name of the file to be locked or unlocked */
2270 unixFile *pFile, /* Open file descriptor on path */
2271 unsigned long long offset, /* First byte to be locked */
2272 unsigned long long length, /* Number of bytes to lock */
2273 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002274){
drh6b9d6dd2008-12-03 19:34:47 +00002275 struct ByteRangeLockPB2 pb;
2276 int err;
drhbfe66312006-10-03 17:40:40 +00002277
2278 pb.unLockFlag = setLockFlag ? 0 : 1;
2279 pb.startEndFlag = 0;
2280 pb.offset = offset;
2281 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002282 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002283
2284 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002285 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2286 offset, length);
drhbfe66312006-10-03 17:40:40 +00002287 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2288 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002289 int rc;
2290 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002291 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2292 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002293#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2294 rc = SQLITE_BUSY;
2295#else
drh734c9862008-11-28 15:37:20 +00002296 rc = sqliteErrorFromPosixError(tErrno,
2297 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002298#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002299 if( IS_LOCK_ERROR(rc) ){
2300 pFile->lastErrno = tErrno;
2301 }
2302 return rc;
drhbfe66312006-10-03 17:40:40 +00002303 } else {
aswift5b1a2562008-08-22 00:22:35 +00002304 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002305 }
2306}
2307
drh6b9d6dd2008-12-03 19:34:47 +00002308/*
2309** This routine checks if there is a RESERVED lock held on the specified
2310** file by this or any other process. If such a lock is held, set *pResOut
2311** to a non-zero value otherwise *pResOut is set to zero. The return value
2312** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2313*/
danielk1977e339d652008-06-28 11:23:00 +00002314static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002315 int rc = SQLITE_OK;
2316 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002317 unixFile *pFile = (unixFile*)id;
2318
aswift5b1a2562008-08-22 00:22:35 +00002319 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2320
2321 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002322 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2323
2324 /* Check if a thread in this process holds such a lock */
2325 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002326 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002327 }
2328
2329 /* Otherwise see if some other process holds it.
2330 */
aswift5b1a2562008-08-22 00:22:35 +00002331 if( !reserved ){
2332 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002333 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002334 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002335 /* if we succeeded in taking the reserved lock, unlock it to restore
2336 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002337 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002338 } else {
2339 /* if we failed to get the lock then someone else must have it */
2340 reserved = 1;
2341 }
2342 if( IS_LOCK_ERROR(lrc) ){
2343 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002344 }
2345 }
drhbfe66312006-10-03 17:40:40 +00002346
aswift5b1a2562008-08-22 00:22:35 +00002347 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2348
2349 *pResOut = reserved;
2350 return rc;
drhbfe66312006-10-03 17:40:40 +00002351}
2352
drh6b9d6dd2008-12-03 19:34:47 +00002353/*
2354** Lock the file with the lock specified by parameter locktype - one
2355** of the following:
2356**
2357** (1) SHARED_LOCK
2358** (2) RESERVED_LOCK
2359** (3) PENDING_LOCK
2360** (4) EXCLUSIVE_LOCK
2361**
2362** Sometimes when requesting one lock state, additional lock states
2363** are inserted in between. The locking might fail on one of the later
2364** transitions leaving the lock state different from what it started but
2365** still short of its goal. The following chart shows the allowed
2366** transitions and the inserted intermediate states:
2367**
2368** UNLOCKED -> SHARED
2369** SHARED -> RESERVED
2370** SHARED -> (PENDING) -> EXCLUSIVE
2371** RESERVED -> (PENDING) -> EXCLUSIVE
2372** PENDING -> EXCLUSIVE
2373**
2374** This routine will only increase a lock. Use the sqlite3OsUnlock()
2375** routine to lower a locking level.
2376*/
danielk1977e339d652008-06-28 11:23:00 +00002377static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002378 int rc = SQLITE_OK;
2379 unixFile *pFile = (unixFile*)id;
2380 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002381
2382 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002383 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002384 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2385
drhbfe66312006-10-03 17:40:40 +00002386 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002387 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002388 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002389 */
drhbfe66312006-10-03 17:40:40 +00002390 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002391 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002392 locktypeName(locktype));
2393 return SQLITE_OK;
2394 }
2395
2396 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002397 */
drhbfe66312006-10-03 17:40:40 +00002398 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2399 assert( locktype!=PENDING_LOCK );
2400 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2401
2402 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002403 */
drh6c7d5c52008-11-21 20:32:33 +00002404 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002405
2406 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002407 */
drhbfe66312006-10-03 17:40:40 +00002408 rc = transferOwnership(pFile);
2409 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002410 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002411 return rc;
2412 }
2413
2414 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002415 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2416 ** be released.
2417 */
drhbfe66312006-10-03 17:40:40 +00002418 if( locktype==SHARED_LOCK
2419 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002420 ){
2421 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002422 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002423 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002424 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002425 goto afp_end_lock;
2426 }
2427 }
2428
2429 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002430 ** operating system calls for the specified lock.
2431 */
drhbfe66312006-10-03 17:40:40 +00002432 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002433 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002434
aswift5b1a2562008-08-22 00:22:35 +00002435 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002436 /* note that the quality of the randomness doesn't matter that much */
2437 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002438 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002439 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002440 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002441 if( IS_LOCK_ERROR(lrc1) ){
2442 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002443 }
aswift5b1a2562008-08-22 00:22:35 +00002444 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002445 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002446
aswift5b1a2562008-08-22 00:22:35 +00002447 if( IS_LOCK_ERROR(lrc1) ) {
2448 pFile->lastErrno = lrc1Errno;
2449 rc = lrc1;
2450 goto afp_end_lock;
2451 } else if( IS_LOCK_ERROR(lrc2) ){
2452 rc = lrc2;
2453 goto afp_end_lock;
2454 } else if( lrc1 != SQLITE_OK ) {
2455 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002456 } else {
2457 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002458 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002459 }
2460 }else{
2461 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2462 ** assumed that there is a SHARED or greater lock on the file
2463 ** already.
2464 */
2465 int failed = 0;
2466 assert( 0!=pFile->locktype );
2467 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2468 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002469 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002470 }
2471 if (!failed && locktype == EXCLUSIVE_LOCK) {
2472 /* Acquire an EXCLUSIVE lock */
2473
2474 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002475 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002476 */
drh6b9d6dd2008-12-03 19:34:47 +00002477 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002478 context->sharedByte, 1, 0)) ){
2479 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002480 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002481 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002482 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002483 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002484 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2485 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2486 ** a critical I/O error
2487 */
2488 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2489 SQLITE_IOERR_LOCK;
2490 goto afp_end_lock;
2491 }
2492 }else{
aswift5b1a2562008-08-22 00:22:35 +00002493 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002494 }
2495 }
aswift5b1a2562008-08-22 00:22:35 +00002496 if( failed ){
2497 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002498 }
2499 }
2500
2501 if( rc==SQLITE_OK ){
2502 pFile->locktype = locktype;
2503 }else if( locktype==EXCLUSIVE_LOCK ){
2504 pFile->locktype = PENDING_LOCK;
2505 }
2506
2507afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002508 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002509 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002510 rc==SQLITE_OK ? "ok" : "failed");
2511 return rc;
2512}
2513
2514/*
drh339eb0b2008-03-07 15:34:11 +00002515** Lower the locking level on file descriptor pFile to locktype. locktype
2516** must be either NO_LOCK or SHARED_LOCK.
2517**
2518** If the locking level of the file descriptor is already at or below
2519** the requested locking level, this routine is a no-op.
2520*/
danielk1977e339d652008-06-28 11:23:00 +00002521static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002522 int rc = SQLITE_OK;
2523 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002524 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002525
2526 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002527 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002528 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002529
drhbfe66312006-10-03 17:40:40 +00002530 assert( locktype<=SHARED_LOCK );
2531 if( pFile->locktype<=locktype ){
2532 return SQLITE_OK;
2533 }
2534 if( CHECK_THREADID(pFile) ){
2535 return SQLITE_MISUSE;
2536 }
drh6c7d5c52008-11-21 20:32:33 +00002537 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002538 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002539
2540 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002541 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002542 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2543 /* only re-establish the shared lock if necessary */
2544 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002545 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002546 }
2547 }
2548 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002549 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002550 }
2551 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002552 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002553 }
2554 }else if( locktype==NO_LOCK ){
2555 /* clear the shared lock */
2556 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002557 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002558 }
drhbfe66312006-10-03 17:40:40 +00002559
aswiftaebf4132008-11-21 00:10:35 +00002560 if( rc==SQLITE_OK ){
2561 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002562 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002563 pOpen->nLock--;
2564 assert( pOpen->nLock>=0 );
2565 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2566 int i;
2567 for(i=0; i<pOpen->nPending; i++){
2568 if( pOpen->aPending[i] < 0 ) continue;
2569 if( close(pOpen->aPending[i]) ){
2570 pFile->lastErrno = errno;
2571 rc = SQLITE_IOERR_CLOSE;
2572 }else{
2573 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002574 }
aswiftaebf4132008-11-21 00:10:35 +00002575 }
2576 if( rc==SQLITE_OK ){
2577 sqlite3_free(pOpen->aPending);
2578 pOpen->nPending = 0;
2579 pOpen->aPending = 0;
2580 }
drhbfe66312006-10-03 17:40:40 +00002581 }
2582 }
drhbfe66312006-10-03 17:40:40 +00002583 }
drh6c7d5c52008-11-21 20:32:33 +00002584 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002585 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002586 return rc;
2587}
2588
2589/*
drh339eb0b2008-03-07 15:34:11 +00002590** Close a file & cleanup AFP specific locking context
2591*/
danielk1977e339d652008-06-28 11:23:00 +00002592static int afpClose(sqlite3_file *id) {
2593 if( id ){
2594 unixFile *pFile = (unixFile*)id;
2595 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002596 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002597 if( pFile->pOpen && pFile->pOpen->nLock ){
2598 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002599 ** yet because that would clear those locks. Instead, add the file
2600 ** descriptor to pOpen->aPending. It will be automatically closed when
2601 ** the last lock is cleared.
2602 */
aswiftaebf4132008-11-21 00:10:35 +00002603 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002604 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002605 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2606 if( aNew==0 ){
2607 /* If a malloc fails, just leak the file descriptor */
2608 }else{
2609 pOpen->aPending = aNew;
2610 pOpen->aPending[pOpen->nPending] = pFile->h;
2611 pOpen->nPending++;
2612 pFile->h = -1;
2613 }
2614 }
2615 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002616 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002617 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002618 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002619 }
aswiftaebf4132008-11-21 00:10:35 +00002620 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002621}
2622
drhd2cb50b2009-01-09 21:41:17 +00002623#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002624/*
2625** The code above is the AFP lock implementation. The code is specific
2626** to MacOSX and does not work on other unix platforms. No alternative
2627** is available. If you don't compile for a mac, then the "unix-afp"
2628** VFS is not available.
2629**
2630********************* End of the AFP lock implementation **********************
2631******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002632
drh734c9862008-11-28 15:37:20 +00002633
2634/******************************************************************************
2635**************** Non-locking sqlite3_file methods *****************************
2636**
2637** The next division contains implementations for all methods of the
2638** sqlite3_file object other than the locking methods. The locking
2639** methods were defined in divisions above (one locking method per
2640** division). Those methods that are common to all locking modes
2641** are gather together into this division.
2642*/
drhbfe66312006-10-03 17:40:40 +00002643
2644/*
drh734c9862008-11-28 15:37:20 +00002645** Seek to the offset passed as the second argument, then read cnt
2646** bytes into pBuf. Return the number of bytes actually read.
2647**
2648** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2649** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2650** one system to another. Since SQLite does not define USE_PREAD
2651** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2652** See tickets #2741 and #2681.
2653**
2654** To avoid stomping the errno value on a failed read the lastErrno value
2655** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002656*/
drh734c9862008-11-28 15:37:20 +00002657static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2658 int got;
2659 i64 newOffset;
2660 TIMER_START;
2661#if defined(USE_PREAD)
2662 got = pread(id->h, pBuf, cnt, offset);
2663 SimulateIOError( got = -1 );
2664#elif defined(USE_PREAD64)
2665 got = pread64(id->h, pBuf, cnt, offset);
2666 SimulateIOError( got = -1 );
2667#else
2668 newOffset = lseek(id->h, offset, SEEK_SET);
2669 SimulateIOError( newOffset-- );
2670 if( newOffset!=offset ){
2671 if( newOffset == -1 ){
2672 ((unixFile*)id)->lastErrno = errno;
2673 }else{
2674 ((unixFile*)id)->lastErrno = 0;
2675 }
2676 return -1;
2677 }
2678 got = read(id->h, pBuf, cnt);
2679#endif
2680 TIMER_END;
2681 if( got<0 ){
2682 ((unixFile*)id)->lastErrno = errno;
2683 }
2684 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2685 return got;
drhbfe66312006-10-03 17:40:40 +00002686}
2687
2688/*
drh734c9862008-11-28 15:37:20 +00002689** Read data from a file into a buffer. Return SQLITE_OK if all
2690** bytes were read successfully and SQLITE_IOERR if anything goes
2691** wrong.
drh339eb0b2008-03-07 15:34:11 +00002692*/
drh734c9862008-11-28 15:37:20 +00002693static int unixRead(
2694 sqlite3_file *id,
2695 void *pBuf,
2696 int amt,
2697 sqlite3_int64 offset
2698){
2699 int got;
2700 assert( id );
drh08c6d442009-02-09 17:34:07 +00002701
2702 /* Never read or write any of the bytes in the locking range */
2703 assert( ((unixFile*)id)->isLockable==0
2704 || offset>=PENDING_BYTE+512
2705 || offset+amt<=PENDING_BYTE );
2706
drh734c9862008-11-28 15:37:20 +00002707 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
2708 if( got==amt ){
2709 return SQLITE_OK;
2710 }else if( got<0 ){
2711 /* lastErrno set by seekAndRead */
2712 return SQLITE_IOERR_READ;
2713 }else{
2714 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2715 /* Unread parts of the buffer must be zero-filled */
2716 memset(&((char*)pBuf)[got], 0, amt-got);
2717 return SQLITE_IOERR_SHORT_READ;
2718 }
2719}
2720
2721/*
2722** Seek to the offset in id->offset then read cnt bytes into pBuf.
2723** Return the number of bytes actually read. Update the offset.
2724**
2725** To avoid stomping the errno value on a failed write the lastErrno value
2726** is set before returning.
2727*/
2728static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2729 int got;
2730 i64 newOffset;
2731 TIMER_START;
2732#if defined(USE_PREAD)
2733 got = pwrite(id->h, pBuf, cnt, offset);
2734#elif defined(USE_PREAD64)
2735 got = pwrite64(id->h, pBuf, cnt, offset);
2736#else
2737 newOffset = lseek(id->h, offset, SEEK_SET);
2738 if( newOffset!=offset ){
2739 if( newOffset == -1 ){
2740 ((unixFile*)id)->lastErrno = errno;
2741 }else{
2742 ((unixFile*)id)->lastErrno = 0;
2743 }
2744 return -1;
2745 }
2746 got = write(id->h, pBuf, cnt);
2747#endif
2748 TIMER_END;
2749 if( got<0 ){
2750 ((unixFile*)id)->lastErrno = errno;
2751 }
2752
2753 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2754 return got;
2755}
2756
2757
2758/*
2759** Write data from a buffer into a file. Return SQLITE_OK on success
2760** or some other error code on failure.
2761*/
2762static int unixWrite(
2763 sqlite3_file *id,
2764 const void *pBuf,
2765 int amt,
2766 sqlite3_int64 offset
2767){
2768 int wrote = 0;
2769 assert( id );
2770 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002771
drh08c6d442009-02-09 17:34:07 +00002772 /* Never read or write any of the bytes in the locking range */
2773 assert( ((unixFile*)id)->isLockable==0
2774 || offset>=PENDING_BYTE+512
2775 || offset+amt<=PENDING_BYTE );
2776
drh8f941bc2009-01-14 23:03:40 +00002777#ifndef NDEBUG
2778 /* If we are doing a normal write to a database file (as opposed to
2779 ** doing a hot-journal rollback or a write to some file other than a
2780 ** normal database file) then record the fact that the database
2781 ** has changed. If the transaction counter is modified, record that
2782 ** fact too.
2783 */
2784 if( ((unixFile*)id)->inNormalWrite ){
2785 unixFile *pFile = (unixFile*)id;
2786 pFile->dbUpdate = 1; /* The database has been modified */
2787 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002788 int rc;
drh8f941bc2009-01-14 23:03:40 +00002789 char oldCntr[4];
2790 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002791 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002792 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002793 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002794 pFile->transCntrChng = 1; /* The transaction counter has changed */
2795 }
2796 }
2797 }
2798#endif
2799
drh734c9862008-11-28 15:37:20 +00002800 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2801 amt -= wrote;
2802 offset += wrote;
2803 pBuf = &((char*)pBuf)[wrote];
2804 }
2805 SimulateIOError(( wrote=(-1), amt=1 ));
2806 SimulateDiskfullError(( wrote=0, amt=1 ));
2807 if( amt>0 ){
2808 if( wrote<0 ){
2809 /* lastErrno set by seekAndWrite */
2810 return SQLITE_IOERR_WRITE;
2811 }else{
2812 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2813 return SQLITE_FULL;
2814 }
2815 }
2816 return SQLITE_OK;
2817}
2818
2819#ifdef SQLITE_TEST
2820/*
2821** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002822** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002823*/
2824int sqlite3_sync_count = 0;
2825int sqlite3_fullsync_count = 0;
2826#endif
2827
2828/*
drh89240432009-03-25 01:06:01 +00002829** We do not trust systems to provide a working fdatasync(). Some do.
2830** Others do no. To be safe, we will stick with the (slower) fsync().
2831** If you know that your system does support fdatasync() correctly,
2832** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002833*/
drh89240432009-03-25 01:06:01 +00002834#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002835# define fdatasync fsync
2836#endif
2837
2838/*
2839** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2840** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2841** only available on Mac OS X. But that could change.
2842*/
2843#ifdef F_FULLFSYNC
2844# define HAVE_FULLFSYNC 1
2845#else
2846# define HAVE_FULLFSYNC 0
2847#endif
2848
2849
2850/*
2851** The fsync() system call does not work as advertised on many
2852** unix systems. The following procedure is an attempt to make
2853** it work better.
2854**
2855** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2856** for testing when we want to run through the test suite quickly.
2857** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2858** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2859** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002860**
2861** SQLite sets the dataOnly flag if the size of the file is unchanged.
2862** The idea behind dataOnly is that it should only write the file content
2863** to disk, not the inode. We only set dataOnly if the file size is
2864** unchanged since the file size is part of the inode. However,
2865** Ted Ts'o tells us that fdatasync() will also write the inode if the
2866** file size has changed. The only real difference between fdatasync()
2867** and fsync(), Ted tells us, is that fdatasync() will not flush the
2868** inode if the mtime or owner or other inode attributes have changed.
2869** We only care about the file size, not the other file attributes, so
2870** as far as SQLite is concerned, an fdatasync() is always adequate.
2871** So, we always use fdatasync() if it is available, regardless of
2872** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002873*/
2874static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002875 int rc;
drh734c9862008-11-28 15:37:20 +00002876
2877 /* The following "ifdef/elif/else/" block has the same structure as
2878 ** the one below. It is replicated here solely to avoid cluttering
2879 ** up the real code with the UNUSED_PARAMETER() macros.
2880 */
2881#ifdef SQLITE_NO_SYNC
2882 UNUSED_PARAMETER(fd);
2883 UNUSED_PARAMETER(fullSync);
2884 UNUSED_PARAMETER(dataOnly);
2885#elif HAVE_FULLFSYNC
2886 UNUSED_PARAMETER(dataOnly);
2887#else
2888 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002889 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002890#endif
2891
2892 /* Record the number of times that we do a normal fsync() and
2893 ** FULLSYNC. This is used during testing to verify that this procedure
2894 ** gets called with the correct arguments.
2895 */
2896#ifdef SQLITE_TEST
2897 if( fullSync ) sqlite3_fullsync_count++;
2898 sqlite3_sync_count++;
2899#endif
2900
2901 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2902 ** no-op
2903 */
2904#ifdef SQLITE_NO_SYNC
2905 rc = SQLITE_OK;
2906#elif HAVE_FULLFSYNC
2907 if( fullSync ){
2908 rc = fcntl(fd, F_FULLFSYNC, 0);
2909 }else{
2910 rc = 1;
2911 }
2912 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002913 ** It shouldn't be possible for fullfsync to fail on the local
2914 ** file system (on OSX), so failure indicates that FULLFSYNC
2915 ** isn't supported for this file system. So, attempt an fsync
2916 ** and (for now) ignore the overhead of a superfluous fcntl call.
2917 ** It'd be better to detect fullfsync support once and avoid
2918 ** the fcntl call every time sync is called.
2919 */
drh734c9862008-11-28 15:37:20 +00002920 if( rc ) rc = fsync(fd);
2921
2922#else
drh0b647ff2009-03-21 14:41:04 +00002923 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002924#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002925 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002926 rc = fsync(fd);
2927 }
drh0b647ff2009-03-21 14:41:04 +00002928#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002929#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2930
2931 if( OS_VXWORKS && rc!= -1 ){
2932 rc = 0;
2933 }
chw97185482008-11-17 08:05:31 +00002934 return rc;
drhbfe66312006-10-03 17:40:40 +00002935}
2936
drh734c9862008-11-28 15:37:20 +00002937/*
2938** Make sure all writes to a particular file are committed to disk.
2939**
2940** If dataOnly==0 then both the file itself and its metadata (file
2941** size, access time, etc) are synced. If dataOnly!=0 then only the
2942** file data is synced.
2943**
2944** Under Unix, also make sure that the directory entry for the file
2945** has been created by fsync-ing the directory that contains the file.
2946** If we do not do this and we encounter a power failure, the directory
2947** entry for the journal might not exist after we reboot. The next
2948** SQLite to access the file will not know that the journal exists (because
2949** the directory entry for the journal was never created) and the transaction
2950** will not roll back - possibly leading to database corruption.
2951*/
2952static int unixSync(sqlite3_file *id, int flags){
2953 int rc;
2954 unixFile *pFile = (unixFile*)id;
2955
2956 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2957 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2958
2959 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2960 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2961 || (flags&0x0F)==SQLITE_SYNC_FULL
2962 );
2963
2964 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2965 ** line is to test that doing so does not cause any problems.
2966 */
2967 SimulateDiskfullError( return SQLITE_FULL );
2968
2969 assert( pFile );
2970 OSTRACE2("SYNC %-3d\n", pFile->h);
2971 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2972 SimulateIOError( rc=1 );
2973 if( rc ){
2974 pFile->lastErrno = errno;
2975 return SQLITE_IOERR_FSYNC;
2976 }
2977 if( pFile->dirfd>=0 ){
2978 int err;
2979 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2980 HAVE_FULLFSYNC, isFullsync);
2981#ifndef SQLITE_DISABLE_DIRSYNC
2982 /* The directory sync is only attempted if full_fsync is
2983 ** turned off or unavailable. If a full_fsync occurred above,
2984 ** then the directory sync is superfluous.
2985 */
2986 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2987 /*
2988 ** We have received multiple reports of fsync() returning
2989 ** errors when applied to directories on certain file systems.
2990 ** A failed directory sync is not a big deal. So it seems
2991 ** better to ignore the error. Ticket #1657
2992 */
2993 /* pFile->lastErrno = errno; */
2994 /* return SQLITE_IOERR; */
2995 }
2996#endif
2997 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2998 if( err==0 ){ /* directory when we are done */
2999 pFile->dirfd = -1;
3000 }else{
3001 pFile->lastErrno = errno;
3002 rc = SQLITE_IOERR_DIR_CLOSE;
3003 }
3004 }
3005 return rc;
3006}
3007
3008/*
3009** Truncate an open file to a specified size
3010*/
3011static int unixTruncate(sqlite3_file *id, i64 nByte){
3012 int rc;
3013 assert( id );
3014 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3015 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3016 if( rc ){
3017 ((unixFile*)id)->lastErrno = errno;
3018 return SQLITE_IOERR_TRUNCATE;
3019 }else{
3020 return SQLITE_OK;
3021 }
3022}
3023
3024/*
3025** Determine the current size of a file in bytes
3026*/
3027static int unixFileSize(sqlite3_file *id, i64 *pSize){
3028 int rc;
3029 struct stat buf;
3030 assert( id );
3031 rc = fstat(((unixFile*)id)->h, &buf);
3032 SimulateIOError( rc=1 );
3033 if( rc!=0 ){
3034 ((unixFile*)id)->lastErrno = errno;
3035 return SQLITE_IOERR_FSTAT;
3036 }
3037 *pSize = buf.st_size;
3038
3039 /* When opening a zero-size database, the findLockInfo() procedure
3040 ** writes a single byte into that file in order to work around a bug
3041 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3042 ** layers, we need to report this file size as zero even though it is
3043 ** really 1. Ticket #3260.
3044 */
3045 if( *pSize==1 ) *pSize = 0;
3046
3047
3048 return SQLITE_OK;
3049}
3050
drhd2cb50b2009-01-09 21:41:17 +00003051#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003052/*
3053** Handler for proxy-locking file-control verbs. Defined below in the
3054** proxying locking division.
3055*/
3056static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003057#endif
drh715ff302008-12-03 22:32:44 +00003058
danielk1977ad94b582007-08-20 06:44:22 +00003059
danielk1977e3026632004-06-22 11:29:02 +00003060/*
drh9e33c2c2007-08-31 18:34:59 +00003061** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003062*/
drhcc6bb3e2007-08-31 16:11:35 +00003063static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003064 switch( op ){
3065 case SQLITE_FCNTL_LOCKSTATE: {
3066 *(int*)pArg = ((unixFile*)id)->locktype;
3067 return SQLITE_OK;
3068 }
drh7708e972008-11-29 00:56:52 +00003069 case SQLITE_LAST_ERRNO: {
3070 *(int*)pArg = ((unixFile*)id)->lastErrno;
3071 return SQLITE_OK;
3072 }
drh8f941bc2009-01-14 23:03:40 +00003073#ifndef NDEBUG
3074 /* The pager calls this method to signal that it has done
3075 ** a rollback and that the database is therefore unchanged and
3076 ** it hence it is OK for the transaction change counter to be
3077 ** unchanged.
3078 */
3079 case SQLITE_FCNTL_DB_UNCHANGED: {
3080 ((unixFile*)id)->dbUpdate = 0;
3081 return SQLITE_OK;
3082 }
3083#endif
drhd2cb50b2009-01-09 21:41:17 +00003084#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003085 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003086 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003087 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003088 }
drhd2cb50b2009-01-09 21:41:17 +00003089#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003090 }
drhcc6bb3e2007-08-31 16:11:35 +00003091 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003092}
3093
3094/*
danielk1977a3d4c882007-03-23 10:08:38 +00003095** Return the sector size in bytes of the underlying block device for
3096** the specified file. This is almost always 512 bytes, but may be
3097** larger for some devices.
3098**
3099** SQLite code assumes this function cannot fail. It also assumes that
3100** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003101** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003102** same for both.
3103*/
danielk1977397d65f2008-11-19 11:35:39 +00003104static int unixSectorSize(sqlite3_file *NotUsed){
3105 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003106 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003107}
3108
danielk197790949c22007-08-17 16:50:38 +00003109/*
danielk1977397d65f2008-11-19 11:35:39 +00003110** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003111*/
danielk1977397d65f2008-11-19 11:35:39 +00003112static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3113 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003114 return 0;
3115}
3116
drh734c9862008-11-28 15:37:20 +00003117/*
3118** Here ends the implementation of all sqlite3_file methods.
3119**
3120********************** End sqlite3_file Methods *******************************
3121******************************************************************************/
3122
3123/*
drh6b9d6dd2008-12-03 19:34:47 +00003124** This division contains definitions of sqlite3_io_methods objects that
3125** implement various file locking strategies. It also contains definitions
3126** of "finder" functions. A finder-function is used to locate the appropriate
3127** sqlite3_io_methods object for a particular database file. The pAppData
3128** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3129** the correct finder-function for that VFS.
3130**
3131** Most finder functions return a pointer to a fixed sqlite3_io_methods
3132** object. The only interesting finder-function is autolockIoFinder, which
3133** looks at the filesystem type and tries to guess the best locking
3134** strategy from that.
3135**
drh1875f7a2008-12-08 18:19:17 +00003136** For finder-funtion F, two objects are created:
3137**
3138** (1) The real finder-function named "FImpt()".
3139**
3140** (2) A constant pointer to this functio named just "F".
3141**
3142**
3143** A pointer to the F pointer is used as the pAppData value for VFS
3144** objects. We have to do this instead of letting pAppData point
3145** directly at the finder-function since C90 rules prevent a void*
3146** from be cast into a function pointer.
3147**
drh6b9d6dd2008-12-03 19:34:47 +00003148**
drh7708e972008-11-29 00:56:52 +00003149** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003150**
drh7708e972008-11-29 00:56:52 +00003151** * A constant sqlite3_io_methods object call METHOD that has locking
3152** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3153**
3154** * An I/O method finder function called FINDER that returns a pointer
3155** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003156*/
drh7708e972008-11-29 00:56:52 +00003157#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3158static const sqlite3_io_methods METHOD = { \
3159 1, /* iVersion */ \
3160 CLOSE, /* xClose */ \
3161 unixRead, /* xRead */ \
3162 unixWrite, /* xWrite */ \
3163 unixTruncate, /* xTruncate */ \
3164 unixSync, /* xSync */ \
3165 unixFileSize, /* xFileSize */ \
3166 LOCK, /* xLock */ \
3167 UNLOCK, /* xUnlock */ \
3168 CKLOCK, /* xCheckReservedLock */ \
3169 unixFileControl, /* xFileControl */ \
3170 unixSectorSize, /* xSectorSize */ \
3171 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3172}; \
drh1875f7a2008-12-08 18:19:17 +00003173static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003174 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3175 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003176} \
3177static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3178 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003179
3180/*
3181** Here are all of the sqlite3_io_methods objects for each of the
3182** locking strategies. Functions that return pointers to these methods
3183** are also created.
3184*/
3185IOMETHODS(
3186 posixIoFinder, /* Finder function name */
3187 posixIoMethods, /* sqlite3_io_methods object name */
3188 unixClose, /* xClose method */
3189 unixLock, /* xLock method */
3190 unixUnlock, /* xUnlock method */
3191 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003192)
drh7708e972008-11-29 00:56:52 +00003193IOMETHODS(
3194 nolockIoFinder, /* Finder function name */
3195 nolockIoMethods, /* sqlite3_io_methods object name */
3196 nolockClose, /* xClose method */
3197 nolockLock, /* xLock method */
3198 nolockUnlock, /* xUnlock method */
3199 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003200)
drh7708e972008-11-29 00:56:52 +00003201IOMETHODS(
3202 dotlockIoFinder, /* Finder function name */
3203 dotlockIoMethods, /* sqlite3_io_methods object name */
3204 dotlockClose, /* xClose method */
3205 dotlockLock, /* xLock method */
3206 dotlockUnlock, /* xUnlock method */
3207 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003208)
drh7708e972008-11-29 00:56:52 +00003209
3210#if SQLITE_ENABLE_LOCKING_STYLE
3211IOMETHODS(
3212 flockIoFinder, /* Finder function name */
3213 flockIoMethods, /* sqlite3_io_methods object name */
3214 flockClose, /* xClose method */
3215 flockLock, /* xLock method */
3216 flockUnlock, /* xUnlock method */
3217 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003218)
drh7708e972008-11-29 00:56:52 +00003219#endif
3220
drh6c7d5c52008-11-21 20:32:33 +00003221#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003222IOMETHODS(
3223 semIoFinder, /* Finder function name */
3224 semIoMethods, /* sqlite3_io_methods object name */
3225 semClose, /* xClose method */
3226 semLock, /* xLock method */
3227 semUnlock, /* xUnlock method */
3228 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003229)
aswiftaebf4132008-11-21 00:10:35 +00003230#endif
drh7708e972008-11-29 00:56:52 +00003231
drhd2cb50b2009-01-09 21:41:17 +00003232#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003233IOMETHODS(
3234 afpIoFinder, /* Finder function name */
3235 afpIoMethods, /* sqlite3_io_methods object name */
3236 afpClose, /* xClose method */
3237 afpLock, /* xLock method */
3238 afpUnlock, /* xUnlock method */
3239 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003240)
drh715ff302008-12-03 22:32:44 +00003241#endif
3242
3243/*
3244** The proxy locking method is a "super-method" in the sense that it
3245** opens secondary file descriptors for the conch and lock files and
3246** it uses proxy, dot-file, AFP, and flock() locking methods on those
3247** secondary files. For this reason, the division that implements
3248** proxy locking is located much further down in the file. But we need
3249** to go ahead and define the sqlite3_io_methods and finder function
3250** for proxy locking here. So we forward declare the I/O methods.
3251*/
drhd2cb50b2009-01-09 21:41:17 +00003252#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003253static int proxyClose(sqlite3_file*);
3254static int proxyLock(sqlite3_file*, int);
3255static int proxyUnlock(sqlite3_file*, int);
3256static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003257IOMETHODS(
3258 proxyIoFinder, /* Finder function name */
3259 proxyIoMethods, /* sqlite3_io_methods object name */
3260 proxyClose, /* xClose method */
3261 proxyLock, /* xLock method */
3262 proxyUnlock, /* xUnlock method */
3263 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003264)
aswiftaebf4132008-11-21 00:10:35 +00003265#endif
drh7708e972008-11-29 00:56:52 +00003266
3267
drhd2cb50b2009-01-09 21:41:17 +00003268#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003269/*
drh6b9d6dd2008-12-03 19:34:47 +00003270** This "finder" function attempts to determine the best locking strategy
3271** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003272** object that implements that strategy.
3273**
3274** This is for MacOSX only.
3275*/
drh1875f7a2008-12-08 18:19:17 +00003276static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003277 const char *filePath, /* name of the database file */
3278 int fd /* file descriptor open on the database file */
3279){
3280 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003281 const char *zFilesystem; /* Filesystem type name */
3282 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003283 } aMap[] = {
3284 { "hfs", &posixIoMethods },
3285 { "ufs", &posixIoMethods },
3286 { "afpfs", &afpIoMethods },
3287#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3288 { "smbfs", &afpIoMethods },
3289#else
3290 { "smbfs", &flockIoMethods },
3291#endif
3292 { "webdav", &nolockIoMethods },
3293 { 0, 0 }
3294 };
3295 int i;
3296 struct statfs fsInfo;
3297 struct flock lockInfo;
3298
3299 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003300 /* If filePath==NULL that means we are dealing with a transient file
3301 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003302 return &nolockIoMethods;
3303 }
3304 if( statfs(filePath, &fsInfo) != -1 ){
3305 if( fsInfo.f_flags & MNT_RDONLY ){
3306 return &nolockIoMethods;
3307 }
3308 for(i=0; aMap[i].zFilesystem; i++){
3309 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3310 return aMap[i].pMethods;
3311 }
3312 }
3313 }
3314
3315 /* Default case. Handles, amongst others, "nfs".
3316 ** Test byte-range lock using fcntl(). If the call succeeds,
3317 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003318 */
drh7708e972008-11-29 00:56:52 +00003319 lockInfo.l_len = 1;
3320 lockInfo.l_start = 0;
3321 lockInfo.l_whence = SEEK_SET;
3322 lockInfo.l_type = F_RDLCK;
3323 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3324 return &posixIoMethods;
3325 }else{
3326 return &dotlockIoMethods;
3327 }
3328}
danielk1977852e2322008-12-22 03:36:59 +00003329static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003330 = autolockIoFinderImpl;
3331
drhd2cb50b2009-01-09 21:41:17 +00003332#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003333
3334/*
3335** An abstract type for a pointer to a IO method finder function:
3336*/
3337typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3338
aswiftaebf4132008-11-21 00:10:35 +00003339
drh734c9862008-11-28 15:37:20 +00003340/****************************************************************************
3341**************************** sqlite3_vfs methods ****************************
3342**
3343** This division contains the implementation of methods on the
3344** sqlite3_vfs object.
3345*/
3346
danielk1977a3d4c882007-03-23 10:08:38 +00003347/*
danielk1977e339d652008-06-28 11:23:00 +00003348** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003349*/
3350static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003351 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003352 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003353 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003354 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003355 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003356 int noLock, /* Omit locking if true */
3357 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003358){
drh7708e972008-11-29 00:56:52 +00003359 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003360 unixFile *pNew = (unixFile *)pId;
3361 int rc = SQLITE_OK;
3362
danielk197717b90b52008-06-06 11:11:25 +00003363 assert( pNew->pLock==NULL );
3364 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003365
drh715ff302008-12-03 22:32:44 +00003366 /* Parameter isDelete is only used on vxworks.
3367 ** Express this explicitly here to prevent compiler warnings
3368 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003369 */
drh7708e972008-11-29 00:56:52 +00003370#if !OS_VXWORKS
3371 UNUSED_PARAMETER(isDelete);
3372#endif
danielk1977a03396a2008-11-19 14:35:46 +00003373
drh218c5082008-03-07 00:27:10 +00003374 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003375 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003376 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003377 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003378
drh6c7d5c52008-11-21 20:32:33 +00003379#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003380 pNew->pId = vxworksFindFileId(zFilename);
3381 if( pNew->pId==0 ){
3382 noLock = 1;
3383 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003384 }
3385#endif
3386
drhda0e7682008-07-30 15:27:54 +00003387 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003388 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003389 }else{
drh1875f7a2008-12-08 18:19:17 +00003390 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003391#if SQLITE_ENABLE_LOCKING_STYLE
3392 /* Cache zFilename in the locking context (AFP and dotlock override) for
3393 ** proxyLock activation is possible (remote proxy is based on db name)
3394 ** zFilename remains valid until file is closed, to support */
3395 pNew->lockingContext = (void*)zFilename;
3396#endif
drhda0e7682008-07-30 15:27:54 +00003397 }
danielk1977e339d652008-06-28 11:23:00 +00003398
drh7708e972008-11-29 00:56:52 +00003399 if( pLockingStyle == &posixIoMethods ){
3400 unixEnterMutex();
3401 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3402 unixLeaveMutex();
3403 }
danielk1977e339d652008-06-28 11:23:00 +00003404
drhd2cb50b2009-01-09 21:41:17 +00003405#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003406 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003407 /* AFP locking uses the file path so it needs to be included in
3408 ** the afpLockingContext.
3409 */
3410 afpLockingContext *pCtx;
3411 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3412 if( pCtx==0 ){
3413 rc = SQLITE_NOMEM;
3414 }else{
3415 /* NB: zFilename exists and remains valid until the file is closed
3416 ** according to requirement F11141. So we do not need to make a
3417 ** copy of the filename. */
3418 pCtx->dbPath = zFilename;
3419 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003420 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003421 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3422 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003423 }
drh7708e972008-11-29 00:56:52 +00003424 }
3425#endif
danielk1977e339d652008-06-28 11:23:00 +00003426
drh7708e972008-11-29 00:56:52 +00003427 else if( pLockingStyle == &dotlockIoMethods ){
3428 /* Dotfile locking uses the file path so it needs to be included in
3429 ** the dotlockLockingContext
3430 */
3431 char *zLockFile;
3432 int nFilename;
drhea678832008-12-10 19:26:22 +00003433 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003434 zLockFile = (char *)sqlite3_malloc(nFilename);
3435 if( zLockFile==0 ){
3436 rc = SQLITE_NOMEM;
3437 }else{
3438 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003439 }
drh7708e972008-11-29 00:56:52 +00003440 pNew->lockingContext = zLockFile;
3441 }
danielk1977e339d652008-06-28 11:23:00 +00003442
drh6c7d5c52008-11-21 20:32:33 +00003443#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003444 else if( pLockingStyle == &semIoMethods ){
3445 /* Named semaphore locking uses the file path so it needs to be
3446 ** included in the semLockingContext
3447 */
3448 unixEnterMutex();
3449 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3450 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3451 char *zSemName = pNew->pOpen->aSemName;
3452 int n;
3453 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3454 pNew->pId->zCanonicalName);
3455 for( n=0; zSemName[n]; n++ )
3456 if( zSemName[n]=='/' ) zSemName[n] = '_';
3457 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3458 if( pNew->pOpen->pSem == SEM_FAILED ){
3459 rc = SQLITE_NOMEM;
3460 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003461 }
chw97185482008-11-17 08:05:31 +00003462 }
drh7708e972008-11-29 00:56:52 +00003463 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003464 }
drh7708e972008-11-29 00:56:52 +00003465#endif
aswift5b1a2562008-08-22 00:22:35 +00003466
3467 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003468#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003469 if( rc!=SQLITE_OK ){
3470 unlink(zFilename);
3471 isDelete = 0;
3472 }
3473 pNew->isDelete = isDelete;
3474#endif
danielk1977e339d652008-06-28 11:23:00 +00003475 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003476 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003477 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003478 }else{
drh7708e972008-11-29 00:56:52 +00003479 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003480 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003481 }
danielk1977e339d652008-06-28 11:23:00 +00003482 return rc;
drh054889e2005-11-30 03:20:31 +00003483}
drh9c06c952005-11-26 00:25:00 +00003484
danielk1977ad94b582007-08-20 06:44:22 +00003485/*
3486** Open a file descriptor to the directory containing file zFilename.
3487** If successful, *pFd is set to the opened file descriptor and
3488** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3489** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3490** value.
3491**
3492** If SQLITE_OK is returned, the caller is responsible for closing
3493** the file descriptor *pFd using close().
3494*/
danielk1977fee2d252007-08-18 10:59:19 +00003495static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003496 int ii;
drh777b17a2007-09-20 10:02:54 +00003497 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003498 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003499
drh153c62c2007-08-24 03:51:33 +00003500 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003501 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003502 if( ii>0 ){
3503 zDirname[ii] = '\0';
3504 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003505 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003506#ifdef FD_CLOEXEC
3507 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3508#endif
3509 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3510 }
3511 }
danielk1977fee2d252007-08-18 10:59:19 +00003512 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003513 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003514}
3515
danielk1977b4b47412007-08-17 15:53:36 +00003516/*
danielk197717b90b52008-06-06 11:11:25 +00003517** Create a temporary file name in zBuf. zBuf must be allocated
3518** by the calling process and must be big enough to hold at least
3519** pVfs->mxPathname bytes.
3520*/
3521static int getTempname(int nBuf, char *zBuf){
3522 static const char *azDirs[] = {
3523 0,
aswiftaebf4132008-11-21 00:10:35 +00003524 0,
danielk197717b90b52008-06-06 11:11:25 +00003525 "/var/tmp",
3526 "/usr/tmp",
3527 "/tmp",
3528 ".",
3529 };
3530 static const unsigned char zChars[] =
3531 "abcdefghijklmnopqrstuvwxyz"
3532 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3533 "0123456789";
drh41022642008-11-21 00:24:42 +00003534 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003535 struct stat buf;
3536 const char *zDir = ".";
3537
3538 /* It's odd to simulate an io-error here, but really this is just
3539 ** using the io-error infrastructure to test that SQLite handles this
3540 ** function failing.
3541 */
3542 SimulateIOError( return SQLITE_IOERR );
3543
3544 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003545 if (NULL == azDirs[1]) {
3546 azDirs[1] = getenv("TMPDIR");
3547 }
3548
3549 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003550 if( azDirs[i]==0 ) continue;
3551 if( stat(azDirs[i], &buf) ) continue;
3552 if( !S_ISDIR(buf.st_mode) ) continue;
3553 if( access(azDirs[i], 07) ) continue;
3554 zDir = azDirs[i];
3555 break;
3556 }
3557
3558 /* Check that the output buffer is large enough for the temporary file
3559 ** name. If it is not, return SQLITE_ERROR.
3560 */
danielk197700e13612008-11-17 19:18:54 +00003561 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003562 return SQLITE_ERROR;
3563 }
3564
3565 do{
3566 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003567 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003568 sqlite3_randomness(15, &zBuf[j]);
3569 for(i=0; i<15; i++, j++){
3570 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3571 }
3572 zBuf[j] = 0;
3573 }while( access(zBuf,0)==0 );
3574 return SQLITE_OK;
3575}
3576
drhd2cb50b2009-01-09 21:41:17 +00003577#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003578/*
3579** Routine to transform a unixFile into a proxy-locking unixFile.
3580** Implementation in the proxy-lock division, but used by unixOpen()
3581** if SQLITE_PREFER_PROXY_LOCKING is defined.
3582*/
3583static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003584#endif
drhc66d5b62008-12-03 22:48:32 +00003585
danielk197717b90b52008-06-06 11:11:25 +00003586
3587/*
danielk1977ad94b582007-08-20 06:44:22 +00003588** Open the file zPath.
3589**
danielk1977b4b47412007-08-17 15:53:36 +00003590** Previously, the SQLite OS layer used three functions in place of this
3591** one:
3592**
3593** sqlite3OsOpenReadWrite();
3594** sqlite3OsOpenReadOnly();
3595** sqlite3OsOpenExclusive();
3596**
3597** These calls correspond to the following combinations of flags:
3598**
3599** ReadWrite() -> (READWRITE | CREATE)
3600** ReadOnly() -> (READONLY)
3601** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3602**
3603** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3604** true, the file was configured to be automatically deleted when the
3605** file handle closed. To achieve the same effect using this new
3606** interface, add the DELETEONCLOSE flag to those specified above for
3607** OpenExclusive().
3608*/
3609static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003610 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3611 const char *zPath, /* Pathname of file to be opened */
3612 sqlite3_file *pFile, /* The file descriptor to be filled in */
3613 int flags, /* Input flags to control the opening */
3614 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003615){
danielk1977fee2d252007-08-18 10:59:19 +00003616 int fd = 0; /* File descriptor returned by open() */
3617 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003618 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003619 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003620 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003621 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003622
3623 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3624 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3625 int isCreate = (flags & SQLITE_OPEN_CREATE);
3626 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3627 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3628
danielk1977fee2d252007-08-18 10:59:19 +00003629 /* If creating a master or main-file journal, this function will open
3630 ** a file-descriptor on the directory too. The first time unixSync()
3631 ** is called the directory file descriptor will be fsync()ed and close()d.
3632 */
3633 int isOpenDirectory = (isCreate &&
3634 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3635 );
3636
danielk197717b90b52008-06-06 11:11:25 +00003637 /* If argument zPath is a NULL pointer, this function is required to open
3638 ** a temporary file. Use this buffer to store the file name in.
3639 */
3640 char zTmpname[MAX_PATHNAME+1];
3641 const char *zName = zPath;
3642
danielk1977fee2d252007-08-18 10:59:19 +00003643 /* Check the following statements are true:
3644 **
3645 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3646 ** (b) if CREATE is set, then READWRITE must also be set, and
3647 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003648 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003649 */
danielk1977b4b47412007-08-17 15:53:36 +00003650 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003651 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003652 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003653 assert(isDelete==0 || isCreate);
3654
drh33f4e022007-09-03 15:19:34 +00003655 /* The main DB, main journal, and master journal are never automatically
3656 ** deleted
3657 */
3658 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3659 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3660 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003661
danielk1977fee2d252007-08-18 10:59:19 +00003662 /* Assert that the upper layer has set one of the "file-type" flags. */
3663 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3664 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3665 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003666 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003667 );
3668
danielk1977e339d652008-06-28 11:23:00 +00003669 memset(pFile, 0, sizeof(unixFile));
3670
danielk197717b90b52008-06-06 11:11:25 +00003671 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003672 assert(isDelete && !isOpenDirectory);
3673 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3674 if( rc!=SQLITE_OK ){
3675 return rc;
3676 }
3677 zName = zTmpname;
3678 }
3679
drh734c9862008-11-28 15:37:20 +00003680 if( isReadonly ) openFlags |= O_RDONLY;
3681 if( isReadWrite ) openFlags |= O_RDWR;
3682 if( isCreate ) openFlags |= O_CREAT;
3683 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3684 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003685
drh734c9862008-11-28 15:37:20 +00003686 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3687 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003688 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003689 /* Failed to open the file for read/write access. Try read-only. */
3690 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3691 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003692 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003693 }
3694 if( fd<0 ){
3695 return SQLITE_CANTOPEN;
3696 }
3697 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003698#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003699 zPath = zName;
3700#else
danielk197717b90b52008-06-06 11:11:25 +00003701 unlink(zName);
chw97185482008-11-17 08:05:31 +00003702#endif
danielk1977b4b47412007-08-17 15:53:36 +00003703 }
drh41022642008-11-21 00:24:42 +00003704#if SQLITE_ENABLE_LOCKING_STYLE
3705 else{
drh734c9862008-11-28 15:37:20 +00003706 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003707 }
3708#endif
danielk1977b4b47412007-08-17 15:53:36 +00003709 if( pOutFlags ){
3710 *pOutFlags = flags;
3711 }
3712
drh08c6d442009-02-09 17:34:07 +00003713#ifndef NDEBUG
3714 if( (flags & SQLITE_OPEN_MAIN_DB)!=0 ){
3715 ((unixFile*)pFile)->isLockable = 1;
3716 }
3717#endif
3718
danielk1977b4b47412007-08-17 15:53:36 +00003719 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00003720 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003721 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003722 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003723 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003724 return rc;
3725 }
3726 }
danielk1977e339d652008-06-28 11:23:00 +00003727
3728#ifdef FD_CLOEXEC
3729 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3730#endif
3731
drhda0e7682008-07-30 15:27:54 +00003732 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003733
3734#if SQLITE_PREFER_PROXY_LOCKING
3735 if( zPath!=NULL && !noLock ){
3736 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3737 int useProxy = 0;
3738
3739 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003740 ** 0 means never use proxy, NULL means use proxy for non-local files only
3741 */
aswiftaebf4132008-11-21 00:10:35 +00003742 if( envforce!=NULL ){
3743 useProxy = atoi(envforce)>0;
3744 }else{
3745 struct statfs fsInfo;
3746
3747 if( statfs(zPath, &fsInfo) == -1 ){
3748 ((unixFile*)pFile)->lastErrno = errno;
3749 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3750 close(fd); /* silently leak if fail, in error */
3751 return SQLITE_IOERR_ACCESS;
3752 }
3753 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3754 }
3755 if( useProxy ){
3756 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3757 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003758 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003759 }
3760 return rc;
3761 }
3762 }
3763#endif
3764
chw97185482008-11-17 08:05:31 +00003765 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003766}
3767
3768/*
danielk1977fee2d252007-08-18 10:59:19 +00003769** Delete the file at zPath. If the dirSync argument is true, fsync()
3770** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003771*/
drh6b9d6dd2008-12-03 19:34:47 +00003772static int unixDelete(
3773 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3774 const char *zPath, /* Name of file to be deleted */
3775 int dirSync /* If true, fsync() directory after deleting file */
3776){
danielk1977fee2d252007-08-18 10:59:19 +00003777 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003778 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003779 SimulateIOError(return SQLITE_IOERR_DELETE);
3780 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003781#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003782 if( dirSync ){
3783 int fd;
3784 rc = openDirectory(zPath, &fd);
3785 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003786#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003787 if( fsync(fd)==-1 )
3788#else
3789 if( fsync(fd) )
3790#endif
3791 {
danielk1977fee2d252007-08-18 10:59:19 +00003792 rc = SQLITE_IOERR_DIR_FSYNC;
3793 }
aswiftaebf4132008-11-21 00:10:35 +00003794 if( close(fd)&&!rc ){
3795 rc = SQLITE_IOERR_DIR_CLOSE;
3796 }
danielk1977fee2d252007-08-18 10:59:19 +00003797 }
3798 }
danielk1977d138dd82008-10-15 16:02:48 +00003799#endif
danielk1977fee2d252007-08-18 10:59:19 +00003800 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003801}
3802
danielk197790949c22007-08-17 16:50:38 +00003803/*
3804** Test the existance of or access permissions of file zPath. The
3805** test performed depends on the value of flags:
3806**
3807** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3808** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3809** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3810**
3811** Otherwise return 0.
3812*/
danielk1977861f7452008-06-05 11:39:11 +00003813static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003814 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3815 const char *zPath, /* Path of the file to examine */
3816 int flags, /* What do we want to learn about the zPath file? */
3817 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003818){
rse25c0d1a2007-09-20 08:38:14 +00003819 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003820 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003821 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003822 switch( flags ){
3823 case SQLITE_ACCESS_EXISTS:
3824 amode = F_OK;
3825 break;
3826 case SQLITE_ACCESS_READWRITE:
3827 amode = W_OK|R_OK;
3828 break;
drh50d3f902007-08-27 21:10:36 +00003829 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003830 amode = R_OK;
3831 break;
3832
3833 default:
3834 assert(!"Invalid flags argument");
3835 }
danielk1977861f7452008-06-05 11:39:11 +00003836 *pResOut = (access(zPath, amode)==0);
3837 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003838}
3839
danielk1977b4b47412007-08-17 15:53:36 +00003840
3841/*
3842** Turn a relative pathname into a full pathname. The relative path
3843** is stored as a nul-terminated string in the buffer pointed to by
3844** zPath.
3845**
3846** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3847** (in this case, MAX_PATHNAME bytes). The full-path is written to
3848** this buffer before returning.
3849*/
danielk1977adfb9b02007-09-17 07:02:56 +00003850static int unixFullPathname(
3851 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3852 const char *zPath, /* Possibly relative input path */
3853 int nOut, /* Size of output buffer in bytes */
3854 char *zOut /* Output buffer */
3855){
danielk1977843e65f2007-09-01 16:16:15 +00003856
3857 /* It's odd to simulate an io-error here, but really this is just
3858 ** using the io-error infrastructure to test that SQLite handles this
3859 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003860 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003861 */
3862 SimulateIOError( return SQLITE_ERROR );
3863
drh153c62c2007-08-24 03:51:33 +00003864 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003865 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003866
drh3c7f2dc2007-12-06 13:26:20 +00003867 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003868 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003869 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003870 }else{
3871 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003872 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003873 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003874 }
drhea678832008-12-10 19:26:22 +00003875 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003876 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003877 }
3878 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003879}
3880
drh0ccebe72005-06-07 22:22:50 +00003881
drh761df872006-12-21 01:29:22 +00003882#ifndef SQLITE_OMIT_LOAD_EXTENSION
3883/*
3884** Interfaces for opening a shared library, finding entry points
3885** within the shared library, and closing the shared library.
3886*/
3887#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003888static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3889 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003890 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3891}
danielk197795c8a542007-09-01 06:51:27 +00003892
3893/*
3894** SQLite calls this function immediately after a call to unixDlSym() or
3895** unixDlOpen() fails (returns a null pointer). If a more detailed error
3896** message is available, it is written to zBufOut. If no error message
3897** is available, zBufOut is left unmodified and SQLite uses a default
3898** error message.
3899*/
danielk1977397d65f2008-11-19 11:35:39 +00003900static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003901 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003902 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003903 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003904 zErr = dlerror();
3905 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003906 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003907 }
drh6c7d5c52008-11-21 20:32:33 +00003908 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003909}
drh1875f7a2008-12-08 18:19:17 +00003910static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3911 /*
3912 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3913 ** cast into a pointer to a function. And yet the library dlsym() routine
3914 ** returns a void* which is really a pointer to a function. So how do we
3915 ** use dlsym() with -pedantic-errors?
3916 **
3917 ** Variable x below is defined to be a pointer to a function taking
3918 ** parameters void* and const char* and returning a pointer to a function.
3919 ** We initialize x by assigning it a pointer to the dlsym() function.
3920 ** (That assignment requires a cast.) Then we call the function that
3921 ** x points to.
3922 **
3923 ** This work-around is unlikely to work correctly on any system where
3924 ** you really cannot cast a function pointer into void*. But then, on the
3925 ** other hand, dlsym() will not work on such a system either, so we have
3926 ** not really lost anything.
3927 */
3928 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003929 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003930 x = (void(*(*)(void*,const char*))(void))dlsym;
3931 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003932}
danielk1977397d65f2008-11-19 11:35:39 +00003933static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
3934 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003935 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003936}
danielk1977b4b47412007-08-17 15:53:36 +00003937#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3938 #define unixDlOpen 0
3939 #define unixDlError 0
3940 #define unixDlSym 0
3941 #define unixDlClose 0
3942#endif
3943
3944/*
danielk197790949c22007-08-17 16:50:38 +00003945** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003946*/
danielk1977397d65f2008-11-19 11:35:39 +00003947static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
3948 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00003949 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00003950
drhbbd42a62004-05-22 17:41:58 +00003951 /* We have to initialize zBuf to prevent valgrind from reporting
3952 ** errors. The reports issued by valgrind are incorrect - we would
3953 ** prefer that the randomness be increased by making use of the
3954 ** uninitialized space in zBuf - but valgrind errors tend to worry
3955 ** some users. Rather than argue, it seems easier just to initialize
3956 ** the whole array and silence valgrind, even if that means less randomness
3957 ** in the random seed.
3958 **
3959 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00003960 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00003961 ** tests repeatable.
3962 */
danielk1977b4b47412007-08-17 15:53:36 +00003963 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00003964#if !defined(SQLITE_TEST)
3965 {
drh842b8642005-01-21 17:53:17 +00003966 int pid, fd;
3967 fd = open("/dev/urandom", O_RDONLY);
3968 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00003969 time_t t;
3970 time(&t);
danielk197790949c22007-08-17 16:50:38 +00003971 memcpy(zBuf, &t, sizeof(t));
3972 pid = getpid();
3973 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00003974 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00003975 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00003976 }else{
drh72cbd072008-10-14 17:58:38 +00003977 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00003978 close(fd);
3979 }
drhbbd42a62004-05-22 17:41:58 +00003980 }
3981#endif
drh72cbd072008-10-14 17:58:38 +00003982 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00003983}
3984
danielk1977b4b47412007-08-17 15:53:36 +00003985
drhbbd42a62004-05-22 17:41:58 +00003986/*
3987** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00003988** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00003989** The return value is the number of microseconds of sleep actually
3990** requested from the underlying operating system, a number which
3991** might be greater than or equal to the argument, but not less
3992** than the argument.
drhbbd42a62004-05-22 17:41:58 +00003993*/
danielk1977397d65f2008-11-19 11:35:39 +00003994static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00003995#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003996 struct timespec sp;
3997
3998 sp.tv_sec = microseconds / 1000000;
3999 sp.tv_nsec = (microseconds % 1000000) * 1000;
4000 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004001 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004002 return microseconds;
4003#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004004 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004005 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004006 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004007#else
danielk1977b4b47412007-08-17 15:53:36 +00004008 int seconds = (microseconds+999999)/1000000;
4009 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004010 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004011 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004012#endif
drh88f474a2006-01-02 20:00:12 +00004013}
4014
4015/*
drh6b9d6dd2008-12-03 19:34:47 +00004016** The following variable, if set to a non-zero value, is interpreted as
4017** the number of seconds since 1970 and is used to set the result of
4018** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004019*/
4020#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004021int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004022#endif
4023
4024/*
4025** Find the current time (in Universal Coordinated Time). Write the
4026** current time and date as a Julian Day number into *prNow and
4027** return 0. Return 1 if the time and date cannot be found.
4028*/
danielk1977397d65f2008-11-19 11:35:39 +00004029static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh6c7d5c52008-11-21 20:32:33 +00004030#if defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004031 time_t t;
4032 time(&t);
4033 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004034#elif OS_VXWORKS
4035 struct timespec sNow;
4036 clock_gettime(CLOCK_REALTIME, &sNow);
4037 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004038#else
4039 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004040 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004041 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4042#endif
danielk1977397d65f2008-11-19 11:35:39 +00004043
drhbbd42a62004-05-22 17:41:58 +00004044#ifdef SQLITE_TEST
4045 if( sqlite3_current_time ){
4046 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4047 }
4048#endif
danielk1977397d65f2008-11-19 11:35:39 +00004049 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004050 return 0;
4051}
danielk1977b4b47412007-08-17 15:53:36 +00004052
drh6b9d6dd2008-12-03 19:34:47 +00004053/*
4054** We added the xGetLastError() method with the intention of providing
4055** better low-level error messages when operating-system problems come up
4056** during SQLite operation. But so far, none of that has been implemented
4057** in the core. So this routine is never called. For now, it is merely
4058** a place-holder.
4059*/
danielk1977397d65f2008-11-19 11:35:39 +00004060static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4061 UNUSED_PARAMETER(NotUsed);
4062 UNUSED_PARAMETER(NotUsed2);
4063 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004064 return 0;
4065}
4066
drh153c62c2007-08-24 03:51:33 +00004067/*
drh734c9862008-11-28 15:37:20 +00004068************************ End of sqlite3_vfs methods ***************************
4069******************************************************************************/
4070
drh715ff302008-12-03 22:32:44 +00004071/******************************************************************************
4072************************** Begin Proxy Locking ********************************
4073**
4074** Proxy locking is a "uber-locking-method" in this sense: It uses the
4075** other locking methods on secondary lock files. Proxy locking is a
4076** meta-layer over top of the primitive locking implemented above. For
4077** this reason, the division that implements of proxy locking is deferred
4078** until late in the file (here) after all of the other I/O methods have
4079** been defined - so that the primitive locking methods are available
4080** as services to help with the implementation of proxy locking.
4081**
4082****
4083**
4084** The default locking schemes in SQLite use byte-range locks on the
4085** database file to coordinate safe, concurrent access by multiple readers
4086** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4087** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4088** as POSIX read & write locks over fixed set of locations (via fsctl),
4089** on AFP and SMB only exclusive byte-range locks are available via fsctl
4090** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4091** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4092** address in the shared range is taken for a SHARED lock, the entire
4093** shared range is taken for an EXCLUSIVE lock):
4094**
4095** PENDING_BYTE 0x40000000
4096** RESERVED_BYTE 0x40000001
4097** SHARED_RANGE 0x40000002 -> 0x40000200
4098**
4099** This works well on the local file system, but shows a nearly 100x
4100** slowdown in read performance on AFP because the AFP client disables
4101** the read cache when byte-range locks are present. Enabling the read
4102** cache exposes a cache coherency problem that is present on all OS X
4103** supported network file systems. NFS and AFP both observe the
4104** close-to-open semantics for ensuring cache coherency
4105** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4106** address the requirements for concurrent database access by multiple
4107** readers and writers
4108** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4109**
4110** To address the performance and cache coherency issues, proxy file locking
4111** changes the way database access is controlled by limiting access to a
4112** single host at a time and moving file locks off of the database file
4113** and onto a proxy file on the local file system.
4114**
4115**
4116** Using proxy locks
4117** -----------------
4118**
4119** C APIs
4120**
4121** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4122** <proxy_path> | ":auto:");
4123** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4124**
4125**
4126** SQL pragmas
4127**
4128** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4129** PRAGMA [database.]lock_proxy_file
4130**
4131** Specifying ":auto:" means that if there is a conch file with a matching
4132** host ID in it, the proxy path in the conch file will be used, otherwise
4133** a proxy path based on the user's temp dir
4134** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4135** actual proxy file name is generated from the name and path of the
4136** database file. For example:
4137**
4138** For database path "/Users/me/foo.db"
4139** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4140**
4141** Once a lock proxy is configured for a database connection, it can not
4142** be removed, however it may be switched to a different proxy path via
4143** the above APIs (assuming the conch file is not being held by another
4144** connection or process).
4145**
4146**
4147** How proxy locking works
4148** -----------------------
4149**
4150** Proxy file locking relies primarily on two new supporting files:
4151**
4152** * conch file to limit access to the database file to a single host
4153** at a time
4154**
4155** * proxy file to act as a proxy for the advisory locks normally
4156** taken on the database
4157**
4158** The conch file - to use a proxy file, sqlite must first "hold the conch"
4159** by taking an sqlite-style shared lock on the conch file, reading the
4160** contents and comparing the host's unique host ID (see below) and lock
4161** proxy path against the values stored in the conch. The conch file is
4162** stored in the same directory as the database file and the file name
4163** is patterned after the database file name as ".<databasename>-conch".
4164** If the conch file does not exist, or it's contents do not match the
4165** host ID and/or proxy path, then the lock is escalated to an exclusive
4166** lock and the conch file contents is updated with the host ID and proxy
4167** path and the lock is downgraded to a shared lock again. If the conch
4168** is held by another process (with a shared lock), the exclusive lock
4169** will fail and SQLITE_BUSY is returned.
4170**
4171** The proxy file - a single-byte file used for all advisory file locks
4172** normally taken on the database file. This allows for safe sharing
4173** of the database file for multiple readers and writers on the same
4174** host (the conch ensures that they all use the same local lock file).
4175**
4176** There is a third file - the host ID file - used as a persistent record
4177** of a unique identifier for the host, a 128-byte unique host id file
4178** in the path defined by the HOSTIDPATH macro (default value is
4179** /Library/Caches/.com.apple.sqliteConchHostId).
4180**
4181** Requesting the lock proxy does not immediately take the conch, it is
4182** only taken when the first request to lock database file is made.
4183** This matches the semantics of the traditional locking behavior, where
4184** opening a connection to a database file does not take a lock on it.
4185** The shared lock and an open file descriptor are maintained until
4186** the connection to the database is closed.
4187**
4188** The proxy file and the lock file are never deleted so they only need
4189** to be created the first time they are used.
4190**
4191** Configuration options
4192** ---------------------
4193**
4194** SQLITE_PREFER_PROXY_LOCKING
4195**
4196** Database files accessed on non-local file systems are
4197** automatically configured for proxy locking, lock files are
4198** named automatically using the same logic as
4199** PRAGMA lock_proxy_file=":auto:"
4200**
4201** SQLITE_PROXY_DEBUG
4202**
4203** Enables the logging of error messages during host id file
4204** retrieval and creation
4205**
4206** HOSTIDPATH
4207**
4208** Overrides the default host ID file path location
4209**
4210** LOCKPROXYDIR
4211**
4212** Overrides the default directory used for lock proxy files that
4213** are named automatically via the ":auto:" setting
4214**
4215** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4216**
4217** Permissions to use when creating a directory for storing the
4218** lock proxy files, only used when LOCKPROXYDIR is not set.
4219**
4220**
4221** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4222** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4223** force proxy locking to be used for every database file opened, and 0
4224** will force automatic proxy locking to be disabled for all database
4225** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4226** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4227*/
4228
4229/*
4230** Proxy locking is only available on MacOSX
4231*/
drhd2cb50b2009-01-09 21:41:17 +00004232#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004233
4234#ifdef SQLITE_TEST
4235/* simulate multiple hosts by creating unique hostid file paths */
4236int sqlite3_hostid_num = 0;
4237#endif
4238
4239/*
4240** The proxyLockingContext has the path and file structures for the remote
4241** and local proxy files in it
4242*/
4243typedef struct proxyLockingContext proxyLockingContext;
4244struct proxyLockingContext {
4245 unixFile *conchFile; /* Open conch file */
4246 char *conchFilePath; /* Name of the conch file */
4247 unixFile *lockProxy; /* Open proxy lock file */
4248 char *lockProxyPath; /* Name of the proxy lock file */
4249 char *dbPath; /* Name of the open file */
4250 int conchHeld; /* True if the conch is currently held */
4251 void *oldLockingContext; /* Original lockingcontext to restore on close */
4252 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4253};
4254
4255/* HOSTIDLEN and CONCHLEN both include space for the string
4256** terminating nul
4257*/
4258#define HOSTIDLEN 128
4259#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4260#ifndef HOSTIDPATH
4261# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4262#endif
4263
4264/* basically a copy of unixRandomness with different
4265** test behavior built in */
4266static int proxyGenerateHostID(char *pHostID){
4267 int pid, fd, len;
4268 unsigned char *key = (unsigned char *)pHostID;
4269
4270 memset(key, 0, HOSTIDLEN);
4271 len = 0;
4272 fd = open("/dev/urandom", O_RDONLY);
4273 if( fd>=0 ){
4274 len = read(fd, key, HOSTIDLEN);
4275 close(fd); /* silently leak the fd if it fails */
4276 }
4277 if( len < HOSTIDLEN ){
4278 time_t t;
4279 time(&t);
4280 memcpy(key, &t, sizeof(t));
4281 pid = getpid();
4282 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4283 }
4284
4285#ifdef MAKE_PRETTY_HOSTID
4286 {
4287 int i;
4288 /* filter the bytes into printable ascii characters and NUL terminate */
4289 key[(HOSTIDLEN-1)] = 0x00;
4290 for( i=0; i<(HOSTIDLEN-1); i++ ){
4291 unsigned char pa = key[i]&0x7F;
4292 if( pa<0x20 ){
4293 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4294 }else if( pa==0x7F ){
4295 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4296 }
4297 }
4298 }
4299#endif
4300 return SQLITE_OK;
4301}
4302
4303/* writes the host id path to path, path should be an pre-allocated buffer
4304** with enough space for a path
4305*/
4306static void proxyGetHostIDPath(char *path, size_t len){
4307 strlcpy(path, HOSTIDPATH, len);
4308#ifdef SQLITE_TEST
4309 if( sqlite3_hostid_num>0 ){
4310 char suffix[2] = "1";
4311 suffix[0] = suffix[0] + sqlite3_hostid_num;
4312 strlcat(path, suffix, len);
4313 }
4314#endif
4315 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4316}
4317
4318/* get the host ID from a sqlite hostid file stored in the
4319** user-specific tmp directory, create the ID if it's not there already
4320*/
4321static int proxyGetHostID(char *pHostID, int *pError){
4322 int fd;
4323 char path[MAXPATHLEN];
4324 size_t len;
4325 int rc=SQLITE_OK;
4326
4327 proxyGetHostIDPath(path, MAXPATHLEN);
4328 /* try to create the host ID file, if it already exists read the contents */
4329 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4330 if( fd<0 ){
4331 int err=errno;
4332
4333 if( err!=EEXIST ){
4334#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4335 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4336 path, strerror(err));
4337#endif
4338 return SQLITE_PERM;
4339 }
4340 /* couldn't create the file, read it instead */
4341 fd = open(path, O_RDONLY|O_EXCL);
4342 if( fd<0 ){
4343#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4344 int err = errno;
4345 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4346 path, strerror(err));
4347#endif
4348 return SQLITE_PERM;
4349 }
4350 len = pread(fd, pHostID, HOSTIDLEN, 0);
4351 if( len<0 ){
4352 *pError = errno;
4353 rc = SQLITE_IOERR_READ;
4354 }else if( len<HOSTIDLEN ){
4355 *pError = 0;
4356 rc = SQLITE_IOERR_SHORT_READ;
4357 }
4358 close(fd); /* silently leak the fd if it fails */
4359 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4360 return rc;
4361 }else{
4362 /* we're creating the host ID file (use a random string of bytes) */
4363 proxyGenerateHostID(pHostID);
4364 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4365 if( len<0 ){
4366 *pError = errno;
4367 rc = SQLITE_IOERR_WRITE;
4368 }else if( len<HOSTIDLEN ){
4369 *pError = 0;
4370 rc = SQLITE_IOERR_WRITE;
4371 }
4372 close(fd); /* silently leak the fd if it fails */
4373 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4374 return rc;
4375 }
4376}
4377
4378static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4379 int len;
4380 int dbLen;
4381 int i;
4382
4383#ifdef LOCKPROXYDIR
4384 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4385#else
4386# ifdef _CS_DARWIN_USER_TEMP_DIR
4387 {
4388 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4389 len = strlcat(lPath, "sqliteplocks", maxLen);
4390 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4391 /* if mkdir fails, handle as lock file creation failure */
4392 int err = errno;
4393# ifdef SQLITE_DEBUG
4394 if( err!=EEXIST ){
4395 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4396 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4397 }
4398# endif
4399 }else{
4400 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4401 }
4402
4403 }
4404# else
4405 len = strlcpy(lPath, "/tmp/", maxLen);
4406# endif
4407#endif
4408
4409 if( lPath[len-1]!='/' ){
4410 len = strlcat(lPath, "/", maxLen);
4411 }
4412
4413 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004414 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004415 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4416 char c = dbPath[i];
4417 lPath[i+len] = (c=='/')?'_':c;
4418 }
4419 lPath[i+len]='\0';
4420 strlcat(lPath, ":auto:", maxLen);
4421 return SQLITE_OK;
4422}
4423
4424/*
4425** Create a new VFS file descriptor (stored in memory obtained from
4426** sqlite3_malloc) and open the file named "path" in the file descriptor.
4427**
4428** The caller is responsible not only for closing the file descriptor
4429** but also for freeing the memory associated with the file descriptor.
4430*/
4431static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4432 int fd;
4433 int dirfd = -1;
4434 unixFile *pNew;
4435 int rc = SQLITE_OK;
4436 sqlite3_vfs dummyVfs;
4437
4438 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4439 if( fd<0 ){
4440 return SQLITE_CANTOPEN;
4441 }
4442
4443 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4444 if( pNew==NULL ){
4445 rc = SQLITE_NOMEM;
4446 goto end_create_proxy;
4447 }
4448 memset(pNew, 0, sizeof(unixFile));
4449
drh1875f7a2008-12-08 18:19:17 +00004450 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004451 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4452 if( rc==SQLITE_OK ){
4453 *ppFile = pNew;
4454 return SQLITE_OK;
4455 }
4456end_create_proxy:
4457 close(fd); /* silently leak fd if error, we're already in error */
4458 sqlite3_free(pNew);
4459 return rc;
4460}
4461
4462/* takes the conch by taking a shared lock and read the contents conch, if
4463** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4464** lockPath means that the lockPath in the conch file will be used if the
4465** host IDs match, or a new lock path will be generated automatically
4466** and written to the conch file.
4467*/
4468static int proxyTakeConch(unixFile *pFile){
4469 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4470
4471 if( pCtx->conchHeld>0 ){
4472 return SQLITE_OK;
4473 }else{
4474 unixFile *conchFile = pCtx->conchFile;
4475 char testValue[CONCHLEN];
4476 char conchValue[CONCHLEN];
4477 char lockPath[MAXPATHLEN];
4478 char *tLockPath = NULL;
4479 int rc = SQLITE_OK;
4480 int readRc = SQLITE_OK;
4481 int syncPerms = 0;
4482
4483 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4484 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4485
4486 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4487 if( rc==SQLITE_OK ){
4488 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004489 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004490 rc = proxyGetHostID(testValue, &pError);
4491 if( (rc&0xff)==SQLITE_IOERR ){
4492 pFile->lastErrno = pError;
4493 }
4494 if( pCtx->lockProxyPath ){
4495 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4496 }
4497 }
4498 if( rc!=SQLITE_OK ){
4499 goto end_takeconch;
4500 }
4501
4502 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4503 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4504 if( readRc!=SQLITE_OK ){
4505 if( (rc&0xff)==SQLITE_IOERR ){
4506 pFile->lastErrno = conchFile->lastErrno;
4507 }
4508 rc = readRc;
4509 goto end_takeconch;
4510 }
4511 /* if the conch has data compare the contents */
4512 if( !pCtx->lockProxyPath ){
4513 /* for auto-named local lock file, just check the host ID and we'll
4514 ** use the local lock file path that's already in there */
4515 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4516 tLockPath = (char *)&conchValue[HOSTIDLEN];
4517 goto end_takeconch;
4518 }
4519 }else{
4520 /* we've got the conch if conchValue matches our path and host ID */
4521 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4522 goto end_takeconch;
4523 }
4524 }
4525 }else{
4526 /* a short read means we're "creating" the conch (even though it could
4527 ** have been user-intervention), if we acquire the exclusive lock,
4528 ** we'll try to match the current on-disk permissions of the database
4529 */
4530 syncPerms = 1;
4531 }
4532
4533 /* either conch was emtpy or didn't match */
4534 if( !pCtx->lockProxyPath ){
4535 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4536 tLockPath = lockPath;
4537 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4538 }
4539
4540 /* update conch with host and path (this will fail if other process
4541 ** has a shared lock already) */
4542 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4543 if( rc==SQLITE_OK ){
4544 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4545 if( rc==SQLITE_OK && syncPerms ){
4546 struct stat buf;
4547 int err = fstat(pFile->h, &buf);
4548 if( err==0 ){
4549 /* try to match the database file permissions, ignore failure */
4550#ifndef SQLITE_PROXY_DEBUG
4551 fchmod(conchFile->h, buf.st_mode);
4552#else
4553 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4554 int code = errno;
4555 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4556 buf.st_mode, code, strerror(code));
4557 } else {
4558 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4559 }
4560 }else{
4561 int code = errno;
4562 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4563 err, code, strerror(code));
4564#endif
4565 }
4566 }
4567 }
4568 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4569
4570end_takeconch:
4571 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4572 if( rc==SQLITE_OK && pFile->openFlags ){
4573 if( pFile->h>=0 ){
4574#ifdef STRICT_CLOSE_ERROR
4575 if( close(pFile->h) ){
4576 pFile->lastErrno = errno;
4577 return SQLITE_IOERR_CLOSE;
4578 }
4579#else
4580 close(pFile->h); /* silently leak fd if fail */
4581#endif
4582 }
4583 pFile->h = -1;
4584 int fd = open(pCtx->dbPath, pFile->openFlags,
4585 SQLITE_DEFAULT_FILE_PERMISSIONS);
4586 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4587 if( fd>=0 ){
4588 pFile->h = fd;
4589 }else{
drh1875f7a2008-12-08 18:19:17 +00004590 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4591 during locking */
drh715ff302008-12-03 22:32:44 +00004592 }
4593 }
4594 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4595 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004596 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004597 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4598 }
4599 if( rc==SQLITE_OK ){
4600 pCtx->conchHeld = 1;
4601
4602 if( tLockPath ){
4603 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4604 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4605 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4606 pCtx->lockProxyPath;
4607 }
4608 }
4609 } else {
4610 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4611 }
4612 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4613 return rc;
4614 }
4615}
4616
4617/*
4618** If pFile holds a lock on a conch file, then release that lock.
4619*/
4620static int proxyReleaseConch(unixFile *pFile){
4621 int rc; /* Subroutine return code */
4622 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4623 unixFile *conchFile; /* Name of the conch file */
4624
4625 pCtx = (proxyLockingContext *)pFile->lockingContext;
4626 conchFile = pCtx->conchFile;
4627 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4628 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4629 getpid());
4630 pCtx->conchHeld = 0;
4631 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4632 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4633 (rc==SQLITE_OK ? "ok" : "failed"));
4634 return rc;
4635}
4636
4637/*
4638** Given the name of a database file, compute the name of its conch file.
4639** Store the conch filename in memory obtained from sqlite3_malloc().
4640** Make *pConchPath point to the new name. Return SQLITE_OK on success
4641** or SQLITE_NOMEM if unable to obtain memory.
4642**
4643** The caller is responsible for ensuring that the allocated memory
4644** space is eventually freed.
4645**
4646** *pConchPath is set to NULL if a memory allocation error occurs.
4647*/
4648static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4649 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004650 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004651 char *conchPath; /* buffer in which to construct conch name */
4652
4653 /* Allocate space for the conch filename and initialize the name to
4654 ** the name of the original database file. */
4655 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4656 if( conchPath==0 ){
4657 return SQLITE_NOMEM;
4658 }
4659 memcpy(conchPath, dbPath, len+1);
4660
4661 /* now insert a "." before the last / character */
4662 for( i=(len-1); i>=0; i-- ){
4663 if( conchPath[i]=='/' ){
4664 i++;
4665 break;
4666 }
4667 }
4668 conchPath[i]='.';
4669 while ( i<len ){
4670 conchPath[i+1]=dbPath[i];
4671 i++;
4672 }
4673
4674 /* append the "-conch" suffix to the file */
4675 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004676 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004677
4678 return SQLITE_OK;
4679}
4680
4681
4682/* Takes a fully configured proxy locking-style unix file and switches
4683** the local lock file path
4684*/
4685static int switchLockProxyPath(unixFile *pFile, const char *path) {
4686 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4687 char *oldPath = pCtx->lockProxyPath;
4688 int rc = SQLITE_OK;
4689
4690 if( pFile->locktype!=NO_LOCK ){
4691 return SQLITE_BUSY;
4692 }
4693
4694 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4695 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4696 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4697 return SQLITE_OK;
4698 }else{
4699 unixFile *lockProxy = pCtx->lockProxy;
4700 pCtx->lockProxy=NULL;
4701 pCtx->conchHeld = 0;
4702 if( lockProxy!=NULL ){
4703 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4704 if( rc ) return rc;
4705 sqlite3_free(lockProxy);
4706 }
4707 sqlite3_free(oldPath);
4708 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4709 }
4710
4711 return rc;
4712}
4713
4714/*
4715** pFile is a file that has been opened by a prior xOpen call. dbPath
4716** is a string buffer at least MAXPATHLEN+1 characters in size.
4717**
4718** This routine find the filename associated with pFile and writes it
4719** int dbPath.
4720*/
4721static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004722#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004723 if( pFile->pMethod == &afpIoMethods ){
4724 /* afp style keeps a reference to the db path in the filePath field
4725 ** of the struct */
drhea678832008-12-10 19:26:22 +00004726 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004727 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4728 }else
4729#endif
4730 if( pFile->pMethod == &dotlockIoMethods ){
4731 /* dot lock style uses the locking context to store the dot lock
4732 ** file path */
4733 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4734 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4735 }else{
4736 /* all other styles use the locking context to store the db file path */
4737 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4738 strcpy(dbPath, (char *)pFile->lockingContext);
4739 }
4740 return SQLITE_OK;
4741}
4742
4743/*
4744** Takes an already filled in unix file and alters it so all file locking
4745** will be performed on the local proxy lock file. The following fields
4746** are preserved in the locking context so that they can be restored and
4747** the unix structure properly cleaned up at close time:
4748** ->lockingContext
4749** ->pMethod
4750*/
4751static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4752 proxyLockingContext *pCtx;
4753 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4754 char *lockPath=NULL;
4755 int rc = SQLITE_OK;
4756
4757 if( pFile->locktype!=NO_LOCK ){
4758 return SQLITE_BUSY;
4759 }
4760 proxyGetDbPathForUnixFile(pFile, dbPath);
4761 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4762 lockPath=NULL;
4763 }else{
4764 lockPath=(char *)path;
4765 }
4766
4767 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4768 (lockPath ? lockPath : ":auto:"), getpid());
4769
4770 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4771 if( pCtx==0 ){
4772 return SQLITE_NOMEM;
4773 }
4774 memset(pCtx, 0, sizeof(*pCtx));
4775
4776 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4777 if( rc==SQLITE_OK ){
4778 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4779 }
4780 if( rc==SQLITE_OK && lockPath ){
4781 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4782 }
4783
4784 if( rc==SQLITE_OK ){
4785 /* all memory is allocated, proxys are created and assigned,
4786 ** switch the locking context and pMethod then return.
4787 */
4788 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4789 pCtx->oldLockingContext = pFile->lockingContext;
4790 pFile->lockingContext = pCtx;
4791 pCtx->pOldMethod = pFile->pMethod;
4792 pFile->pMethod = &proxyIoMethods;
4793 }else{
4794 if( pCtx->conchFile ){
4795 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4796 if( rc ) return rc;
4797 sqlite3_free(pCtx->conchFile);
4798 }
4799 sqlite3_free(pCtx->conchFilePath);
4800 sqlite3_free(pCtx);
4801 }
4802 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4803 (rc==SQLITE_OK ? "ok" : "failed"));
4804 return rc;
4805}
4806
4807
4808/*
4809** This routine handles sqlite3_file_control() calls that are specific
4810** to proxy locking.
4811*/
4812static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4813 switch( op ){
4814 case SQLITE_GET_LOCKPROXYFILE: {
4815 unixFile *pFile = (unixFile*)id;
4816 if( pFile->pMethod == &proxyIoMethods ){
4817 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4818 proxyTakeConch(pFile);
4819 if( pCtx->lockProxyPath ){
4820 *(const char **)pArg = pCtx->lockProxyPath;
4821 }else{
4822 *(const char **)pArg = ":auto: (not held)";
4823 }
4824 } else {
4825 *(const char **)pArg = NULL;
4826 }
4827 return SQLITE_OK;
4828 }
4829 case SQLITE_SET_LOCKPROXYFILE: {
4830 unixFile *pFile = (unixFile*)id;
4831 int rc = SQLITE_OK;
4832 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4833 if( pArg==NULL || (const char *)pArg==0 ){
4834 if( isProxyStyle ){
4835 /* turn off proxy locking - not supported */
4836 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4837 }else{
4838 /* turn off proxy locking - already off - NOOP */
4839 rc = SQLITE_OK;
4840 }
4841 }else{
4842 const char *proxyPath = (const char *)pArg;
4843 if( isProxyStyle ){
4844 proxyLockingContext *pCtx =
4845 (proxyLockingContext*)pFile->lockingContext;
4846 if( !strcmp(pArg, ":auto:")
4847 || (pCtx->lockProxyPath &&
4848 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4849 ){
4850 rc = SQLITE_OK;
4851 }else{
4852 rc = switchLockProxyPath(pFile, proxyPath);
4853 }
4854 }else{
4855 /* turn on proxy file locking */
4856 rc = proxyTransformUnixFile(pFile, proxyPath);
4857 }
4858 }
4859 return rc;
4860 }
4861 default: {
4862 assert( 0 ); /* The call assures that only valid opcodes are sent */
4863 }
4864 }
4865 /*NOTREACHED*/
4866 return SQLITE_ERROR;
4867}
4868
4869/*
4870** Within this division (the proxying locking implementation) the procedures
4871** above this point are all utilities. The lock-related methods of the
4872** proxy-locking sqlite3_io_method object follow.
4873*/
4874
4875
4876/*
4877** This routine checks if there is a RESERVED lock held on the specified
4878** file by this or any other process. If such a lock is held, set *pResOut
4879** to a non-zero value otherwise *pResOut is set to zero. The return value
4880** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4881*/
4882static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4883 unixFile *pFile = (unixFile*)id;
4884 int rc = proxyTakeConch(pFile);
4885 if( rc==SQLITE_OK ){
4886 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4887 unixFile *proxy = pCtx->lockProxy;
4888 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4889 }
4890 return rc;
4891}
4892
4893/*
4894** Lock the file with the lock specified by parameter locktype - one
4895** of the following:
4896**
4897** (1) SHARED_LOCK
4898** (2) RESERVED_LOCK
4899** (3) PENDING_LOCK
4900** (4) EXCLUSIVE_LOCK
4901**
4902** Sometimes when requesting one lock state, additional lock states
4903** are inserted in between. The locking might fail on one of the later
4904** transitions leaving the lock state different from what it started but
4905** still short of its goal. The following chart shows the allowed
4906** transitions and the inserted intermediate states:
4907**
4908** UNLOCKED -> SHARED
4909** SHARED -> RESERVED
4910** SHARED -> (PENDING) -> EXCLUSIVE
4911** RESERVED -> (PENDING) -> EXCLUSIVE
4912** PENDING -> EXCLUSIVE
4913**
4914** This routine will only increase a lock. Use the sqlite3OsUnlock()
4915** routine to lower a locking level.
4916*/
4917static int proxyLock(sqlite3_file *id, int locktype) {
4918 unixFile *pFile = (unixFile*)id;
4919 int rc = proxyTakeConch(pFile);
4920 if( rc==SQLITE_OK ){
4921 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4922 unixFile *proxy = pCtx->lockProxy;
4923 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4924 pFile->locktype = proxy->locktype;
4925 }
4926 return rc;
4927}
4928
4929
4930/*
4931** Lower the locking level on file descriptor pFile to locktype. locktype
4932** must be either NO_LOCK or SHARED_LOCK.
4933**
4934** If the locking level of the file descriptor is already at or below
4935** the requested locking level, this routine is a no-op.
4936*/
4937static int proxyUnlock(sqlite3_file *id, int locktype) {
4938 unixFile *pFile = (unixFile*)id;
4939 int rc = proxyTakeConch(pFile);
4940 if( rc==SQLITE_OK ){
4941 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4942 unixFile *proxy = pCtx->lockProxy;
4943 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
4944 pFile->locktype = proxy->locktype;
4945 }
4946 return rc;
4947}
4948
4949/*
4950** Close a file that uses proxy locks.
4951*/
4952static int proxyClose(sqlite3_file *id) {
4953 if( id ){
4954 unixFile *pFile = (unixFile*)id;
4955 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4956 unixFile *lockProxy = pCtx->lockProxy;
4957 unixFile *conchFile = pCtx->conchFile;
4958 int rc = SQLITE_OK;
4959
4960 if( lockProxy ){
4961 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
4962 if( rc ) return rc;
4963 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
4964 if( rc ) return rc;
4965 sqlite3_free(lockProxy);
4966 pCtx->lockProxy = 0;
4967 }
4968 if( conchFile ){
4969 if( pCtx->conchHeld ){
4970 rc = proxyReleaseConch(pFile);
4971 if( rc ) return rc;
4972 }
4973 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
4974 if( rc ) return rc;
4975 sqlite3_free(conchFile);
4976 }
4977 sqlite3_free(pCtx->lockProxyPath);
4978 sqlite3_free(pCtx->conchFilePath);
4979 sqlite3_free(pCtx->dbPath);
4980 /* restore the original locking context and pMethod then close it */
4981 pFile->lockingContext = pCtx->oldLockingContext;
4982 pFile->pMethod = pCtx->pOldMethod;
4983 sqlite3_free(pCtx);
4984 return pFile->pMethod->xClose(id);
4985 }
4986 return SQLITE_OK;
4987}
4988
4989
4990
drhd2cb50b2009-01-09 21:41:17 +00004991#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00004992/*
4993** The proxy locking style is intended for use with AFP filesystems.
4994** And since AFP is only supported on MacOSX, the proxy locking is also
4995** restricted to MacOSX.
4996**
4997**
4998******************* End of the proxy lock implementation **********************
4999******************************************************************************/
5000
drh734c9862008-11-28 15:37:20 +00005001/*
danielk1977e339d652008-06-28 11:23:00 +00005002** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005003**
5004** This routine registers all VFS implementations for unix-like operating
5005** systems. This routine, and the sqlite3_os_end() routine that follows,
5006** should be the only routines in this file that are visible from other
5007** files.
drh6b9d6dd2008-12-03 19:34:47 +00005008**
5009** This routine is called once during SQLite initialization and by a
5010** single thread. The memory allocation and mutex subsystems have not
5011** necessarily been initialized when this routine is called, and so they
5012** should not be used.
drh153c62c2007-08-24 03:51:33 +00005013*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005014int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005015 /*
5016 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005017 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5018 ** to the "finder" function. (pAppData is a pointer to a pointer because
5019 ** silly C90 rules prohibit a void* from being cast to a function pointer
5020 ** and so we have to go through the intermediate pointer to avoid problems
5021 ** when compiling with -pedantic-errors on GCC.)
5022 **
5023 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005024 ** finder-function. The finder-function returns a pointer to the
5025 ** sqlite_io_methods object that implements the desired locking
5026 ** behaviors. See the division above that contains the IOMETHODS
5027 ** macro for addition information on finder-functions.
5028 **
5029 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5030 ** object. But the "autolockIoFinder" available on MacOSX does a little
5031 ** more than that; it looks at the filesystem type that hosts the
5032 ** database file and tries to choose an locking method appropriate for
5033 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005034 */
drh7708e972008-11-29 00:56:52 +00005035 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005036 1, /* iVersion */ \
5037 sizeof(unixFile), /* szOsFile */ \
5038 MAX_PATHNAME, /* mxPathname */ \
5039 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005040 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005041 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005042 unixOpen, /* xOpen */ \
5043 unixDelete, /* xDelete */ \
5044 unixAccess, /* xAccess */ \
5045 unixFullPathname, /* xFullPathname */ \
5046 unixDlOpen, /* xDlOpen */ \
5047 unixDlError, /* xDlError */ \
5048 unixDlSym, /* xDlSym */ \
5049 unixDlClose, /* xDlClose */ \
5050 unixRandomness, /* xRandomness */ \
5051 unixSleep, /* xSleep */ \
5052 unixCurrentTime, /* xCurrentTime */ \
5053 unixGetLastError /* xGetLastError */ \
5054 }
5055
drh6b9d6dd2008-12-03 19:34:47 +00005056 /*
5057 ** All default VFSes for unix are contained in the following array.
5058 **
5059 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5060 ** by the SQLite core when the VFS is registered. So the following
5061 ** array cannot be const.
5062 */
danielk1977e339d652008-06-28 11:23:00 +00005063 static sqlite3_vfs aVfs[] = {
drhd2cb50b2009-01-09 21:41:17 +00005064#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005065 UNIXVFS("unix", autolockIoFinder ),
5066#else
5067 UNIXVFS("unix", posixIoFinder ),
5068#endif
5069 UNIXVFS("unix-none", nolockIoFinder ),
5070 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005071#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005072 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005073#endif
5074#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005075 UNIXVFS("unix-posix", posixIoFinder ),
5076 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005077#endif
drhd2cb50b2009-01-09 21:41:17 +00005078#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005079 UNIXVFS("unix-afp", afpIoFinder ),
5080 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005081#endif
drh153c62c2007-08-24 03:51:33 +00005082 };
drh6b9d6dd2008-12-03 19:34:47 +00005083 unsigned int i; /* Loop counter */
5084
5085 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005086 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005087 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005088 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005089 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005090}
danielk1977e339d652008-06-28 11:23:00 +00005091
5092/*
drh6b9d6dd2008-12-03 19:34:47 +00005093** Shutdown the operating system interface.
5094**
5095** Some operating systems might need to do some cleanup in this routine,
5096** to release dynamically allocated objects. But not on unix.
5097** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005098*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005099int sqlite3_os_end(void){
5100 return SQLITE_OK;
5101}
drhdce8bdb2007-08-16 13:01:44 +00005102
danielk197729bafea2008-06-26 10:41:19 +00005103#endif /* SQLITE_OS_UNIX */