blob: bc0f32cde1a443987601f3a6d051c6a86852253e [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**
drh06150f92009-07-03 12:57:58 +000046** $Id: os_unix.c,v 1.254 2009/07/03 12:57:58 drh 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;
drh06150f92009-07-03 12:57:58 +0000842 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
843 pthread_join(t, 0);
844 }
drh5fdae772004-06-29 03:29:00 +0000845 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000846 if( d.result!=0 ) return;
847 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000848}
drh06150f92009-07-03 12:57:58 +0000849#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000850
drhbbd42a62004-05-22 17:41:58 +0000851/*
drh6c7d5c52008-11-21 20:32:33 +0000852** Release a unixLockInfo structure previously allocated by findLockInfo().
853*/
854static void releaseLockInfo(struct unixLockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000855 if( pLock ){
856 pLock->nRef--;
857 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000858 if( pLock->pPrev ){
859 assert( pLock->pPrev->pNext==pLock );
860 pLock->pPrev->pNext = pLock->pNext;
861 }else{
862 assert( lockList==pLock );
863 lockList = pLock->pNext;
864 }
865 if( pLock->pNext ){
866 assert( pLock->pNext->pPrev==pLock );
867 pLock->pNext->pPrev = pLock->pPrev;
868 }
danielk1977e339d652008-06-28 11:23:00 +0000869 sqlite3_free(pLock);
870 }
drhbbd42a62004-05-22 17:41:58 +0000871 }
872}
873
874/*
drh6c7d5c52008-11-21 20:32:33 +0000875** Release a unixOpenCnt structure previously allocated by findLockInfo().
drhbbd42a62004-05-22 17:41:58 +0000876*/
drh6c7d5c52008-11-21 20:32:33 +0000877static void releaseOpenCnt(struct unixOpenCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000878 if( pOpen ){
879 pOpen->nRef--;
880 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000881 if( pOpen->pPrev ){
882 assert( pOpen->pPrev->pNext==pOpen );
883 pOpen->pPrev->pNext = pOpen->pNext;
884 }else{
885 assert( openList==pOpen );
886 openList = pOpen->pNext;
887 }
888 if( pOpen->pNext ){
889 assert( pOpen->pNext->pPrev==pOpen );
890 pOpen->pNext->pPrev = pOpen->pPrev;
891 }
892 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000893 sqlite3_free(pOpen);
894 }
drhbbd42a62004-05-22 17:41:58 +0000895 }
896}
897
drh6c7d5c52008-11-21 20:32:33 +0000898/*
899** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
900** describes that file descriptor. Create new ones if necessary. The
901** return values might be uninitialized if an error occurs.
902**
903** Return an appropriate error code.
904*/
905static int findLockInfo(
906 unixFile *pFile, /* Unix file with file desc used in the key */
907 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
908 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
909){
910 int rc; /* System call return code */
911 int fd; /* The file descriptor for pFile */
912 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
913 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
914 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000915 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000916 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
917
918 /* Get low-level information about the file that we can used to
919 ** create a unique name for the file.
920 */
921 fd = pFile->h;
922 rc = fstat(fd, &statbuf);
923 if( rc!=0 ){
924 pFile->lastErrno = errno;
925#ifdef EOVERFLOW
926 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
927#endif
928 return SQLITE_IOERR;
929 }
930
drheb0d74f2009-02-03 15:27:02 +0000931#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000932 /* On OS X on an msdos filesystem, the inode number is reported
933 ** incorrectly for zero-size files. See ticket #3260. To work
934 ** around this problem (we consider it a bug in OS X, not SQLite)
935 ** we always increase the file size to 1 by writing a single byte
936 ** prior to accessing the inode number. The one byte written is
937 ** an ASCII 'S' character which also happens to be the first byte
938 ** in the header of every SQLite database. In this way, if there
939 ** is a race condition such that another thread has already populated
940 ** the first page of the database, no damage is done.
941 */
942 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000943 rc = write(fd, "S", 1);
944 if( rc!=1 ){
945 return SQLITE_IOERR;
946 }
drh6c7d5c52008-11-21 20:32:33 +0000947 rc = fstat(fd, &statbuf);
948 if( rc!=0 ){
949 pFile->lastErrno = errno;
950 return SQLITE_IOERR;
951 }
952 }
drheb0d74f2009-02-03 15:27:02 +0000953#endif
drh6c7d5c52008-11-21 20:32:33 +0000954
955 memset(&lockKey, 0, sizeof(lockKey));
956 lockKey.fid.dev = statbuf.st_dev;
957#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000958 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000959#else
960 lockKey.fid.ino = statbuf.st_ino;
961#endif
drh734c9862008-11-28 15:37:20 +0000962#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000963 if( threadsOverrideEachOthersLocks<0 ){
964 testThreadLockingBehavior(fd);
965 }
966 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
967#endif
968 fileId = lockKey.fid;
969 if( ppLock!=0 ){
970 pLock = lockList;
971 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
972 pLock = pLock->pNext;
973 }
974 if( pLock==0 ){
975 pLock = sqlite3_malloc( sizeof(*pLock) );
976 if( pLock==0 ){
977 rc = SQLITE_NOMEM;
978 goto exit_findlockinfo;
979 }
980 pLock->lockKey = lockKey;
981 pLock->nRef = 1;
982 pLock->cnt = 0;
983 pLock->locktype = 0;
984 pLock->pNext = lockList;
985 pLock->pPrev = 0;
986 if( lockList ) lockList->pPrev = pLock;
987 lockList = pLock;
988 }else{
989 pLock->nRef++;
990 }
991 *ppLock = pLock;
992 }
993 if( ppOpen!=0 ){
994 pOpen = openList;
995 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
996 pOpen = pOpen->pNext;
997 }
998 if( pOpen==0 ){
999 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1000 if( pOpen==0 ){
1001 releaseLockInfo(pLock);
1002 rc = SQLITE_NOMEM;
1003 goto exit_findlockinfo;
1004 }
1005 pOpen->fileId = fileId;
1006 pOpen->nRef = 1;
1007 pOpen->nLock = 0;
1008 pOpen->nPending = 0;
1009 pOpen->aPending = 0;
1010 pOpen->pNext = openList;
1011 pOpen->pPrev = 0;
1012 if( openList ) openList->pPrev = pOpen;
1013 openList = pOpen;
1014#if OS_VXWORKS
1015 pOpen->pSem = NULL;
1016 pOpen->aSemName[0] = '\0';
1017#endif
1018 }else{
1019 pOpen->nRef++;
1020 }
1021 *ppOpen = pOpen;
1022 }
1023
1024exit_findlockinfo:
1025 return rc;
1026}
drh6c7d5c52008-11-21 20:32:33 +00001027
drh7708e972008-11-29 00:56:52 +00001028/*
1029** If we are currently in a different thread than the thread that the
1030** unixFile argument belongs to, then transfer ownership of the unixFile
1031** over to the current thread.
1032**
1033** A unixFile is only owned by a thread on systems that use LinuxThreads.
1034**
1035** Ownership transfer is only allowed if the unixFile is currently unlocked.
1036** If the unixFile is locked and an ownership is wrong, then return
1037** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1038*/
1039#if SQLITE_THREADSAFE && defined(__linux__)
1040static int transferOwnership(unixFile *pFile){
1041 int rc;
1042 pthread_t hSelf;
1043 if( threadsOverrideEachOthersLocks ){
1044 /* Ownership transfers not needed on this system */
1045 return SQLITE_OK;
1046 }
1047 hSelf = pthread_self();
1048 if( pthread_equal(pFile->tid, hSelf) ){
1049 /* We are still in the same thread */
1050 OSTRACE1("No-transfer, same thread\n");
1051 return SQLITE_OK;
1052 }
1053 if( pFile->locktype!=NO_LOCK ){
1054 /* We cannot change ownership while we are holding a lock! */
1055 return SQLITE_MISUSE;
1056 }
1057 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1058 pFile->h, pFile->tid, hSelf);
1059 pFile->tid = hSelf;
1060 if (pFile->pLock != NULL) {
1061 releaseLockInfo(pFile->pLock);
1062 rc = findLockInfo(pFile, &pFile->pLock, 0);
1063 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1064 locktypeName(pFile->locktype),
1065 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1066 return rc;
1067 } else {
1068 return SQLITE_OK;
1069 }
1070}
1071#else /* if not SQLITE_THREADSAFE */
1072 /* On single-threaded builds, ownership transfer is a no-op */
1073# define transferOwnership(X) SQLITE_OK
1074#endif /* SQLITE_THREADSAFE */
1075
aswift5b1a2562008-08-22 00:22:35 +00001076
1077/*
danielk197713adf8a2004-06-03 16:08:41 +00001078** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001079** file by this or any other process. If such a lock is held, set *pResOut
1080** to a non-zero value otherwise *pResOut is set to zero. The return value
1081** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001082*/
danielk1977861f7452008-06-05 11:39:11 +00001083static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001084 int rc = SQLITE_OK;
1085 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001086 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001087
danielk1977861f7452008-06-05 11:39:11 +00001088 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1089
drh054889e2005-11-30 03:20:31 +00001090 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001091 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001092
1093 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001094 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001095 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001096 }
1097
drh2ac3ee92004-06-07 16:27:46 +00001098 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001099 */
danielk197709480a92009-02-09 05:32:32 +00001100#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001101 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001102 struct flock lock;
1103 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001104 lock.l_start = RESERVED_BYTE;
1105 lock.l_len = 1;
1106 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001107 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1108 int tErrno = errno;
1109 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1110 pFile->lastErrno = tErrno;
1111 } else if( lock.l_type!=F_UNLCK ){
1112 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001113 }
1114 }
danielk197709480a92009-02-09 05:32:32 +00001115#endif
danielk197713adf8a2004-06-03 16:08:41 +00001116
drh6c7d5c52008-11-21 20:32:33 +00001117 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001118 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001119
aswift5b1a2562008-08-22 00:22:35 +00001120 *pResOut = reserved;
1121 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001122}
1123
1124/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001125** Lock the file with the lock specified by parameter locktype - one
1126** of the following:
1127**
drh2ac3ee92004-06-07 16:27:46 +00001128** (1) SHARED_LOCK
1129** (2) RESERVED_LOCK
1130** (3) PENDING_LOCK
1131** (4) EXCLUSIVE_LOCK
1132**
drhb3e04342004-06-08 00:47:47 +00001133** Sometimes when requesting one lock state, additional lock states
1134** are inserted in between. The locking might fail on one of the later
1135** transitions leaving the lock state different from what it started but
1136** still short of its goal. The following chart shows the allowed
1137** transitions and the inserted intermediate states:
1138**
1139** UNLOCKED -> SHARED
1140** SHARED -> RESERVED
1141** SHARED -> (PENDING) -> EXCLUSIVE
1142** RESERVED -> (PENDING) -> EXCLUSIVE
1143** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001144**
drha6abd042004-06-09 17:37:22 +00001145** This routine will only increase a lock. Use the sqlite3OsUnlock()
1146** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001147*/
danielk197762079062007-08-15 17:08:46 +00001148static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001149 /* The following describes the implementation of the various locks and
1150 ** lock transitions in terms of the POSIX advisory shared and exclusive
1151 ** lock primitives (called read-locks and write-locks below, to avoid
1152 ** confusion with SQLite lock names). The algorithms are complicated
1153 ** slightly in order to be compatible with windows systems simultaneously
1154 ** accessing the same database file, in case that is ever required.
1155 **
1156 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1157 ** byte', each single bytes at well known offsets, and the 'shared byte
1158 ** range', a range of 510 bytes at a well known offset.
1159 **
1160 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1161 ** byte'. If this is successful, a random byte from the 'shared byte
1162 ** range' is read-locked and the lock on the 'pending byte' released.
1163 **
danielk197790ba3bd2004-06-25 08:32:25 +00001164 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1165 ** A RESERVED lock is implemented by grabbing a write-lock on the
1166 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001167 **
1168 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001169 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1170 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1171 ** obtained, but existing SHARED locks are allowed to persist. A process
1172 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1173 ** This property is used by the algorithm for rolling back a journal file
1174 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001175 **
danielk197790ba3bd2004-06-25 08:32:25 +00001176 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1177 ** implemented by obtaining a write-lock on the entire 'shared byte
1178 ** range'. Since all other locks require a read-lock on one of the bytes
1179 ** within this range, this ensures that no other locks are held on the
1180 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001181 **
1182 ** The reason a single byte cannot be used instead of the 'shared byte
1183 ** range' is that some versions of windows do not support read-locks. By
1184 ** locking a random byte from a range, concurrent SHARED locks may exist
1185 ** even if the locking primitive used is always a write-lock.
1186 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001187 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001188 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001189 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001190 struct flock lock;
1191 int s;
1192
drh054889e2005-11-30 03:20:31 +00001193 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001194 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001195 locktypeName(locktype), locktypeName(pFile->locktype),
1196 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001197
1198 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001199 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001200 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001201 */
drh054889e2005-11-30 03:20:31 +00001202 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001203 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001204 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001205 return SQLITE_OK;
1206 }
1207
drhb3e04342004-06-08 00:47:47 +00001208 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001209 */
drh054889e2005-11-30 03:20:31 +00001210 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001211 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001212 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001213
drh054889e2005-11-30 03:20:31 +00001214 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001215 */
drh6c7d5c52008-11-21 20:32:33 +00001216 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001217
drh029b44b2006-01-15 00:13:15 +00001218 /* Make sure the current thread owns the pFile.
1219 */
1220 rc = transferOwnership(pFile);
1221 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001222 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001223 return rc;
1224 }
drh64b1bea2006-01-15 02:30:57 +00001225 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001226
danielk1977ad94b582007-08-20 06:44:22 +00001227 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 ** handle that precludes the requested lock, return BUSY.
1229 */
drh054889e2005-11-30 03:20:31 +00001230 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001231 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001232 ){
1233 rc = SQLITE_BUSY;
1234 goto end_lock;
1235 }
1236
1237 /* If a SHARED lock is requested, and some thread using this PID already
1238 ** has a SHARED or RESERVED lock, then increment reference counts and
1239 ** return SQLITE_OK.
1240 */
1241 if( locktype==SHARED_LOCK &&
1242 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1243 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001244 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001245 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001246 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001247 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001248 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001249 goto end_lock;
1250 }
1251
danielk197713adf8a2004-06-03 16:08:41 +00001252 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001253
danielk19779a1d0ab2004-06-01 14:09:28 +00001254 lock.l_whence = SEEK_SET;
1255
drh3cde3bb2004-06-12 02:17:14 +00001256 /* A PENDING lock is needed before acquiring a SHARED lock and before
1257 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1258 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001259 */
drh3cde3bb2004-06-12 02:17:14 +00001260 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001261 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001262 ){
danielk1977489468c2004-06-28 08:25:47 +00001263 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001264 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001265 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001266 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001267 int tErrno = errno;
1268 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1269 if( IS_LOCK_ERROR(rc) ){
1270 pFile->lastErrno = tErrno;
1271 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001272 goto end_lock;
1273 }
drh3cde3bb2004-06-12 02:17:14 +00001274 }
1275
1276
1277 /* If control gets to this point, then actually go ahead and make
1278 ** operating system calls for the specified lock.
1279 */
1280 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001281 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001282 assert( pLock->cnt==0 );
1283 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001284
drh2ac3ee92004-06-07 16:27:46 +00001285 /* Now get the read-lock */
1286 lock.l_start = SHARED_FIRST;
1287 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001288 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1289 tErrno = errno;
1290 }
drh2ac3ee92004-06-07 16:27:46 +00001291 /* Drop the temporary PENDING lock */
1292 lock.l_start = PENDING_BYTE;
1293 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001295 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001296 if( s != -1 ){
1297 /* This could happen with a network mount */
1298 tErrno = errno;
1299 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1300 if( IS_LOCK_ERROR(rc) ){
1301 pFile->lastErrno = tErrno;
1302 }
1303 goto end_lock;
1304 }
drh2b4b5962005-06-15 17:47:55 +00001305 }
drhe2396a12007-03-29 20:19:58 +00001306 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001307 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1308 if( IS_LOCK_ERROR(rc) ){
1309 pFile->lastErrno = tErrno;
1310 }
drhbbd42a62004-05-22 17:41:58 +00001311 }else{
drh054889e2005-11-30 03:20:31 +00001312 pFile->locktype = SHARED_LOCK;
1313 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001314 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001315 }
drh3cde3bb2004-06-12 02:17:14 +00001316 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1317 /* We are trying for an exclusive lock but another thread in this
1318 ** same process is still holding a shared lock. */
1319 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001320 }else{
drh3cde3bb2004-06-12 02:17:14 +00001321 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001322 ** assumed that there is a SHARED or greater lock on the file
1323 ** already.
1324 */
drh054889e2005-11-30 03:20:31 +00001325 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001326 lock.l_type = F_WRLCK;
1327 switch( locktype ){
1328 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001329 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001330 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001331 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001332 lock.l_start = SHARED_FIRST;
1333 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001334 break;
1335 default:
1336 assert(0);
1337 }
drh054889e2005-11-30 03:20:31 +00001338 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001339 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001340 int tErrno = errno;
1341 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1342 if( IS_LOCK_ERROR(rc) ){
1343 pFile->lastErrno = tErrno;
1344 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001345 }
drhbbd42a62004-05-22 17:41:58 +00001346 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001347
drh8f941bc2009-01-14 23:03:40 +00001348
1349#ifndef NDEBUG
1350 /* Set up the transaction-counter change checking flags when
1351 ** transitioning from a SHARED to a RESERVED lock. The change
1352 ** from SHARED to RESERVED marks the beginning of a normal
1353 ** write operation (not a hot journal rollback).
1354 */
1355 if( rc==SQLITE_OK
1356 && pFile->locktype<=SHARED_LOCK
1357 && locktype==RESERVED_LOCK
1358 ){
1359 pFile->transCntrChng = 0;
1360 pFile->dbUpdate = 0;
1361 pFile->inNormalWrite = 1;
1362 }
1363#endif
1364
1365
danielk1977ecb2a962004-06-02 06:30:16 +00001366 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001367 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001368 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001369 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001370 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001371 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001372 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001373
1374end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001375 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001376 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001377 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001378 return rc;
1379}
1380
1381/*
drh054889e2005-11-30 03:20:31 +00001382** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001383** must be either NO_LOCK or SHARED_LOCK.
1384**
1385** If the locking level of the file descriptor is already at or below
1386** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001387*/
danielk197762079062007-08-15 17:08:46 +00001388static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001389 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001390 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001391 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001392 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001393 int h;
drha6abd042004-06-09 17:37:22 +00001394
drh054889e2005-11-30 03:20:31 +00001395 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001396 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001397 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001398
1399 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001400 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001401 return SQLITE_OK;
1402 }
drhf1a221e2006-01-15 17:27:17 +00001403 if( CHECK_THREADID(pFile) ){
1404 return SQLITE_MISUSE;
1405 }
drh6c7d5c52008-11-21 20:32:33 +00001406 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001407 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001408 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001409 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001410 if( pFile->locktype>SHARED_LOCK ){
1411 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001412 SimulateIOErrorBenign(1);
1413 SimulateIOError( h=(-1) )
1414 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001415
1416#ifndef NDEBUG
1417 /* When reducing a lock such that other processes can start
1418 ** reading the database file again, make sure that the
1419 ** transaction counter was updated if any part of the database
1420 ** file changed. If the transaction counter is not updated,
1421 ** other connections to the same file might not realize that
1422 ** the file has changed and hence might not know to flush their
1423 ** cache. The use of a stale cache can lead to database corruption.
1424 */
1425 assert( pFile->inNormalWrite==0
1426 || pFile->dbUpdate==0
1427 || pFile->transCntrChng==1 );
1428 pFile->inNormalWrite = 0;
1429#endif
1430
1431
drh9c105bb2004-10-02 20:38:28 +00001432 if( locktype==SHARED_LOCK ){
1433 lock.l_type = F_RDLCK;
1434 lock.l_whence = SEEK_SET;
1435 lock.l_start = SHARED_FIRST;
1436 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001437 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001438 int tErrno = errno;
1439 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1440 if( IS_LOCK_ERROR(rc) ){
1441 pFile->lastErrno = tErrno;
1442 }
danielk197709480a92009-02-09 05:32:32 +00001443 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001444 }
1445 }
drhbbd42a62004-05-22 17:41:58 +00001446 lock.l_type = F_UNLCK;
1447 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001448 lock.l_start = PENDING_BYTE;
1449 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001450 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001451 pLock->locktype = SHARED_LOCK;
1452 }else{
aswift5b1a2562008-08-22 00:22:35 +00001453 int tErrno = errno;
1454 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1455 if( IS_LOCK_ERROR(rc) ){
1456 pFile->lastErrno = tErrno;
1457 }
drhcd731cf2009-03-28 23:23:02 +00001458 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001459 }
drhbbd42a62004-05-22 17:41:58 +00001460 }
drha6abd042004-06-09 17:37:22 +00001461 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001462 struct unixOpenCnt *pOpen;
danielk197764a54c52009-03-30 07:39:35 +00001463 int rc2 = SQLITE_OK;
danielk1977ecb2a962004-06-02 06:30:16 +00001464
drha6abd042004-06-09 17:37:22 +00001465 /* Decrement the shared lock counter. Release the lock using an
1466 ** OS call only when all threads in this same process have released
1467 ** the lock.
1468 */
1469 pLock->cnt--;
1470 if( pLock->cnt==0 ){
1471 lock.l_type = F_UNLCK;
1472 lock.l_whence = SEEK_SET;
1473 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001474 SimulateIOErrorBenign(1);
1475 SimulateIOError( h=(-1) )
1476 SimulateIOErrorBenign(0);
1477 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001478 pLock->locktype = NO_LOCK;
1479 }else{
aswift5b1a2562008-08-22 00:22:35 +00001480 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001481 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001482 if( IS_LOCK_ERROR(rc) ){
1483 pFile->lastErrno = tErrno;
1484 }
drhf48f9ca2009-03-28 23:47:10 +00001485 pLock->locktype = NO_LOCK;
1486 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001487 }
drha6abd042004-06-09 17:37:22 +00001488 }
1489
drhbbd42a62004-05-22 17:41:58 +00001490 /* Decrement the count of locks against this same file. When the
1491 ** count reaches zero, close any other file descriptors whose close
1492 ** was deferred because of outstanding locks.
1493 */
danielk197764a54c52009-03-30 07:39:35 +00001494 pOpen = pFile->pOpen;
1495 pOpen->nLock--;
1496 assert( pOpen->nLock>=0 );
1497 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1498 int i;
1499 for(i=0; i<pOpen->nPending; i++){
1500 /* close pending fds, but if closing fails don't free the array
1501 ** assign -1 to the successfully closed descriptors and record the
1502 ** error. The next attempt to unlock will try again. */
1503 if( pOpen->aPending[i] < 0 ) continue;
1504 if( close(pOpen->aPending[i]) ){
1505 pFile->lastErrno = errno;
1506 rc2 = SQLITE_IOERR_CLOSE;
1507 }else{
1508 pOpen->aPending[i] = -1;
aswiftaebf4132008-11-21 00:10:35 +00001509 }
drhbbd42a62004-05-22 17:41:58 +00001510 }
danielk197764a54c52009-03-30 07:39:35 +00001511 if( rc2==SQLITE_OK ){
1512 sqlite3_free(pOpen->aPending);
1513 pOpen->nPending = 0;
1514 pOpen->aPending = 0;
1515 }
1516 }
1517 if( rc==SQLITE_OK ){
1518 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001519 }
1520 }
aswift5b1a2562008-08-22 00:22:35 +00001521
1522end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001523 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001524 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001525 return rc;
drhbbd42a62004-05-22 17:41:58 +00001526}
1527
1528/*
danielk1977e339d652008-06-28 11:23:00 +00001529** This function performs the parts of the "close file" operation
1530** common to all locking schemes. It closes the directory and file
1531** handles, if they are valid, and sets all fields of the unixFile
1532** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001533**
1534** It is *not* necessary to hold the mutex when this routine is called,
1535** even on VxWorks. A mutex will be acquired on VxWorks by the
1536** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001537*/
1538static int closeUnixFile(sqlite3_file *id){
1539 unixFile *pFile = (unixFile*)id;
1540 if( pFile ){
1541 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001542 int err = close(pFile->dirfd);
1543 if( err ){
1544 pFile->lastErrno = errno;
1545 return SQLITE_IOERR_DIR_CLOSE;
1546 }else{
1547 pFile->dirfd=-1;
1548 }
danielk1977e339d652008-06-28 11:23:00 +00001549 }
1550 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001551 int err = close(pFile->h);
1552 if( err ){
1553 pFile->lastErrno = errno;
1554 return SQLITE_IOERR_CLOSE;
1555 }
danielk1977e339d652008-06-28 11:23:00 +00001556 }
drh6c7d5c52008-11-21 20:32:33 +00001557#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001558 if( pFile->pId ){
1559 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001560 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001561 }
drh107886a2008-11-21 22:21:50 +00001562 vxworksReleaseFileId(pFile->pId);
1563 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001564 }
1565#endif
danielk1977e339d652008-06-28 11:23:00 +00001566 OSTRACE2("CLOSE %-3d\n", pFile->h);
1567 OpenCounter(-1);
1568 memset(pFile, 0, sizeof(unixFile));
1569 }
1570 return SQLITE_OK;
1571}
1572
1573/*
danielk1977e3026632004-06-22 11:29:02 +00001574** Close a file.
1575*/
danielk197762079062007-08-15 17:08:46 +00001576static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001577 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001578 if( id ){
1579 unixFile *pFile = (unixFile *)id;
1580 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001581 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001582 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001583 /* If there are outstanding locks, do not actually close the file just
1584 ** yet because that would clear those locks. Instead, add the file
1585 ** descriptor to pOpen->aPending. It will be automatically closed when
1586 ** the last lock is cleared.
1587 */
1588 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001589 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001590 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001591 if( aNew==0 ){
1592 /* If a malloc fails, just leak the file descriptor */
1593 }else{
1594 pOpen->aPending = aNew;
1595 pOpen->aPending[pOpen->nPending] = pFile->h;
1596 pOpen->nPending++;
1597 pFile->h = -1;
1598 }
danielk1977e3026632004-06-22 11:29:02 +00001599 }
danielk1977e339d652008-06-28 11:23:00 +00001600 releaseLockInfo(pFile->pLock);
1601 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001602 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001603 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001604 }
aswiftaebf4132008-11-21 00:10:35 +00001605 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001606}
1607
drh734c9862008-11-28 15:37:20 +00001608/************** End of the posix advisory lock implementation *****************
1609******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001610
drh734c9862008-11-28 15:37:20 +00001611/******************************************************************************
1612****************************** No-op Locking **********************************
1613**
1614** Of the various locking implementations available, this is by far the
1615** simplest: locking is ignored. No attempt is made to lock the database
1616** file for reading or writing.
1617**
1618** This locking mode is appropriate for use on read-only databases
1619** (ex: databases that are burned into CD-ROM, for example.) It can
1620** also be used if the application employs some external mechanism to
1621** prevent simultaneous access of the same database by two or more
1622** database connections. But there is a serious risk of database
1623** corruption if this locking mode is used in situations where multiple
1624** database connections are accessing the same database file at the same
1625** time and one or more of those connections are writing.
1626*/
drhbfe66312006-10-03 17:40:40 +00001627
drh734c9862008-11-28 15:37:20 +00001628static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1629 UNUSED_PARAMETER(NotUsed);
1630 *pResOut = 0;
1631 return SQLITE_OK;
1632}
drh734c9862008-11-28 15:37:20 +00001633static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1634 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1635 return SQLITE_OK;
1636}
drh734c9862008-11-28 15:37:20 +00001637static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1638 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1639 return SQLITE_OK;
1640}
1641
1642/*
drh9b35ea62008-11-29 02:20:26 +00001643** Close the file.
drh734c9862008-11-28 15:37:20 +00001644*/
1645static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001646 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001647}
1648
1649/******************* End of the no-op lock implementation *********************
1650******************************************************************************/
1651
1652/******************************************************************************
1653************************* Begin dot-file Locking ******************************
1654**
1655** The dotfile locking implementation uses the existing of separate lock
1656** files in order to control access to the database. This works on just
1657** about every filesystem imaginable. But there are serious downsides:
1658**
1659** (1) There is zero concurrency. A single reader blocks all other
1660** connections from reading or writing the database.
1661**
1662** (2) An application crash or power loss can leave stale lock files
1663** sitting around that need to be cleared manually.
1664**
1665** Nevertheless, a dotlock is an appropriate locking mode for use if no
1666** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001667**
1668** Dotfile locking works by creating a file in the same directory as the
1669** database and with the same name but with a ".lock" extension added.
1670** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1671** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001672*/
1673
1674/*
1675** The file suffix added to the data base filename in order to create the
1676** lock file.
1677*/
1678#define DOTLOCK_SUFFIX ".lock"
1679
drh7708e972008-11-29 00:56:52 +00001680/*
1681** This routine checks if there is a RESERVED lock held on the specified
1682** file by this or any other process. If such a lock is held, set *pResOut
1683** to a non-zero value otherwise *pResOut is set to zero. The return value
1684** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1685**
1686** In dotfile locking, either a lock exists or it does not. So in this
1687** variation of CheckReservedLock(), *pResOut is set to true if any lock
1688** is held on the file and false if the file is unlocked.
1689*/
drh734c9862008-11-28 15:37:20 +00001690static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1691 int rc = SQLITE_OK;
1692 int reserved = 0;
1693 unixFile *pFile = (unixFile*)id;
1694
1695 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1696
1697 assert( pFile );
1698
1699 /* Check if a thread in this process holds such a lock */
1700 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001701 /* Either this connection or some other connection in the same process
1702 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001703 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001704 }else{
1705 /* The lock is held if and only if the lockfile exists */
1706 const char *zLockFile = (const char*)pFile->lockingContext;
1707 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001708 }
1709 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001710 *pResOut = reserved;
1711 return rc;
1712}
1713
drh7708e972008-11-29 00:56:52 +00001714/*
1715** Lock the file with the lock specified by parameter locktype - one
1716** of the following:
1717**
1718** (1) SHARED_LOCK
1719** (2) RESERVED_LOCK
1720** (3) PENDING_LOCK
1721** (4) EXCLUSIVE_LOCK
1722**
1723** Sometimes when requesting one lock state, additional lock states
1724** are inserted in between. The locking might fail on one of the later
1725** transitions leaving the lock state different from what it started but
1726** still short of its goal. The following chart shows the allowed
1727** transitions and the inserted intermediate states:
1728**
1729** UNLOCKED -> SHARED
1730** SHARED -> RESERVED
1731** SHARED -> (PENDING) -> EXCLUSIVE
1732** RESERVED -> (PENDING) -> EXCLUSIVE
1733** PENDING -> EXCLUSIVE
1734**
1735** This routine will only increase a lock. Use the sqlite3OsUnlock()
1736** routine to lower a locking level.
1737**
1738** With dotfile locking, we really only support state (4): EXCLUSIVE.
1739** But we track the other locking levels internally.
1740*/
drh734c9862008-11-28 15:37:20 +00001741static int dotlockLock(sqlite3_file *id, int locktype) {
1742 unixFile *pFile = (unixFile*)id;
1743 int fd;
1744 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001745 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001746
drh7708e972008-11-29 00:56:52 +00001747
1748 /* If we have any lock, then the lock file already exists. All we have
1749 ** to do is adjust our internal record of the lock level.
1750 */
1751 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001752 pFile->locktype = locktype;
1753#if !OS_VXWORKS
1754 /* Always update the timestamp on the old file */
1755 utimes(zLockFile, NULL);
1756#endif
drh7708e972008-11-29 00:56:52 +00001757 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001758 }
1759
1760 /* grab an exclusive lock */
1761 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1762 if( fd<0 ){
1763 /* failed to open/create the file, someone else may have stolen the lock */
1764 int tErrno = errno;
1765 if( EEXIST == tErrno ){
1766 rc = SQLITE_BUSY;
1767 } else {
1768 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1769 if( IS_LOCK_ERROR(rc) ){
1770 pFile->lastErrno = tErrno;
1771 }
1772 }
drh7708e972008-11-29 00:56:52 +00001773 return rc;
drh734c9862008-11-28 15:37:20 +00001774 }
1775 if( close(fd) ){
1776 pFile->lastErrno = errno;
1777 rc = SQLITE_IOERR_CLOSE;
1778 }
1779
1780 /* got it, set the type and return ok */
1781 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001782 return rc;
1783}
1784
drh7708e972008-11-29 00:56:52 +00001785/*
1786** Lower the locking level on file descriptor pFile to locktype. locktype
1787** must be either NO_LOCK or SHARED_LOCK.
1788**
1789** If the locking level of the file descriptor is already at or below
1790** the requested locking level, this routine is a no-op.
1791**
1792** When the locking level reaches NO_LOCK, delete the lock file.
1793*/
drh734c9862008-11-28 15:37:20 +00001794static int dotlockUnlock(sqlite3_file *id, int locktype) {
1795 unixFile *pFile = (unixFile*)id;
1796 char *zLockFile = (char *)pFile->lockingContext;
1797
1798 assert( pFile );
1799 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1800 pFile->locktype, getpid());
1801 assert( locktype<=SHARED_LOCK );
1802
1803 /* no-op if possible */
1804 if( pFile->locktype==locktype ){
1805 return SQLITE_OK;
1806 }
drh7708e972008-11-29 00:56:52 +00001807
1808 /* To downgrade to shared, simply update our internal notion of the
1809 ** lock state. No need to mess with the file on disk.
1810 */
1811 if( locktype==SHARED_LOCK ){
1812 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001813 return SQLITE_OK;
1814 }
1815
drh7708e972008-11-29 00:56:52 +00001816 /* To fully unlock the database, delete the lock file */
1817 assert( locktype==NO_LOCK );
1818 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001819 int rc = 0;
1820 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001821 if( ENOENT != tErrno ){
1822 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1823 }
1824 if( IS_LOCK_ERROR(rc) ){
1825 pFile->lastErrno = tErrno;
1826 }
1827 return rc;
1828 }
1829 pFile->locktype = NO_LOCK;
1830 return SQLITE_OK;
1831}
1832
1833/*
drh9b35ea62008-11-29 02:20:26 +00001834** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001835*/
1836static int dotlockClose(sqlite3_file *id) {
1837 int rc;
1838 if( id ){
1839 unixFile *pFile = (unixFile*)id;
1840 dotlockUnlock(id, NO_LOCK);
1841 sqlite3_free(pFile->lockingContext);
1842 }
drh734c9862008-11-28 15:37:20 +00001843 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001844 return rc;
1845}
1846/****************** End of the dot-file lock implementation *******************
1847******************************************************************************/
1848
1849/******************************************************************************
1850************************** Begin flock Locking ********************************
1851**
1852** Use the flock() system call to do file locking.
1853**
drh6b9d6dd2008-12-03 19:34:47 +00001854** flock() locking is like dot-file locking in that the various
1855** fine-grain locking levels supported by SQLite are collapsed into
1856** a single exclusive lock. In other words, SHARED, RESERVED, and
1857** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1858** still works when you do this, but concurrency is reduced since
1859** only a single process can be reading the database at a time.
1860**
drh734c9862008-11-28 15:37:20 +00001861** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1862** compiling for VXWORKS.
1863*/
1864#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001865
drh6b9d6dd2008-12-03 19:34:47 +00001866/*
1867** This routine checks if there is a RESERVED lock held on the specified
1868** file by this or any other process. If such a lock is held, set *pResOut
1869** to a non-zero value otherwise *pResOut is set to zero. The return value
1870** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1871*/
drh734c9862008-11-28 15:37:20 +00001872static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1873 int rc = SQLITE_OK;
1874 int reserved = 0;
1875 unixFile *pFile = (unixFile*)id;
1876
1877 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1878
1879 assert( pFile );
1880
1881 /* Check if a thread in this process holds such a lock */
1882 if( pFile->locktype>SHARED_LOCK ){
1883 reserved = 1;
1884 }
1885
1886 /* Otherwise see if some other process holds it. */
1887 if( !reserved ){
1888 /* attempt to get the lock */
1889 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1890 if( !lrc ){
1891 /* got the lock, unlock it */
1892 lrc = flock(pFile->h, LOCK_UN);
1893 if ( lrc ) {
1894 int tErrno = errno;
1895 /* unlock failed with an error */
1896 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1897 if( IS_LOCK_ERROR(lrc) ){
1898 pFile->lastErrno = tErrno;
1899 rc = lrc;
1900 }
1901 }
1902 } else {
1903 int tErrno = errno;
1904 reserved = 1;
1905 /* someone else might have it reserved */
1906 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1907 if( IS_LOCK_ERROR(lrc) ){
1908 pFile->lastErrno = tErrno;
1909 rc = lrc;
1910 }
1911 }
1912 }
1913 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1914
1915#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1916 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1917 rc = SQLITE_OK;
1918 reserved=1;
1919 }
1920#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1921 *pResOut = reserved;
1922 return rc;
1923}
1924
drh6b9d6dd2008-12-03 19:34:47 +00001925/*
1926** Lock the file with the lock specified by parameter locktype - one
1927** of the following:
1928**
1929** (1) SHARED_LOCK
1930** (2) RESERVED_LOCK
1931** (3) PENDING_LOCK
1932** (4) EXCLUSIVE_LOCK
1933**
1934** Sometimes when requesting one lock state, additional lock states
1935** are inserted in between. The locking might fail on one of the later
1936** transitions leaving the lock state different from what it started but
1937** still short of its goal. The following chart shows the allowed
1938** transitions and the inserted intermediate states:
1939**
1940** UNLOCKED -> SHARED
1941** SHARED -> RESERVED
1942** SHARED -> (PENDING) -> EXCLUSIVE
1943** RESERVED -> (PENDING) -> EXCLUSIVE
1944** PENDING -> EXCLUSIVE
1945**
1946** flock() only really support EXCLUSIVE locks. We track intermediate
1947** lock states in the sqlite3_file structure, but all locks SHARED or
1948** above are really EXCLUSIVE locks and exclude all other processes from
1949** access the file.
1950**
1951** This routine will only increase a lock. Use the sqlite3OsUnlock()
1952** routine to lower a locking level.
1953*/
drh734c9862008-11-28 15:37:20 +00001954static int flockLock(sqlite3_file *id, int locktype) {
1955 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001956 unixFile *pFile = (unixFile*)id;
1957
1958 assert( pFile );
1959
1960 /* if we already have a lock, it is exclusive.
1961 ** Just adjust level and punt on outta here. */
1962 if (pFile->locktype > NO_LOCK) {
1963 pFile->locktype = locktype;
1964 return SQLITE_OK;
1965 }
1966
1967 /* grab an exclusive lock */
1968
1969 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1970 int tErrno = errno;
1971 /* didn't get, must be busy */
1972 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1973 if( IS_LOCK_ERROR(rc) ){
1974 pFile->lastErrno = tErrno;
1975 }
1976 } else {
1977 /* got it, set the type and return ok */
1978 pFile->locktype = locktype;
1979 }
1980 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1981 rc==SQLITE_OK ? "ok" : "failed");
1982#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1983 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1984 rc = SQLITE_BUSY;
1985 }
1986#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1987 return rc;
1988}
1989
drh6b9d6dd2008-12-03 19:34:47 +00001990
1991/*
1992** Lower the locking level on file descriptor pFile to locktype. locktype
1993** must be either NO_LOCK or SHARED_LOCK.
1994**
1995** If the locking level of the file descriptor is already at or below
1996** the requested locking level, this routine is a no-op.
1997*/
drh734c9862008-11-28 15:37:20 +00001998static int flockUnlock(sqlite3_file *id, int locktype) {
1999 unixFile *pFile = (unixFile*)id;
2000
2001 assert( pFile );
2002 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2003 pFile->locktype, getpid());
2004 assert( locktype<=SHARED_LOCK );
2005
2006 /* no-op if possible */
2007 if( pFile->locktype==locktype ){
2008 return SQLITE_OK;
2009 }
2010
2011 /* shared can just be set because we always have an exclusive */
2012 if (locktype==SHARED_LOCK) {
2013 pFile->locktype = locktype;
2014 return SQLITE_OK;
2015 }
2016
2017 /* no, really, unlock. */
2018 int rc = flock(pFile->h, LOCK_UN);
2019 if (rc) {
2020 int r, tErrno = errno;
2021 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2022 if( IS_LOCK_ERROR(r) ){
2023 pFile->lastErrno = tErrno;
2024 }
2025#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2026 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2027 r = SQLITE_BUSY;
2028 }
2029#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2030
2031 return r;
2032 } else {
2033 pFile->locktype = NO_LOCK;
2034 return SQLITE_OK;
2035 }
2036}
2037
2038/*
2039** Close a file.
2040*/
2041static int flockClose(sqlite3_file *id) {
2042 if( id ){
2043 flockUnlock(id, NO_LOCK);
2044 }
2045 return closeUnixFile(id);
2046}
2047
2048#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2049
2050/******************* End of the flock lock implementation *********************
2051******************************************************************************/
2052
2053/******************************************************************************
2054************************ Begin Named Semaphore Locking ************************
2055**
2056** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002057**
2058** Semaphore locking is like dot-lock and flock in that it really only
2059** supports EXCLUSIVE locking. Only a single process can read or write
2060** the database file at a time. This reduces potential concurrency, but
2061** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002062*/
2063#if OS_VXWORKS
2064
drh6b9d6dd2008-12-03 19:34:47 +00002065/*
2066** This routine checks if there is a RESERVED lock held on the specified
2067** file by this or any other process. If such a lock is held, set *pResOut
2068** to a non-zero value otherwise *pResOut is set to zero. The return value
2069** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2070*/
drh734c9862008-11-28 15:37:20 +00002071static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2072 int rc = SQLITE_OK;
2073 int reserved = 0;
2074 unixFile *pFile = (unixFile*)id;
2075
2076 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2077
2078 assert( pFile );
2079
2080 /* Check if a thread in this process holds such a lock */
2081 if( pFile->locktype>SHARED_LOCK ){
2082 reserved = 1;
2083 }
2084
2085 /* Otherwise see if some other process holds it. */
2086 if( !reserved ){
2087 sem_t *pSem = pFile->pOpen->pSem;
2088 struct stat statBuf;
2089
2090 if( sem_trywait(pSem)==-1 ){
2091 int tErrno = errno;
2092 if( EAGAIN != tErrno ){
2093 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2094 pFile->lastErrno = tErrno;
2095 } else {
2096 /* someone else has the lock when we are in NO_LOCK */
2097 reserved = (pFile->locktype < SHARED_LOCK);
2098 }
2099 }else{
2100 /* we could have it if we want it */
2101 sem_post(pSem);
2102 }
2103 }
2104 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2105
2106 *pResOut = reserved;
2107 return rc;
2108}
2109
drh6b9d6dd2008-12-03 19:34:47 +00002110/*
2111** Lock the file with the lock specified by parameter locktype - one
2112** of the following:
2113**
2114** (1) SHARED_LOCK
2115** (2) RESERVED_LOCK
2116** (3) PENDING_LOCK
2117** (4) EXCLUSIVE_LOCK
2118**
2119** Sometimes when requesting one lock state, additional lock states
2120** are inserted in between. The locking might fail on one of the later
2121** transitions leaving the lock state different from what it started but
2122** still short of its goal. The following chart shows the allowed
2123** transitions and the inserted intermediate states:
2124**
2125** UNLOCKED -> SHARED
2126** SHARED -> RESERVED
2127** SHARED -> (PENDING) -> EXCLUSIVE
2128** RESERVED -> (PENDING) -> EXCLUSIVE
2129** PENDING -> EXCLUSIVE
2130**
2131** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2132** lock states in the sqlite3_file structure, but all locks SHARED or
2133** above are really EXCLUSIVE locks and exclude all other processes from
2134** access the file.
2135**
2136** This routine will only increase a lock. Use the sqlite3OsUnlock()
2137** routine to lower a locking level.
2138*/
drh734c9862008-11-28 15:37:20 +00002139static int semLock(sqlite3_file *id, int locktype) {
2140 unixFile *pFile = (unixFile*)id;
2141 int fd;
2142 sem_t *pSem = pFile->pOpen->pSem;
2143 int rc = SQLITE_OK;
2144
2145 /* if we already have a lock, it is exclusive.
2146 ** Just adjust level and punt on outta here. */
2147 if (pFile->locktype > NO_LOCK) {
2148 pFile->locktype = locktype;
2149 rc = SQLITE_OK;
2150 goto sem_end_lock;
2151 }
2152
2153 /* lock semaphore now but bail out when already locked. */
2154 if( sem_trywait(pSem)==-1 ){
2155 rc = SQLITE_BUSY;
2156 goto sem_end_lock;
2157 }
2158
2159 /* got it, set the type and return ok */
2160 pFile->locktype = locktype;
2161
2162 sem_end_lock:
2163 return rc;
2164}
2165
drh6b9d6dd2008-12-03 19:34:47 +00002166/*
2167** Lower the locking level on file descriptor pFile to locktype. locktype
2168** must be either NO_LOCK or SHARED_LOCK.
2169**
2170** If the locking level of the file descriptor is already at or below
2171** the requested locking level, this routine is a no-op.
2172*/
drh734c9862008-11-28 15:37:20 +00002173static int semUnlock(sqlite3_file *id, int locktype) {
2174 unixFile *pFile = (unixFile*)id;
2175 sem_t *pSem = pFile->pOpen->pSem;
2176
2177 assert( pFile );
2178 assert( pSem );
2179 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2180 pFile->locktype, getpid());
2181 assert( locktype<=SHARED_LOCK );
2182
2183 /* no-op if possible */
2184 if( pFile->locktype==locktype ){
2185 return SQLITE_OK;
2186 }
2187
2188 /* shared can just be set because we always have an exclusive */
2189 if (locktype==SHARED_LOCK) {
2190 pFile->locktype = locktype;
2191 return SQLITE_OK;
2192 }
2193
2194 /* no, really unlock. */
2195 if ( sem_post(pSem)==-1 ) {
2196 int rc, tErrno = errno;
2197 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2198 if( IS_LOCK_ERROR(rc) ){
2199 pFile->lastErrno = tErrno;
2200 }
2201 return rc;
2202 }
2203 pFile->locktype = NO_LOCK;
2204 return SQLITE_OK;
2205}
2206
2207/*
2208 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002209 */
drh734c9862008-11-28 15:37:20 +00002210static int semClose(sqlite3_file *id) {
2211 if( id ){
2212 unixFile *pFile = (unixFile*)id;
2213 semUnlock(id, NO_LOCK);
2214 assert( pFile );
2215 unixEnterMutex();
2216 releaseLockInfo(pFile->pLock);
2217 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002218 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002219 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002220 }
2221 return SQLITE_OK;
2222}
2223
2224#endif /* OS_VXWORKS */
2225/*
2226** Named semaphore locking is only available on VxWorks.
2227**
2228*************** End of the named semaphore lock implementation ****************
2229******************************************************************************/
2230
2231
2232/******************************************************************************
2233*************************** Begin AFP Locking *********************************
2234**
2235** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2236** on Apple Macintosh computers - both OS9 and OSX.
2237**
2238** Third-party implementations of AFP are available. But this code here
2239** only works on OSX.
2240*/
2241
drhd2cb50b2009-01-09 21:41:17 +00002242#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002243/*
2244** The afpLockingContext structure contains all afp lock specific state
2245*/
drhbfe66312006-10-03 17:40:40 +00002246typedef struct afpLockingContext afpLockingContext;
2247struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002248 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002249 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002250};
2251
2252struct ByteRangeLockPB2
2253{
2254 unsigned long long offset; /* offset to first byte to lock */
2255 unsigned long long length; /* nbr of bytes to lock */
2256 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2257 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2258 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2259 int fd; /* file desc to assoc this lock with */
2260};
2261
drhfd131da2007-08-07 17:13:03 +00002262#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002263
drh6b9d6dd2008-12-03 19:34:47 +00002264/*
2265** This is a utility for setting or clearing a bit-range lock on an
2266** AFP filesystem.
2267**
2268** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2269*/
2270static int afpSetLock(
2271 const char *path, /* Name of the file to be locked or unlocked */
2272 unixFile *pFile, /* Open file descriptor on path */
2273 unsigned long long offset, /* First byte to be locked */
2274 unsigned long long length, /* Number of bytes to lock */
2275 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002276){
drh6b9d6dd2008-12-03 19:34:47 +00002277 struct ByteRangeLockPB2 pb;
2278 int err;
drhbfe66312006-10-03 17:40:40 +00002279
2280 pb.unLockFlag = setLockFlag ? 0 : 1;
2281 pb.startEndFlag = 0;
2282 pb.offset = offset;
2283 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002284 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002285
2286 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002287 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2288 offset, length);
drhbfe66312006-10-03 17:40:40 +00002289 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2290 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002291 int rc;
2292 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002293 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2294 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002295#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2296 rc = SQLITE_BUSY;
2297#else
drh734c9862008-11-28 15:37:20 +00002298 rc = sqliteErrorFromPosixError(tErrno,
2299 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002300#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002301 if( IS_LOCK_ERROR(rc) ){
2302 pFile->lastErrno = tErrno;
2303 }
2304 return rc;
drhbfe66312006-10-03 17:40:40 +00002305 } else {
aswift5b1a2562008-08-22 00:22:35 +00002306 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002307 }
2308}
2309
drh6b9d6dd2008-12-03 19:34:47 +00002310/*
2311** This routine checks if there is a RESERVED lock held on the specified
2312** file by this or any other process. If such a lock is held, set *pResOut
2313** to a non-zero value otherwise *pResOut is set to zero. The return value
2314** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2315*/
danielk1977e339d652008-06-28 11:23:00 +00002316static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002317 int rc = SQLITE_OK;
2318 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002319 unixFile *pFile = (unixFile*)id;
2320
aswift5b1a2562008-08-22 00:22:35 +00002321 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2322
2323 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002324 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2325
2326 /* Check if a thread in this process holds such a lock */
2327 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002328 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002329 }
2330
2331 /* Otherwise see if some other process holds it.
2332 */
aswift5b1a2562008-08-22 00:22:35 +00002333 if( !reserved ){
2334 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002335 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002336 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002337 /* if we succeeded in taking the reserved lock, unlock it to restore
2338 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002339 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002340 } else {
2341 /* if we failed to get the lock then someone else must have it */
2342 reserved = 1;
2343 }
2344 if( IS_LOCK_ERROR(lrc) ){
2345 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002346 }
2347 }
drhbfe66312006-10-03 17:40:40 +00002348
aswift5b1a2562008-08-22 00:22:35 +00002349 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2350
2351 *pResOut = reserved;
2352 return rc;
drhbfe66312006-10-03 17:40:40 +00002353}
2354
drh6b9d6dd2008-12-03 19:34:47 +00002355/*
2356** Lock the file with the lock specified by parameter locktype - one
2357** of the following:
2358**
2359** (1) SHARED_LOCK
2360** (2) RESERVED_LOCK
2361** (3) PENDING_LOCK
2362** (4) EXCLUSIVE_LOCK
2363**
2364** Sometimes when requesting one lock state, additional lock states
2365** are inserted in between. The locking might fail on one of the later
2366** transitions leaving the lock state different from what it started but
2367** still short of its goal. The following chart shows the allowed
2368** transitions and the inserted intermediate states:
2369**
2370** UNLOCKED -> SHARED
2371** SHARED -> RESERVED
2372** SHARED -> (PENDING) -> EXCLUSIVE
2373** RESERVED -> (PENDING) -> EXCLUSIVE
2374** PENDING -> EXCLUSIVE
2375**
2376** This routine will only increase a lock. Use the sqlite3OsUnlock()
2377** routine to lower a locking level.
2378*/
danielk1977e339d652008-06-28 11:23:00 +00002379static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002380 int rc = SQLITE_OK;
2381 unixFile *pFile = (unixFile*)id;
2382 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002383
2384 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002385 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002386 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2387
drhbfe66312006-10-03 17:40:40 +00002388 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002389 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002390 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002391 */
drhbfe66312006-10-03 17:40:40 +00002392 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002393 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002394 locktypeName(locktype));
2395 return SQLITE_OK;
2396 }
2397
2398 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002399 */
drhbfe66312006-10-03 17:40:40 +00002400 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2401 assert( locktype!=PENDING_LOCK );
2402 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2403
2404 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002405 */
drh6c7d5c52008-11-21 20:32:33 +00002406 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002407
2408 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002409 */
drhbfe66312006-10-03 17:40:40 +00002410 rc = transferOwnership(pFile);
2411 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002412 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002413 return rc;
2414 }
2415
2416 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002417 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2418 ** be released.
2419 */
drhbfe66312006-10-03 17:40:40 +00002420 if( locktype==SHARED_LOCK
2421 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002422 ){
2423 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002424 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002425 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002426 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002427 goto afp_end_lock;
2428 }
2429 }
2430
2431 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002432 ** operating system calls for the specified lock.
2433 */
drhbfe66312006-10-03 17:40:40 +00002434 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002435 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002436
aswift5b1a2562008-08-22 00:22:35 +00002437 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002438 /* note that the quality of the randomness doesn't matter that much */
2439 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002440 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002441 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002442 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002443 if( IS_LOCK_ERROR(lrc1) ){
2444 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002445 }
aswift5b1a2562008-08-22 00:22:35 +00002446 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002447 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002448
aswift5b1a2562008-08-22 00:22:35 +00002449 if( IS_LOCK_ERROR(lrc1) ) {
2450 pFile->lastErrno = lrc1Errno;
2451 rc = lrc1;
2452 goto afp_end_lock;
2453 } else if( IS_LOCK_ERROR(lrc2) ){
2454 rc = lrc2;
2455 goto afp_end_lock;
2456 } else if( lrc1 != SQLITE_OK ) {
2457 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002458 } else {
2459 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002460 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002461 }
2462 }else{
2463 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2464 ** assumed that there is a SHARED or greater lock on the file
2465 ** already.
2466 */
2467 int failed = 0;
2468 assert( 0!=pFile->locktype );
2469 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2470 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002471 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002472 }
2473 if (!failed && locktype == EXCLUSIVE_LOCK) {
2474 /* Acquire an EXCLUSIVE lock */
2475
2476 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002477 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002478 */
drh6b9d6dd2008-12-03 19:34:47 +00002479 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002480 context->sharedByte, 1, 0)) ){
2481 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002482 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002483 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002484 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002485 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002486 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2487 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2488 ** a critical I/O error
2489 */
2490 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2491 SQLITE_IOERR_LOCK;
2492 goto afp_end_lock;
2493 }
2494 }else{
aswift5b1a2562008-08-22 00:22:35 +00002495 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002496 }
2497 }
aswift5b1a2562008-08-22 00:22:35 +00002498 if( failed ){
2499 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002500 }
2501 }
2502
2503 if( rc==SQLITE_OK ){
2504 pFile->locktype = locktype;
2505 }else if( locktype==EXCLUSIVE_LOCK ){
2506 pFile->locktype = PENDING_LOCK;
2507 }
2508
2509afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002510 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002511 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002512 rc==SQLITE_OK ? "ok" : "failed");
2513 return rc;
2514}
2515
2516/*
drh339eb0b2008-03-07 15:34:11 +00002517** Lower the locking level on file descriptor pFile to locktype. locktype
2518** must be either NO_LOCK or SHARED_LOCK.
2519**
2520** If the locking level of the file descriptor is already at or below
2521** the requested locking level, this routine is a no-op.
2522*/
danielk1977e339d652008-06-28 11:23:00 +00002523static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002524 int rc = SQLITE_OK;
2525 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002526 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002527
2528 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002529 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002530 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002531
drhbfe66312006-10-03 17:40:40 +00002532 assert( locktype<=SHARED_LOCK );
2533 if( pFile->locktype<=locktype ){
2534 return SQLITE_OK;
2535 }
2536 if( CHECK_THREADID(pFile) ){
2537 return SQLITE_MISUSE;
2538 }
drh6c7d5c52008-11-21 20:32:33 +00002539 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002540 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002541
2542 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002543 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002544 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2545 /* only re-establish the shared lock if necessary */
2546 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002547 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002548 }
2549 }
2550 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002551 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002552 }
2553 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002554 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002555 }
2556 }else if( locktype==NO_LOCK ){
2557 /* clear the shared lock */
2558 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002559 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002560 }
drhbfe66312006-10-03 17:40:40 +00002561
aswiftaebf4132008-11-21 00:10:35 +00002562 if( rc==SQLITE_OK ){
2563 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002564 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002565 pOpen->nLock--;
2566 assert( pOpen->nLock>=0 );
2567 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2568 int i;
2569 for(i=0; i<pOpen->nPending; i++){
2570 if( pOpen->aPending[i] < 0 ) continue;
2571 if( close(pOpen->aPending[i]) ){
2572 pFile->lastErrno = errno;
2573 rc = SQLITE_IOERR_CLOSE;
2574 }else{
2575 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002576 }
aswiftaebf4132008-11-21 00:10:35 +00002577 }
2578 if( rc==SQLITE_OK ){
2579 sqlite3_free(pOpen->aPending);
2580 pOpen->nPending = 0;
2581 pOpen->aPending = 0;
2582 }
drhbfe66312006-10-03 17:40:40 +00002583 }
2584 }
drhbfe66312006-10-03 17:40:40 +00002585 }
drh6c7d5c52008-11-21 20:32:33 +00002586 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002587 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002588 return rc;
2589}
2590
2591/*
drh339eb0b2008-03-07 15:34:11 +00002592** Close a file & cleanup AFP specific locking context
2593*/
danielk1977e339d652008-06-28 11:23:00 +00002594static int afpClose(sqlite3_file *id) {
2595 if( id ){
2596 unixFile *pFile = (unixFile*)id;
2597 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002598 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002599 if( pFile->pOpen && pFile->pOpen->nLock ){
2600 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002601 ** yet because that would clear those locks. Instead, add the file
2602 ** descriptor to pOpen->aPending. It will be automatically closed when
2603 ** the last lock is cleared.
2604 */
aswiftaebf4132008-11-21 00:10:35 +00002605 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002606 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002607 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2608 if( aNew==0 ){
2609 /* If a malloc fails, just leak the file descriptor */
2610 }else{
2611 pOpen->aPending = aNew;
2612 pOpen->aPending[pOpen->nPending] = pFile->h;
2613 pOpen->nPending++;
2614 pFile->h = -1;
2615 }
2616 }
2617 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002618 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002619 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002620 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002621 }
aswiftaebf4132008-11-21 00:10:35 +00002622 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002623}
2624
drhd2cb50b2009-01-09 21:41:17 +00002625#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002626/*
2627** The code above is the AFP lock implementation. The code is specific
2628** to MacOSX and does not work on other unix platforms. No alternative
2629** is available. If you don't compile for a mac, then the "unix-afp"
2630** VFS is not available.
2631**
2632********************* End of the AFP lock implementation **********************
2633******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002634
drh734c9862008-11-28 15:37:20 +00002635
2636/******************************************************************************
2637**************** Non-locking sqlite3_file methods *****************************
2638**
2639** The next division contains implementations for all methods of the
2640** sqlite3_file object other than the locking methods. The locking
2641** methods were defined in divisions above (one locking method per
2642** division). Those methods that are common to all locking modes
2643** are gather together into this division.
2644*/
drhbfe66312006-10-03 17:40:40 +00002645
2646/*
drh734c9862008-11-28 15:37:20 +00002647** Seek to the offset passed as the second argument, then read cnt
2648** bytes into pBuf. Return the number of bytes actually read.
2649**
2650** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2651** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2652** one system to another. Since SQLite does not define USE_PREAD
2653** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2654** See tickets #2741 and #2681.
2655**
2656** To avoid stomping the errno value on a failed read the lastErrno value
2657** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002658*/
drh734c9862008-11-28 15:37:20 +00002659static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2660 int got;
2661 i64 newOffset;
2662 TIMER_START;
2663#if defined(USE_PREAD)
2664 got = pread(id->h, pBuf, cnt, offset);
2665 SimulateIOError( got = -1 );
2666#elif defined(USE_PREAD64)
2667 got = pread64(id->h, pBuf, cnt, offset);
2668 SimulateIOError( got = -1 );
2669#else
2670 newOffset = lseek(id->h, offset, SEEK_SET);
2671 SimulateIOError( newOffset-- );
2672 if( newOffset!=offset ){
2673 if( newOffset == -1 ){
2674 ((unixFile*)id)->lastErrno = errno;
2675 }else{
2676 ((unixFile*)id)->lastErrno = 0;
2677 }
2678 return -1;
2679 }
2680 got = read(id->h, pBuf, cnt);
2681#endif
2682 TIMER_END;
2683 if( got<0 ){
2684 ((unixFile*)id)->lastErrno = errno;
2685 }
2686 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2687 return got;
drhbfe66312006-10-03 17:40:40 +00002688}
2689
2690/*
drh734c9862008-11-28 15:37:20 +00002691** Read data from a file into a buffer. Return SQLITE_OK if all
2692** bytes were read successfully and SQLITE_IOERR if anything goes
2693** wrong.
drh339eb0b2008-03-07 15:34:11 +00002694*/
drh734c9862008-11-28 15:37:20 +00002695static int unixRead(
2696 sqlite3_file *id,
2697 void *pBuf,
2698 int amt,
2699 sqlite3_int64 offset
2700){
2701 int got;
2702 assert( id );
drh08c6d442009-02-09 17:34:07 +00002703
2704 /* Never read or write any of the bytes in the locking range */
2705 assert( ((unixFile*)id)->isLockable==0
2706 || offset>=PENDING_BYTE+512
2707 || offset+amt<=PENDING_BYTE );
2708
drh734c9862008-11-28 15:37:20 +00002709 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
2710 if( got==amt ){
2711 return SQLITE_OK;
2712 }else if( got<0 ){
2713 /* lastErrno set by seekAndRead */
2714 return SQLITE_IOERR_READ;
2715 }else{
2716 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2717 /* Unread parts of the buffer must be zero-filled */
2718 memset(&((char*)pBuf)[got], 0, amt-got);
2719 return SQLITE_IOERR_SHORT_READ;
2720 }
2721}
2722
2723/*
2724** Seek to the offset in id->offset then read cnt bytes into pBuf.
2725** Return the number of bytes actually read. Update the offset.
2726**
2727** To avoid stomping the errno value on a failed write the lastErrno value
2728** is set before returning.
2729*/
2730static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2731 int got;
2732 i64 newOffset;
2733 TIMER_START;
2734#if defined(USE_PREAD)
2735 got = pwrite(id->h, pBuf, cnt, offset);
2736#elif defined(USE_PREAD64)
2737 got = pwrite64(id->h, pBuf, cnt, offset);
2738#else
2739 newOffset = lseek(id->h, offset, SEEK_SET);
2740 if( newOffset!=offset ){
2741 if( newOffset == -1 ){
2742 ((unixFile*)id)->lastErrno = errno;
2743 }else{
2744 ((unixFile*)id)->lastErrno = 0;
2745 }
2746 return -1;
2747 }
2748 got = write(id->h, pBuf, cnt);
2749#endif
2750 TIMER_END;
2751 if( got<0 ){
2752 ((unixFile*)id)->lastErrno = errno;
2753 }
2754
2755 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2756 return got;
2757}
2758
2759
2760/*
2761** Write data from a buffer into a file. Return SQLITE_OK on success
2762** or some other error code on failure.
2763*/
2764static int unixWrite(
2765 sqlite3_file *id,
2766 const void *pBuf,
2767 int amt,
2768 sqlite3_int64 offset
2769){
2770 int wrote = 0;
2771 assert( id );
2772 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002773
drh08c6d442009-02-09 17:34:07 +00002774 /* Never read or write any of the bytes in the locking range */
2775 assert( ((unixFile*)id)->isLockable==0
2776 || offset>=PENDING_BYTE+512
2777 || offset+amt<=PENDING_BYTE );
2778
drh8f941bc2009-01-14 23:03:40 +00002779#ifndef NDEBUG
2780 /* If we are doing a normal write to a database file (as opposed to
2781 ** doing a hot-journal rollback or a write to some file other than a
2782 ** normal database file) then record the fact that the database
2783 ** has changed. If the transaction counter is modified, record that
2784 ** fact too.
2785 */
2786 if( ((unixFile*)id)->inNormalWrite ){
2787 unixFile *pFile = (unixFile*)id;
2788 pFile->dbUpdate = 1; /* The database has been modified */
2789 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002790 int rc;
drh8f941bc2009-01-14 23:03:40 +00002791 char oldCntr[4];
2792 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002793 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002794 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002795 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002796 pFile->transCntrChng = 1; /* The transaction counter has changed */
2797 }
2798 }
2799 }
2800#endif
2801
drh734c9862008-11-28 15:37:20 +00002802 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2803 amt -= wrote;
2804 offset += wrote;
2805 pBuf = &((char*)pBuf)[wrote];
2806 }
2807 SimulateIOError(( wrote=(-1), amt=1 ));
2808 SimulateDiskfullError(( wrote=0, amt=1 ));
2809 if( amt>0 ){
2810 if( wrote<0 ){
2811 /* lastErrno set by seekAndWrite */
2812 return SQLITE_IOERR_WRITE;
2813 }else{
2814 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2815 return SQLITE_FULL;
2816 }
2817 }
2818 return SQLITE_OK;
2819}
2820
2821#ifdef SQLITE_TEST
2822/*
2823** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002824** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002825*/
2826int sqlite3_sync_count = 0;
2827int sqlite3_fullsync_count = 0;
2828#endif
2829
2830/*
drh89240432009-03-25 01:06:01 +00002831** We do not trust systems to provide a working fdatasync(). Some do.
2832** Others do no. To be safe, we will stick with the (slower) fsync().
2833** If you know that your system does support fdatasync() correctly,
2834** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002835*/
drh89240432009-03-25 01:06:01 +00002836#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002837# define fdatasync fsync
2838#endif
2839
2840/*
2841** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2842** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2843** only available on Mac OS X. But that could change.
2844*/
2845#ifdef F_FULLFSYNC
2846# define HAVE_FULLFSYNC 1
2847#else
2848# define HAVE_FULLFSYNC 0
2849#endif
2850
2851
2852/*
2853** The fsync() system call does not work as advertised on many
2854** unix systems. The following procedure is an attempt to make
2855** it work better.
2856**
2857** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2858** for testing when we want to run through the test suite quickly.
2859** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2860** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2861** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002862**
2863** SQLite sets the dataOnly flag if the size of the file is unchanged.
2864** The idea behind dataOnly is that it should only write the file content
2865** to disk, not the inode. We only set dataOnly if the file size is
2866** unchanged since the file size is part of the inode. However,
2867** Ted Ts'o tells us that fdatasync() will also write the inode if the
2868** file size has changed. The only real difference between fdatasync()
2869** and fsync(), Ted tells us, is that fdatasync() will not flush the
2870** inode if the mtime or owner or other inode attributes have changed.
2871** We only care about the file size, not the other file attributes, so
2872** as far as SQLite is concerned, an fdatasync() is always adequate.
2873** So, we always use fdatasync() if it is available, regardless of
2874** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002875*/
2876static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002877 int rc;
drh734c9862008-11-28 15:37:20 +00002878
2879 /* The following "ifdef/elif/else/" block has the same structure as
2880 ** the one below. It is replicated here solely to avoid cluttering
2881 ** up the real code with the UNUSED_PARAMETER() macros.
2882 */
2883#ifdef SQLITE_NO_SYNC
2884 UNUSED_PARAMETER(fd);
2885 UNUSED_PARAMETER(fullSync);
2886 UNUSED_PARAMETER(dataOnly);
2887#elif HAVE_FULLFSYNC
2888 UNUSED_PARAMETER(dataOnly);
2889#else
2890 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002891 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002892#endif
2893
2894 /* Record the number of times that we do a normal fsync() and
2895 ** FULLSYNC. This is used during testing to verify that this procedure
2896 ** gets called with the correct arguments.
2897 */
2898#ifdef SQLITE_TEST
2899 if( fullSync ) sqlite3_fullsync_count++;
2900 sqlite3_sync_count++;
2901#endif
2902
2903 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2904 ** no-op
2905 */
2906#ifdef SQLITE_NO_SYNC
2907 rc = SQLITE_OK;
2908#elif HAVE_FULLFSYNC
2909 if( fullSync ){
2910 rc = fcntl(fd, F_FULLFSYNC, 0);
2911 }else{
2912 rc = 1;
2913 }
2914 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002915 ** It shouldn't be possible for fullfsync to fail on the local
2916 ** file system (on OSX), so failure indicates that FULLFSYNC
2917 ** isn't supported for this file system. So, attempt an fsync
2918 ** and (for now) ignore the overhead of a superfluous fcntl call.
2919 ** It'd be better to detect fullfsync support once and avoid
2920 ** the fcntl call every time sync is called.
2921 */
drh734c9862008-11-28 15:37:20 +00002922 if( rc ) rc = fsync(fd);
2923
2924#else
drh0b647ff2009-03-21 14:41:04 +00002925 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002926#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002927 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002928 rc = fsync(fd);
2929 }
drh0b647ff2009-03-21 14:41:04 +00002930#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002931#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2932
2933 if( OS_VXWORKS && rc!= -1 ){
2934 rc = 0;
2935 }
chw97185482008-11-17 08:05:31 +00002936 return rc;
drhbfe66312006-10-03 17:40:40 +00002937}
2938
drh734c9862008-11-28 15:37:20 +00002939/*
2940** Make sure all writes to a particular file are committed to disk.
2941**
2942** If dataOnly==0 then both the file itself and its metadata (file
2943** size, access time, etc) are synced. If dataOnly!=0 then only the
2944** file data is synced.
2945**
2946** Under Unix, also make sure that the directory entry for the file
2947** has been created by fsync-ing the directory that contains the file.
2948** If we do not do this and we encounter a power failure, the directory
2949** entry for the journal might not exist after we reboot. The next
2950** SQLite to access the file will not know that the journal exists (because
2951** the directory entry for the journal was never created) and the transaction
2952** will not roll back - possibly leading to database corruption.
2953*/
2954static int unixSync(sqlite3_file *id, int flags){
2955 int rc;
2956 unixFile *pFile = (unixFile*)id;
2957
2958 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2959 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2960
2961 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2962 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2963 || (flags&0x0F)==SQLITE_SYNC_FULL
2964 );
2965
2966 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2967 ** line is to test that doing so does not cause any problems.
2968 */
2969 SimulateDiskfullError( return SQLITE_FULL );
2970
2971 assert( pFile );
2972 OSTRACE2("SYNC %-3d\n", pFile->h);
2973 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2974 SimulateIOError( rc=1 );
2975 if( rc ){
2976 pFile->lastErrno = errno;
2977 return SQLITE_IOERR_FSYNC;
2978 }
2979 if( pFile->dirfd>=0 ){
2980 int err;
2981 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2982 HAVE_FULLFSYNC, isFullsync);
2983#ifndef SQLITE_DISABLE_DIRSYNC
2984 /* The directory sync is only attempted if full_fsync is
2985 ** turned off or unavailable. If a full_fsync occurred above,
2986 ** then the directory sync is superfluous.
2987 */
2988 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2989 /*
2990 ** We have received multiple reports of fsync() returning
2991 ** errors when applied to directories on certain file systems.
2992 ** A failed directory sync is not a big deal. So it seems
2993 ** better to ignore the error. Ticket #1657
2994 */
2995 /* pFile->lastErrno = errno; */
2996 /* return SQLITE_IOERR; */
2997 }
2998#endif
2999 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3000 if( err==0 ){ /* directory when we are done */
3001 pFile->dirfd = -1;
3002 }else{
3003 pFile->lastErrno = errno;
3004 rc = SQLITE_IOERR_DIR_CLOSE;
3005 }
3006 }
3007 return rc;
3008}
3009
3010/*
3011** Truncate an open file to a specified size
3012*/
3013static int unixTruncate(sqlite3_file *id, i64 nByte){
3014 int rc;
3015 assert( id );
3016 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3017 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3018 if( rc ){
3019 ((unixFile*)id)->lastErrno = errno;
3020 return SQLITE_IOERR_TRUNCATE;
3021 }else{
3022 return SQLITE_OK;
3023 }
3024}
3025
3026/*
3027** Determine the current size of a file in bytes
3028*/
3029static int unixFileSize(sqlite3_file *id, i64 *pSize){
3030 int rc;
3031 struct stat buf;
3032 assert( id );
3033 rc = fstat(((unixFile*)id)->h, &buf);
3034 SimulateIOError( rc=1 );
3035 if( rc!=0 ){
3036 ((unixFile*)id)->lastErrno = errno;
3037 return SQLITE_IOERR_FSTAT;
3038 }
3039 *pSize = buf.st_size;
3040
3041 /* When opening a zero-size database, the findLockInfo() procedure
3042 ** writes a single byte into that file in order to work around a bug
3043 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3044 ** layers, we need to report this file size as zero even though it is
3045 ** really 1. Ticket #3260.
3046 */
3047 if( *pSize==1 ) *pSize = 0;
3048
3049
3050 return SQLITE_OK;
3051}
3052
drhd2cb50b2009-01-09 21:41:17 +00003053#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003054/*
3055** Handler for proxy-locking file-control verbs. Defined below in the
3056** proxying locking division.
3057*/
3058static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003059#endif
drh715ff302008-12-03 22:32:44 +00003060
danielk1977ad94b582007-08-20 06:44:22 +00003061
danielk1977e3026632004-06-22 11:29:02 +00003062/*
drh9e33c2c2007-08-31 18:34:59 +00003063** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003064*/
drhcc6bb3e2007-08-31 16:11:35 +00003065static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003066 switch( op ){
3067 case SQLITE_FCNTL_LOCKSTATE: {
3068 *(int*)pArg = ((unixFile*)id)->locktype;
3069 return SQLITE_OK;
3070 }
drh7708e972008-11-29 00:56:52 +00003071 case SQLITE_LAST_ERRNO: {
3072 *(int*)pArg = ((unixFile*)id)->lastErrno;
3073 return SQLITE_OK;
3074 }
drh8f941bc2009-01-14 23:03:40 +00003075#ifndef NDEBUG
3076 /* The pager calls this method to signal that it has done
3077 ** a rollback and that the database is therefore unchanged and
3078 ** it hence it is OK for the transaction change counter to be
3079 ** unchanged.
3080 */
3081 case SQLITE_FCNTL_DB_UNCHANGED: {
3082 ((unixFile*)id)->dbUpdate = 0;
3083 return SQLITE_OK;
3084 }
3085#endif
drhd2cb50b2009-01-09 21:41:17 +00003086#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003087 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003088 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003089 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003090 }
drhd2cb50b2009-01-09 21:41:17 +00003091#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003092 }
drhcc6bb3e2007-08-31 16:11:35 +00003093 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003094}
3095
3096/*
danielk1977a3d4c882007-03-23 10:08:38 +00003097** Return the sector size in bytes of the underlying block device for
3098** the specified file. This is almost always 512 bytes, but may be
3099** larger for some devices.
3100**
3101** SQLite code assumes this function cannot fail. It also assumes that
3102** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003103** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003104** same for both.
3105*/
danielk1977397d65f2008-11-19 11:35:39 +00003106static int unixSectorSize(sqlite3_file *NotUsed){
3107 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003108 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003109}
3110
danielk197790949c22007-08-17 16:50:38 +00003111/*
danielk1977397d65f2008-11-19 11:35:39 +00003112** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003113*/
danielk1977397d65f2008-11-19 11:35:39 +00003114static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3115 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003116 return 0;
3117}
3118
drh734c9862008-11-28 15:37:20 +00003119/*
3120** Here ends the implementation of all sqlite3_file methods.
3121**
3122********************** End sqlite3_file Methods *******************************
3123******************************************************************************/
3124
3125/*
drh6b9d6dd2008-12-03 19:34:47 +00003126** This division contains definitions of sqlite3_io_methods objects that
3127** implement various file locking strategies. It also contains definitions
3128** of "finder" functions. A finder-function is used to locate the appropriate
3129** sqlite3_io_methods object for a particular database file. The pAppData
3130** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3131** the correct finder-function for that VFS.
3132**
3133** Most finder functions return a pointer to a fixed sqlite3_io_methods
3134** object. The only interesting finder-function is autolockIoFinder, which
3135** looks at the filesystem type and tries to guess the best locking
3136** strategy from that.
3137**
drh1875f7a2008-12-08 18:19:17 +00003138** For finder-funtion F, two objects are created:
3139**
3140** (1) The real finder-function named "FImpt()".
3141**
3142** (2) A constant pointer to this functio named just "F".
3143**
3144**
3145** A pointer to the F pointer is used as the pAppData value for VFS
3146** objects. We have to do this instead of letting pAppData point
3147** directly at the finder-function since C90 rules prevent a void*
3148** from be cast into a function pointer.
3149**
drh6b9d6dd2008-12-03 19:34:47 +00003150**
drh7708e972008-11-29 00:56:52 +00003151** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003152**
drh7708e972008-11-29 00:56:52 +00003153** * A constant sqlite3_io_methods object call METHOD that has locking
3154** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3155**
3156** * An I/O method finder function called FINDER that returns a pointer
3157** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003158*/
drh7708e972008-11-29 00:56:52 +00003159#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3160static const sqlite3_io_methods METHOD = { \
3161 1, /* iVersion */ \
3162 CLOSE, /* xClose */ \
3163 unixRead, /* xRead */ \
3164 unixWrite, /* xWrite */ \
3165 unixTruncate, /* xTruncate */ \
3166 unixSync, /* xSync */ \
3167 unixFileSize, /* xFileSize */ \
3168 LOCK, /* xLock */ \
3169 UNLOCK, /* xUnlock */ \
3170 CKLOCK, /* xCheckReservedLock */ \
3171 unixFileControl, /* xFileControl */ \
3172 unixSectorSize, /* xSectorSize */ \
3173 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3174}; \
drh1875f7a2008-12-08 18:19:17 +00003175static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003176 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3177 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003178} \
3179static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3180 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003181
3182/*
3183** Here are all of the sqlite3_io_methods objects for each of the
3184** locking strategies. Functions that return pointers to these methods
3185** are also created.
3186*/
3187IOMETHODS(
3188 posixIoFinder, /* Finder function name */
3189 posixIoMethods, /* sqlite3_io_methods object name */
3190 unixClose, /* xClose method */
3191 unixLock, /* xLock method */
3192 unixUnlock, /* xUnlock method */
3193 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003194)
drh7708e972008-11-29 00:56:52 +00003195IOMETHODS(
3196 nolockIoFinder, /* Finder function name */
3197 nolockIoMethods, /* sqlite3_io_methods object name */
3198 nolockClose, /* xClose method */
3199 nolockLock, /* xLock method */
3200 nolockUnlock, /* xUnlock method */
3201 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003202)
drh7708e972008-11-29 00:56:52 +00003203IOMETHODS(
3204 dotlockIoFinder, /* Finder function name */
3205 dotlockIoMethods, /* sqlite3_io_methods object name */
3206 dotlockClose, /* xClose method */
3207 dotlockLock, /* xLock method */
3208 dotlockUnlock, /* xUnlock method */
3209 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003210)
drh7708e972008-11-29 00:56:52 +00003211
chw78a13182009-04-07 05:35:03 +00003212#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003213IOMETHODS(
3214 flockIoFinder, /* Finder function name */
3215 flockIoMethods, /* sqlite3_io_methods object name */
3216 flockClose, /* xClose method */
3217 flockLock, /* xLock method */
3218 flockUnlock, /* xUnlock method */
3219 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003220)
drh7708e972008-11-29 00:56:52 +00003221#endif
3222
drh6c7d5c52008-11-21 20:32:33 +00003223#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003224IOMETHODS(
3225 semIoFinder, /* Finder function name */
3226 semIoMethods, /* sqlite3_io_methods object name */
3227 semClose, /* xClose method */
3228 semLock, /* xLock method */
3229 semUnlock, /* xUnlock method */
3230 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003231)
aswiftaebf4132008-11-21 00:10:35 +00003232#endif
drh7708e972008-11-29 00:56:52 +00003233
drhd2cb50b2009-01-09 21:41:17 +00003234#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003235IOMETHODS(
3236 afpIoFinder, /* Finder function name */
3237 afpIoMethods, /* sqlite3_io_methods object name */
3238 afpClose, /* xClose method */
3239 afpLock, /* xLock method */
3240 afpUnlock, /* xUnlock method */
3241 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003242)
drh715ff302008-12-03 22:32:44 +00003243#endif
3244
3245/*
3246** The proxy locking method is a "super-method" in the sense that it
3247** opens secondary file descriptors for the conch and lock files and
3248** it uses proxy, dot-file, AFP, and flock() locking methods on those
3249** secondary files. For this reason, the division that implements
3250** proxy locking is located much further down in the file. But we need
3251** to go ahead and define the sqlite3_io_methods and finder function
3252** for proxy locking here. So we forward declare the I/O methods.
3253*/
drhd2cb50b2009-01-09 21:41:17 +00003254#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003255static int proxyClose(sqlite3_file*);
3256static int proxyLock(sqlite3_file*, int);
3257static int proxyUnlock(sqlite3_file*, int);
3258static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003259IOMETHODS(
3260 proxyIoFinder, /* Finder function name */
3261 proxyIoMethods, /* sqlite3_io_methods object name */
3262 proxyClose, /* xClose method */
3263 proxyLock, /* xLock method */
3264 proxyUnlock, /* xUnlock method */
3265 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003266)
aswiftaebf4132008-11-21 00:10:35 +00003267#endif
drh7708e972008-11-29 00:56:52 +00003268
3269
drhd2cb50b2009-01-09 21:41:17 +00003270#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003271/*
drh6b9d6dd2008-12-03 19:34:47 +00003272** This "finder" function attempts to determine the best locking strategy
3273** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003274** object that implements that strategy.
3275**
3276** This is for MacOSX only.
3277*/
drh1875f7a2008-12-08 18:19:17 +00003278static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003279 const char *filePath, /* name of the database file */
3280 int fd /* file descriptor open on the database file */
3281){
3282 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003283 const char *zFilesystem; /* Filesystem type name */
3284 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003285 } aMap[] = {
3286 { "hfs", &posixIoMethods },
3287 { "ufs", &posixIoMethods },
3288 { "afpfs", &afpIoMethods },
3289#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3290 { "smbfs", &afpIoMethods },
3291#else
3292 { "smbfs", &flockIoMethods },
3293#endif
3294 { "webdav", &nolockIoMethods },
3295 { 0, 0 }
3296 };
3297 int i;
3298 struct statfs fsInfo;
3299 struct flock lockInfo;
3300
3301 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003302 /* If filePath==NULL that means we are dealing with a transient file
3303 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003304 return &nolockIoMethods;
3305 }
3306 if( statfs(filePath, &fsInfo) != -1 ){
3307 if( fsInfo.f_flags & MNT_RDONLY ){
3308 return &nolockIoMethods;
3309 }
3310 for(i=0; aMap[i].zFilesystem; i++){
3311 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3312 return aMap[i].pMethods;
3313 }
3314 }
3315 }
3316
3317 /* Default case. Handles, amongst others, "nfs".
3318 ** Test byte-range lock using fcntl(). If the call succeeds,
3319 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003320 */
drh7708e972008-11-29 00:56:52 +00003321 lockInfo.l_len = 1;
3322 lockInfo.l_start = 0;
3323 lockInfo.l_whence = SEEK_SET;
3324 lockInfo.l_type = F_RDLCK;
3325 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3326 return &posixIoMethods;
3327 }else{
3328 return &dotlockIoMethods;
3329 }
3330}
danielk1977852e2322008-12-22 03:36:59 +00003331static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003332 = autolockIoFinderImpl;
3333
drhd2cb50b2009-01-09 21:41:17 +00003334#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003335
chw78a13182009-04-07 05:35:03 +00003336#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3337/*
3338** This "finder" function attempts to determine the best locking strategy
3339** for the database file "filePath". It then returns the sqlite3_io_methods
3340** object that implements that strategy.
3341**
3342** This is for VXWorks only.
3343*/
3344static const sqlite3_io_methods *autolockIoFinderImpl(
3345 const char *filePath, /* name of the database file */
3346 int fd /* file descriptor open on the database file */
3347){
3348 struct flock lockInfo;
3349
3350 if( !filePath ){
3351 /* If filePath==NULL that means we are dealing with a transient file
3352 ** that does not need to be locked. */
3353 return &nolockIoMethods;
3354 }
3355
3356 /* Test if fcntl() is supported and use POSIX style locks.
3357 ** Otherwise fall back to the named semaphore method.
3358 */
3359 lockInfo.l_len = 1;
3360 lockInfo.l_start = 0;
3361 lockInfo.l_whence = SEEK_SET;
3362 lockInfo.l_type = F_RDLCK;
3363 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3364 return &posixIoMethods;
3365 }else{
3366 return &semIoMethods;
3367 }
3368}
3369static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
3370 = autolockIoFinderImpl;
3371
3372#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3373
drh7708e972008-11-29 00:56:52 +00003374/*
3375** An abstract type for a pointer to a IO method finder function:
3376*/
3377typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3378
aswiftaebf4132008-11-21 00:10:35 +00003379
drh734c9862008-11-28 15:37:20 +00003380/****************************************************************************
3381**************************** sqlite3_vfs methods ****************************
3382**
3383** This division contains the implementation of methods on the
3384** sqlite3_vfs object.
3385*/
3386
danielk1977a3d4c882007-03-23 10:08:38 +00003387/*
danielk1977e339d652008-06-28 11:23:00 +00003388** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003389*/
3390static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003391 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003392 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003393 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003394 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003395 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003396 int noLock, /* Omit locking if true */
3397 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003398){
drh7708e972008-11-29 00:56:52 +00003399 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003400 unixFile *pNew = (unixFile *)pId;
3401 int rc = SQLITE_OK;
3402
danielk197717b90b52008-06-06 11:11:25 +00003403 assert( pNew->pLock==NULL );
3404 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003405
drh715ff302008-12-03 22:32:44 +00003406 /* Parameter isDelete is only used on vxworks.
3407 ** Express this explicitly here to prevent compiler warnings
3408 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003409 */
drh7708e972008-11-29 00:56:52 +00003410#if !OS_VXWORKS
3411 UNUSED_PARAMETER(isDelete);
3412#endif
danielk1977a03396a2008-11-19 14:35:46 +00003413
drh218c5082008-03-07 00:27:10 +00003414 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003415 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003416 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003417 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003418
drh6c7d5c52008-11-21 20:32:33 +00003419#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003420 pNew->pId = vxworksFindFileId(zFilename);
3421 if( pNew->pId==0 ){
3422 noLock = 1;
3423 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003424 }
3425#endif
3426
drhda0e7682008-07-30 15:27:54 +00003427 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003428 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003429 }else{
drh1875f7a2008-12-08 18:19:17 +00003430 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003431#if SQLITE_ENABLE_LOCKING_STYLE
3432 /* Cache zFilename in the locking context (AFP and dotlock override) for
3433 ** proxyLock activation is possible (remote proxy is based on db name)
3434 ** zFilename remains valid until file is closed, to support */
3435 pNew->lockingContext = (void*)zFilename;
3436#endif
drhda0e7682008-07-30 15:27:54 +00003437 }
danielk1977e339d652008-06-28 11:23:00 +00003438
drh7708e972008-11-29 00:56:52 +00003439 if( pLockingStyle == &posixIoMethods ){
3440 unixEnterMutex();
3441 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3442 unixLeaveMutex();
3443 }
danielk1977e339d652008-06-28 11:23:00 +00003444
drhd2cb50b2009-01-09 21:41:17 +00003445#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003446 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003447 /* AFP locking uses the file path so it needs to be included in
3448 ** the afpLockingContext.
3449 */
3450 afpLockingContext *pCtx;
3451 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3452 if( pCtx==0 ){
3453 rc = SQLITE_NOMEM;
3454 }else{
3455 /* NB: zFilename exists and remains valid until the file is closed
3456 ** according to requirement F11141. So we do not need to make a
3457 ** copy of the filename. */
3458 pCtx->dbPath = zFilename;
3459 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003460 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003461 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3462 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003463 }
drh7708e972008-11-29 00:56:52 +00003464 }
3465#endif
danielk1977e339d652008-06-28 11:23:00 +00003466
drh7708e972008-11-29 00:56:52 +00003467 else if( pLockingStyle == &dotlockIoMethods ){
3468 /* Dotfile locking uses the file path so it needs to be included in
3469 ** the dotlockLockingContext
3470 */
3471 char *zLockFile;
3472 int nFilename;
drhea678832008-12-10 19:26:22 +00003473 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003474 zLockFile = (char *)sqlite3_malloc(nFilename);
3475 if( zLockFile==0 ){
3476 rc = SQLITE_NOMEM;
3477 }else{
3478 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003479 }
drh7708e972008-11-29 00:56:52 +00003480 pNew->lockingContext = zLockFile;
3481 }
danielk1977e339d652008-06-28 11:23:00 +00003482
drh6c7d5c52008-11-21 20:32:33 +00003483#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003484 else if( pLockingStyle == &semIoMethods ){
3485 /* Named semaphore locking uses the file path so it needs to be
3486 ** included in the semLockingContext
3487 */
3488 unixEnterMutex();
3489 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3490 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3491 char *zSemName = pNew->pOpen->aSemName;
3492 int n;
3493 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3494 pNew->pId->zCanonicalName);
3495 for( n=0; zSemName[n]; n++ )
3496 if( zSemName[n]=='/' ) zSemName[n] = '_';
3497 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3498 if( pNew->pOpen->pSem == SEM_FAILED ){
3499 rc = SQLITE_NOMEM;
3500 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003501 }
chw97185482008-11-17 08:05:31 +00003502 }
drh7708e972008-11-29 00:56:52 +00003503 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003504 }
drh7708e972008-11-29 00:56:52 +00003505#endif
aswift5b1a2562008-08-22 00:22:35 +00003506
3507 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003508#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003509 if( rc!=SQLITE_OK ){
3510 unlink(zFilename);
3511 isDelete = 0;
3512 }
3513 pNew->isDelete = isDelete;
3514#endif
danielk1977e339d652008-06-28 11:23:00 +00003515 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003516 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003517 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003518 }else{
drh7708e972008-11-29 00:56:52 +00003519 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003520 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003521 }
danielk1977e339d652008-06-28 11:23:00 +00003522 return rc;
drh054889e2005-11-30 03:20:31 +00003523}
drh9c06c952005-11-26 00:25:00 +00003524
danielk1977ad94b582007-08-20 06:44:22 +00003525/*
3526** Open a file descriptor to the directory containing file zFilename.
3527** If successful, *pFd is set to the opened file descriptor and
3528** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3529** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3530** value.
3531**
3532** If SQLITE_OK is returned, the caller is responsible for closing
3533** the file descriptor *pFd using close().
3534*/
danielk1977fee2d252007-08-18 10:59:19 +00003535static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003536 int ii;
drh777b17a2007-09-20 10:02:54 +00003537 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003538 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003539
drh153c62c2007-08-24 03:51:33 +00003540 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003541 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003542 if( ii>0 ){
3543 zDirname[ii] = '\0';
3544 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003545 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003546#ifdef FD_CLOEXEC
3547 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3548#endif
3549 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3550 }
3551 }
danielk1977fee2d252007-08-18 10:59:19 +00003552 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003553 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003554}
3555
danielk1977b4b47412007-08-17 15:53:36 +00003556/*
danielk197717b90b52008-06-06 11:11:25 +00003557** Create a temporary file name in zBuf. zBuf must be allocated
3558** by the calling process and must be big enough to hold at least
3559** pVfs->mxPathname bytes.
3560*/
3561static int getTempname(int nBuf, char *zBuf){
3562 static const char *azDirs[] = {
3563 0,
aswiftaebf4132008-11-21 00:10:35 +00003564 0,
danielk197717b90b52008-06-06 11:11:25 +00003565 "/var/tmp",
3566 "/usr/tmp",
3567 "/tmp",
3568 ".",
3569 };
3570 static const unsigned char zChars[] =
3571 "abcdefghijklmnopqrstuvwxyz"
3572 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3573 "0123456789";
drh41022642008-11-21 00:24:42 +00003574 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003575 struct stat buf;
3576 const char *zDir = ".";
3577
3578 /* It's odd to simulate an io-error here, but really this is just
3579 ** using the io-error infrastructure to test that SQLite handles this
3580 ** function failing.
3581 */
3582 SimulateIOError( return SQLITE_IOERR );
3583
3584 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003585 if (NULL == azDirs[1]) {
3586 azDirs[1] = getenv("TMPDIR");
3587 }
3588
3589 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003590 if( azDirs[i]==0 ) continue;
3591 if( stat(azDirs[i], &buf) ) continue;
3592 if( !S_ISDIR(buf.st_mode) ) continue;
3593 if( access(azDirs[i], 07) ) continue;
3594 zDir = azDirs[i];
3595 break;
3596 }
3597
3598 /* Check that the output buffer is large enough for the temporary file
3599 ** name. If it is not, return SQLITE_ERROR.
3600 */
danielk197700e13612008-11-17 19:18:54 +00003601 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003602 return SQLITE_ERROR;
3603 }
3604
3605 do{
3606 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003607 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003608 sqlite3_randomness(15, &zBuf[j]);
3609 for(i=0; i<15; i++, j++){
3610 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3611 }
3612 zBuf[j] = 0;
3613 }while( access(zBuf,0)==0 );
3614 return SQLITE_OK;
3615}
3616
drhd2cb50b2009-01-09 21:41:17 +00003617#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003618/*
3619** Routine to transform a unixFile into a proxy-locking unixFile.
3620** Implementation in the proxy-lock division, but used by unixOpen()
3621** if SQLITE_PREFER_PROXY_LOCKING is defined.
3622*/
3623static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003624#endif
drhc66d5b62008-12-03 22:48:32 +00003625
danielk197717b90b52008-06-06 11:11:25 +00003626
3627/*
danielk1977ad94b582007-08-20 06:44:22 +00003628** Open the file zPath.
3629**
danielk1977b4b47412007-08-17 15:53:36 +00003630** Previously, the SQLite OS layer used three functions in place of this
3631** one:
3632**
3633** sqlite3OsOpenReadWrite();
3634** sqlite3OsOpenReadOnly();
3635** sqlite3OsOpenExclusive();
3636**
3637** These calls correspond to the following combinations of flags:
3638**
3639** ReadWrite() -> (READWRITE | CREATE)
3640** ReadOnly() -> (READONLY)
3641** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3642**
3643** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3644** true, the file was configured to be automatically deleted when the
3645** file handle closed. To achieve the same effect using this new
3646** interface, add the DELETEONCLOSE flag to those specified above for
3647** OpenExclusive().
3648*/
3649static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003650 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3651 const char *zPath, /* Pathname of file to be opened */
3652 sqlite3_file *pFile, /* The file descriptor to be filled in */
3653 int flags, /* Input flags to control the opening */
3654 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003655){
drh577d6742009-04-07 00:35:20 +00003656 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00003657 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003658 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003659 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003660 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003661 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003662
3663 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3664 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3665 int isCreate = (flags & SQLITE_OPEN_CREATE);
3666 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3667 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3668
danielk1977fee2d252007-08-18 10:59:19 +00003669 /* If creating a master or main-file journal, this function will open
3670 ** a file-descriptor on the directory too. The first time unixSync()
3671 ** is called the directory file descriptor will be fsync()ed and close()d.
3672 */
3673 int isOpenDirectory = (isCreate &&
3674 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3675 );
3676
danielk197717b90b52008-06-06 11:11:25 +00003677 /* If argument zPath is a NULL pointer, this function is required to open
3678 ** a temporary file. Use this buffer to store the file name in.
3679 */
3680 char zTmpname[MAX_PATHNAME+1];
3681 const char *zName = zPath;
3682
danielk1977fee2d252007-08-18 10:59:19 +00003683 /* Check the following statements are true:
3684 **
3685 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3686 ** (b) if CREATE is set, then READWRITE must also be set, and
3687 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003688 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003689 */
danielk1977b4b47412007-08-17 15:53:36 +00003690 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003691 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003692 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003693 assert(isDelete==0 || isCreate);
3694
drh33f4e022007-09-03 15:19:34 +00003695 /* The main DB, main journal, and master journal are never automatically
3696 ** deleted
3697 */
3698 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3699 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3700 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003701
danielk1977fee2d252007-08-18 10:59:19 +00003702 /* Assert that the upper layer has set one of the "file-type" flags. */
3703 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3704 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3705 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003706 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003707 );
3708
danielk1977e339d652008-06-28 11:23:00 +00003709 memset(pFile, 0, sizeof(unixFile));
3710
danielk197717b90b52008-06-06 11:11:25 +00003711 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003712 assert(isDelete && !isOpenDirectory);
3713 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3714 if( rc!=SQLITE_OK ){
3715 return rc;
3716 }
3717 zName = zTmpname;
3718 }
3719
drh734c9862008-11-28 15:37:20 +00003720 if( isReadonly ) openFlags |= O_RDONLY;
3721 if( isReadWrite ) openFlags |= O_RDWR;
3722 if( isCreate ) openFlags |= O_CREAT;
3723 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3724 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003725
drh734c9862008-11-28 15:37:20 +00003726 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3727 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003728 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003729 /* Failed to open the file for read/write access. Try read-only. */
3730 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3731 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003732 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003733 }
3734 if( fd<0 ){
3735 return SQLITE_CANTOPEN;
3736 }
3737 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003738#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003739 zPath = zName;
3740#else
danielk197717b90b52008-06-06 11:11:25 +00003741 unlink(zName);
chw97185482008-11-17 08:05:31 +00003742#endif
danielk1977b4b47412007-08-17 15:53:36 +00003743 }
drh41022642008-11-21 00:24:42 +00003744#if SQLITE_ENABLE_LOCKING_STYLE
3745 else{
drh734c9862008-11-28 15:37:20 +00003746 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003747 }
3748#endif
danielk1977b4b47412007-08-17 15:53:36 +00003749 if( pOutFlags ){
3750 *pOutFlags = flags;
3751 }
3752
drh08c6d442009-02-09 17:34:07 +00003753#ifndef NDEBUG
3754 if( (flags & SQLITE_OPEN_MAIN_DB)!=0 ){
3755 ((unixFile*)pFile)->isLockable = 1;
3756 }
3757#endif
3758
drh577d6742009-04-07 00:35:20 +00003759 assert( fd>=0 );
danielk1977fee2d252007-08-18 10:59:19 +00003760 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003761 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003762 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003763 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003764 return rc;
3765 }
3766 }
danielk1977e339d652008-06-28 11:23:00 +00003767
3768#ifdef FD_CLOEXEC
3769 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3770#endif
3771
drhda0e7682008-07-30 15:27:54 +00003772 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003773
3774#if SQLITE_PREFER_PROXY_LOCKING
3775 if( zPath!=NULL && !noLock ){
3776 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3777 int useProxy = 0;
3778
3779 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003780 ** 0 means never use proxy, NULL means use proxy for non-local files only
3781 */
aswiftaebf4132008-11-21 00:10:35 +00003782 if( envforce!=NULL ){
3783 useProxy = atoi(envforce)>0;
3784 }else{
3785 struct statfs fsInfo;
3786
3787 if( statfs(zPath, &fsInfo) == -1 ){
3788 ((unixFile*)pFile)->lastErrno = errno;
3789 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3790 close(fd); /* silently leak if fail, in error */
3791 return SQLITE_IOERR_ACCESS;
3792 }
3793 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3794 }
3795 if( useProxy ){
3796 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3797 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003798 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003799 }
3800 return rc;
3801 }
3802 }
3803#endif
3804
chw97185482008-11-17 08:05:31 +00003805 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003806}
3807
3808/*
danielk1977fee2d252007-08-18 10:59:19 +00003809** Delete the file at zPath. If the dirSync argument is true, fsync()
3810** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003811*/
drh6b9d6dd2008-12-03 19:34:47 +00003812static int unixDelete(
3813 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3814 const char *zPath, /* Name of file to be deleted */
3815 int dirSync /* If true, fsync() directory after deleting file */
3816){
danielk1977fee2d252007-08-18 10:59:19 +00003817 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003818 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003819 SimulateIOError(return SQLITE_IOERR_DELETE);
3820 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003821#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003822 if( dirSync ){
3823 int fd;
3824 rc = openDirectory(zPath, &fd);
3825 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003826#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003827 if( fsync(fd)==-1 )
3828#else
3829 if( fsync(fd) )
3830#endif
3831 {
danielk1977fee2d252007-08-18 10:59:19 +00003832 rc = SQLITE_IOERR_DIR_FSYNC;
3833 }
aswiftaebf4132008-11-21 00:10:35 +00003834 if( close(fd)&&!rc ){
3835 rc = SQLITE_IOERR_DIR_CLOSE;
3836 }
danielk1977fee2d252007-08-18 10:59:19 +00003837 }
3838 }
danielk1977d138dd82008-10-15 16:02:48 +00003839#endif
danielk1977fee2d252007-08-18 10:59:19 +00003840 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003841}
3842
danielk197790949c22007-08-17 16:50:38 +00003843/*
3844** Test the existance of or access permissions of file zPath. The
3845** test performed depends on the value of flags:
3846**
3847** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3848** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3849** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3850**
3851** Otherwise return 0.
3852*/
danielk1977861f7452008-06-05 11:39:11 +00003853static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003854 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3855 const char *zPath, /* Path of the file to examine */
3856 int flags, /* What do we want to learn about the zPath file? */
3857 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003858){
rse25c0d1a2007-09-20 08:38:14 +00003859 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003860 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003861 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003862 switch( flags ){
3863 case SQLITE_ACCESS_EXISTS:
3864 amode = F_OK;
3865 break;
3866 case SQLITE_ACCESS_READWRITE:
3867 amode = W_OK|R_OK;
3868 break;
drh50d3f902007-08-27 21:10:36 +00003869 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003870 amode = R_OK;
3871 break;
3872
3873 default:
3874 assert(!"Invalid flags argument");
3875 }
danielk1977861f7452008-06-05 11:39:11 +00003876 *pResOut = (access(zPath, amode)==0);
3877 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003878}
3879
danielk1977b4b47412007-08-17 15:53:36 +00003880
3881/*
3882** Turn a relative pathname into a full pathname. The relative path
3883** is stored as a nul-terminated string in the buffer pointed to by
3884** zPath.
3885**
3886** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3887** (in this case, MAX_PATHNAME bytes). The full-path is written to
3888** this buffer before returning.
3889*/
danielk1977adfb9b02007-09-17 07:02:56 +00003890static int unixFullPathname(
3891 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3892 const char *zPath, /* Possibly relative input path */
3893 int nOut, /* Size of output buffer in bytes */
3894 char *zOut /* Output buffer */
3895){
danielk1977843e65f2007-09-01 16:16:15 +00003896
3897 /* It's odd to simulate an io-error here, but really this is just
3898 ** using the io-error infrastructure to test that SQLite handles this
3899 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003900 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003901 */
3902 SimulateIOError( return SQLITE_ERROR );
3903
drh153c62c2007-08-24 03:51:33 +00003904 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003905 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003906
drh3c7f2dc2007-12-06 13:26:20 +00003907 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003908 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003909 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003910 }else{
3911 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003912 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003913 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003914 }
drhea678832008-12-10 19:26:22 +00003915 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003916 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003917 }
3918 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003919}
3920
drh0ccebe72005-06-07 22:22:50 +00003921
drh761df872006-12-21 01:29:22 +00003922#ifndef SQLITE_OMIT_LOAD_EXTENSION
3923/*
3924** Interfaces for opening a shared library, finding entry points
3925** within the shared library, and closing the shared library.
3926*/
3927#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003928static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3929 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003930 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3931}
danielk197795c8a542007-09-01 06:51:27 +00003932
3933/*
3934** SQLite calls this function immediately after a call to unixDlSym() or
3935** unixDlOpen() fails (returns a null pointer). If a more detailed error
3936** message is available, it is written to zBufOut. If no error message
3937** is available, zBufOut is left unmodified and SQLite uses a default
3938** error message.
3939*/
danielk1977397d65f2008-11-19 11:35:39 +00003940static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003941 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003942 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003943 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003944 zErr = dlerror();
3945 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003946 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003947 }
drh6c7d5c52008-11-21 20:32:33 +00003948 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003949}
drh1875f7a2008-12-08 18:19:17 +00003950static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3951 /*
3952 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3953 ** cast into a pointer to a function. And yet the library dlsym() routine
3954 ** returns a void* which is really a pointer to a function. So how do we
3955 ** use dlsym() with -pedantic-errors?
3956 **
3957 ** Variable x below is defined to be a pointer to a function taking
3958 ** parameters void* and const char* and returning a pointer to a function.
3959 ** We initialize x by assigning it a pointer to the dlsym() function.
3960 ** (That assignment requires a cast.) Then we call the function that
3961 ** x points to.
3962 **
3963 ** This work-around is unlikely to work correctly on any system where
3964 ** you really cannot cast a function pointer into void*. But then, on the
3965 ** other hand, dlsym() will not work on such a system either, so we have
3966 ** not really lost anything.
3967 */
3968 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003969 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003970 x = (void(*(*)(void*,const char*))(void))dlsym;
3971 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003972}
danielk1977397d65f2008-11-19 11:35:39 +00003973static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
3974 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003975 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003976}
danielk1977b4b47412007-08-17 15:53:36 +00003977#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3978 #define unixDlOpen 0
3979 #define unixDlError 0
3980 #define unixDlSym 0
3981 #define unixDlClose 0
3982#endif
3983
3984/*
danielk197790949c22007-08-17 16:50:38 +00003985** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003986*/
danielk1977397d65f2008-11-19 11:35:39 +00003987static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
3988 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00003989 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00003990
drhbbd42a62004-05-22 17:41:58 +00003991 /* We have to initialize zBuf to prevent valgrind from reporting
3992 ** errors. The reports issued by valgrind are incorrect - we would
3993 ** prefer that the randomness be increased by making use of the
3994 ** uninitialized space in zBuf - but valgrind errors tend to worry
3995 ** some users. Rather than argue, it seems easier just to initialize
3996 ** the whole array and silence valgrind, even if that means less randomness
3997 ** in the random seed.
3998 **
3999 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004000 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004001 ** tests repeatable.
4002 */
danielk1977b4b47412007-08-17 15:53:36 +00004003 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004004#if !defined(SQLITE_TEST)
4005 {
drh842b8642005-01-21 17:53:17 +00004006 int pid, fd;
4007 fd = open("/dev/urandom", O_RDONLY);
4008 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004009 time_t t;
4010 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004011 memcpy(zBuf, &t, sizeof(t));
4012 pid = getpid();
4013 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004014 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004015 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004016 }else{
drh72cbd072008-10-14 17:58:38 +00004017 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004018 close(fd);
4019 }
drhbbd42a62004-05-22 17:41:58 +00004020 }
4021#endif
drh72cbd072008-10-14 17:58:38 +00004022 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004023}
4024
danielk1977b4b47412007-08-17 15:53:36 +00004025
drhbbd42a62004-05-22 17:41:58 +00004026/*
4027** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004028** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004029** The return value is the number of microseconds of sleep actually
4030** requested from the underlying operating system, a number which
4031** might be greater than or equal to the argument, but not less
4032** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004033*/
danielk1977397d65f2008-11-19 11:35:39 +00004034static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004035#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004036 struct timespec sp;
4037
4038 sp.tv_sec = microseconds / 1000000;
4039 sp.tv_nsec = (microseconds % 1000000) * 1000;
4040 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004041 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004042 return microseconds;
4043#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004044 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004045 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004046 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004047#else
danielk1977b4b47412007-08-17 15:53:36 +00004048 int seconds = (microseconds+999999)/1000000;
4049 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004050 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004051 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004052#endif
drh88f474a2006-01-02 20:00:12 +00004053}
4054
4055/*
drh6b9d6dd2008-12-03 19:34:47 +00004056** The following variable, if set to a non-zero value, is interpreted as
4057** the number of seconds since 1970 and is used to set the result of
4058** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004059*/
4060#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004061int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004062#endif
4063
4064/*
4065** Find the current time (in Universal Coordinated Time). Write the
4066** current time and date as a Julian Day number into *prNow and
4067** return 0. Return 1 if the time and date cannot be found.
4068*/
danielk1977397d65f2008-11-19 11:35:39 +00004069static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004070#if defined(SQLITE_OMIT_FLOATING_POINT)
4071 time_t t;
4072 time(&t);
4073 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4074#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004075 time_t t;
4076 time(&t);
4077 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004078#elif OS_VXWORKS
4079 struct timespec sNow;
4080 clock_gettime(CLOCK_REALTIME, &sNow);
4081 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004082#else
4083 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004084 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004085 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4086#endif
danielk1977397d65f2008-11-19 11:35:39 +00004087
drhbbd42a62004-05-22 17:41:58 +00004088#ifdef SQLITE_TEST
4089 if( sqlite3_current_time ){
4090 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4091 }
4092#endif
danielk1977397d65f2008-11-19 11:35:39 +00004093 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004094 return 0;
4095}
danielk1977b4b47412007-08-17 15:53:36 +00004096
drh6b9d6dd2008-12-03 19:34:47 +00004097/*
4098** We added the xGetLastError() method with the intention of providing
4099** better low-level error messages when operating-system problems come up
4100** during SQLite operation. But so far, none of that has been implemented
4101** in the core. So this routine is never called. For now, it is merely
4102** a place-holder.
4103*/
danielk1977397d65f2008-11-19 11:35:39 +00004104static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4105 UNUSED_PARAMETER(NotUsed);
4106 UNUSED_PARAMETER(NotUsed2);
4107 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004108 return 0;
4109}
4110
drh153c62c2007-08-24 03:51:33 +00004111/*
drh734c9862008-11-28 15:37:20 +00004112************************ End of sqlite3_vfs methods ***************************
4113******************************************************************************/
4114
drh715ff302008-12-03 22:32:44 +00004115/******************************************************************************
4116************************** Begin Proxy Locking ********************************
4117**
4118** Proxy locking is a "uber-locking-method" in this sense: It uses the
4119** other locking methods on secondary lock files. Proxy locking is a
4120** meta-layer over top of the primitive locking implemented above. For
4121** this reason, the division that implements of proxy locking is deferred
4122** until late in the file (here) after all of the other I/O methods have
4123** been defined - so that the primitive locking methods are available
4124** as services to help with the implementation of proxy locking.
4125**
4126****
4127**
4128** The default locking schemes in SQLite use byte-range locks on the
4129** database file to coordinate safe, concurrent access by multiple readers
4130** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4131** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4132** as POSIX read & write locks over fixed set of locations (via fsctl),
4133** on AFP and SMB only exclusive byte-range locks are available via fsctl
4134** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4135** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4136** address in the shared range is taken for a SHARED lock, the entire
4137** shared range is taken for an EXCLUSIVE lock):
4138**
4139** PENDING_BYTE 0x40000000
4140** RESERVED_BYTE 0x40000001
4141** SHARED_RANGE 0x40000002 -> 0x40000200
4142**
4143** This works well on the local file system, but shows a nearly 100x
4144** slowdown in read performance on AFP because the AFP client disables
4145** the read cache when byte-range locks are present. Enabling the read
4146** cache exposes a cache coherency problem that is present on all OS X
4147** supported network file systems. NFS and AFP both observe the
4148** close-to-open semantics for ensuring cache coherency
4149** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4150** address the requirements for concurrent database access by multiple
4151** readers and writers
4152** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4153**
4154** To address the performance and cache coherency issues, proxy file locking
4155** changes the way database access is controlled by limiting access to a
4156** single host at a time and moving file locks off of the database file
4157** and onto a proxy file on the local file system.
4158**
4159**
4160** Using proxy locks
4161** -----------------
4162**
4163** C APIs
4164**
4165** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4166** <proxy_path> | ":auto:");
4167** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4168**
4169**
4170** SQL pragmas
4171**
4172** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4173** PRAGMA [database.]lock_proxy_file
4174**
4175** Specifying ":auto:" means that if there is a conch file with a matching
4176** host ID in it, the proxy path in the conch file will be used, otherwise
4177** a proxy path based on the user's temp dir
4178** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4179** actual proxy file name is generated from the name and path of the
4180** database file. For example:
4181**
4182** For database path "/Users/me/foo.db"
4183** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4184**
4185** Once a lock proxy is configured for a database connection, it can not
4186** be removed, however it may be switched to a different proxy path via
4187** the above APIs (assuming the conch file is not being held by another
4188** connection or process).
4189**
4190**
4191** How proxy locking works
4192** -----------------------
4193**
4194** Proxy file locking relies primarily on two new supporting files:
4195**
4196** * conch file to limit access to the database file to a single host
4197** at a time
4198**
4199** * proxy file to act as a proxy for the advisory locks normally
4200** taken on the database
4201**
4202** The conch file - to use a proxy file, sqlite must first "hold the conch"
4203** by taking an sqlite-style shared lock on the conch file, reading the
4204** contents and comparing the host's unique host ID (see below) and lock
4205** proxy path against the values stored in the conch. The conch file is
4206** stored in the same directory as the database file and the file name
4207** is patterned after the database file name as ".<databasename>-conch".
4208** If the conch file does not exist, or it's contents do not match the
4209** host ID and/or proxy path, then the lock is escalated to an exclusive
4210** lock and the conch file contents is updated with the host ID and proxy
4211** path and the lock is downgraded to a shared lock again. If the conch
4212** is held by another process (with a shared lock), the exclusive lock
4213** will fail and SQLITE_BUSY is returned.
4214**
4215** The proxy file - a single-byte file used for all advisory file locks
4216** normally taken on the database file. This allows for safe sharing
4217** of the database file for multiple readers and writers on the same
4218** host (the conch ensures that they all use the same local lock file).
4219**
4220** There is a third file - the host ID file - used as a persistent record
4221** of a unique identifier for the host, a 128-byte unique host id file
4222** in the path defined by the HOSTIDPATH macro (default value is
4223** /Library/Caches/.com.apple.sqliteConchHostId).
4224**
4225** Requesting the lock proxy does not immediately take the conch, it is
4226** only taken when the first request to lock database file is made.
4227** This matches the semantics of the traditional locking behavior, where
4228** opening a connection to a database file does not take a lock on it.
4229** The shared lock and an open file descriptor are maintained until
4230** the connection to the database is closed.
4231**
4232** The proxy file and the lock file are never deleted so they only need
4233** to be created the first time they are used.
4234**
4235** Configuration options
4236** ---------------------
4237**
4238** SQLITE_PREFER_PROXY_LOCKING
4239**
4240** Database files accessed on non-local file systems are
4241** automatically configured for proxy locking, lock files are
4242** named automatically using the same logic as
4243** PRAGMA lock_proxy_file=":auto:"
4244**
4245** SQLITE_PROXY_DEBUG
4246**
4247** Enables the logging of error messages during host id file
4248** retrieval and creation
4249**
4250** HOSTIDPATH
4251**
4252** Overrides the default host ID file path location
4253**
4254** LOCKPROXYDIR
4255**
4256** Overrides the default directory used for lock proxy files that
4257** are named automatically via the ":auto:" setting
4258**
4259** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4260**
4261** Permissions to use when creating a directory for storing the
4262** lock proxy files, only used when LOCKPROXYDIR is not set.
4263**
4264**
4265** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4266** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4267** force proxy locking to be used for every database file opened, and 0
4268** will force automatic proxy locking to be disabled for all database
4269** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4270** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4271*/
4272
4273/*
4274** Proxy locking is only available on MacOSX
4275*/
drhd2cb50b2009-01-09 21:41:17 +00004276#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004277
4278#ifdef SQLITE_TEST
4279/* simulate multiple hosts by creating unique hostid file paths */
4280int sqlite3_hostid_num = 0;
4281#endif
4282
4283/*
4284** The proxyLockingContext has the path and file structures for the remote
4285** and local proxy files in it
4286*/
4287typedef struct proxyLockingContext proxyLockingContext;
4288struct proxyLockingContext {
4289 unixFile *conchFile; /* Open conch file */
4290 char *conchFilePath; /* Name of the conch file */
4291 unixFile *lockProxy; /* Open proxy lock file */
4292 char *lockProxyPath; /* Name of the proxy lock file */
4293 char *dbPath; /* Name of the open file */
4294 int conchHeld; /* True if the conch is currently held */
4295 void *oldLockingContext; /* Original lockingcontext to restore on close */
4296 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4297};
4298
4299/* HOSTIDLEN and CONCHLEN both include space for the string
4300** terminating nul
4301*/
4302#define HOSTIDLEN 128
4303#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4304#ifndef HOSTIDPATH
4305# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4306#endif
4307
4308/* basically a copy of unixRandomness with different
4309** test behavior built in */
4310static int proxyGenerateHostID(char *pHostID){
4311 int pid, fd, len;
4312 unsigned char *key = (unsigned char *)pHostID;
4313
4314 memset(key, 0, HOSTIDLEN);
4315 len = 0;
4316 fd = open("/dev/urandom", O_RDONLY);
4317 if( fd>=0 ){
4318 len = read(fd, key, HOSTIDLEN);
4319 close(fd); /* silently leak the fd if it fails */
4320 }
4321 if( len < HOSTIDLEN ){
4322 time_t t;
4323 time(&t);
4324 memcpy(key, &t, sizeof(t));
4325 pid = getpid();
4326 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4327 }
4328
4329#ifdef MAKE_PRETTY_HOSTID
4330 {
4331 int i;
4332 /* filter the bytes into printable ascii characters and NUL terminate */
4333 key[(HOSTIDLEN-1)] = 0x00;
4334 for( i=0; i<(HOSTIDLEN-1); i++ ){
4335 unsigned char pa = key[i]&0x7F;
4336 if( pa<0x20 ){
4337 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4338 }else if( pa==0x7F ){
4339 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4340 }
4341 }
4342 }
4343#endif
4344 return SQLITE_OK;
4345}
4346
4347/* writes the host id path to path, path should be an pre-allocated buffer
4348** with enough space for a path
4349*/
4350static void proxyGetHostIDPath(char *path, size_t len){
4351 strlcpy(path, HOSTIDPATH, len);
4352#ifdef SQLITE_TEST
4353 if( sqlite3_hostid_num>0 ){
4354 char suffix[2] = "1";
4355 suffix[0] = suffix[0] + sqlite3_hostid_num;
4356 strlcat(path, suffix, len);
4357 }
4358#endif
4359 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4360}
4361
4362/* get the host ID from a sqlite hostid file stored in the
4363** user-specific tmp directory, create the ID if it's not there already
4364*/
4365static int proxyGetHostID(char *pHostID, int *pError){
4366 int fd;
4367 char path[MAXPATHLEN];
4368 size_t len;
4369 int rc=SQLITE_OK;
4370
4371 proxyGetHostIDPath(path, MAXPATHLEN);
4372 /* try to create the host ID file, if it already exists read the contents */
4373 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4374 if( fd<0 ){
4375 int err=errno;
4376
4377 if( err!=EEXIST ){
4378#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4379 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4380 path, strerror(err));
4381#endif
4382 return SQLITE_PERM;
4383 }
4384 /* couldn't create the file, read it instead */
4385 fd = open(path, O_RDONLY|O_EXCL);
4386 if( fd<0 ){
4387#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4388 int err = errno;
4389 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4390 path, strerror(err));
4391#endif
4392 return SQLITE_PERM;
4393 }
4394 len = pread(fd, pHostID, HOSTIDLEN, 0);
4395 if( len<0 ){
4396 *pError = errno;
4397 rc = SQLITE_IOERR_READ;
4398 }else if( len<HOSTIDLEN ){
4399 *pError = 0;
4400 rc = SQLITE_IOERR_SHORT_READ;
4401 }
4402 close(fd); /* silently leak the fd if it fails */
4403 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4404 return rc;
4405 }else{
4406 /* we're creating the host ID file (use a random string of bytes) */
4407 proxyGenerateHostID(pHostID);
4408 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4409 if( len<0 ){
4410 *pError = errno;
4411 rc = SQLITE_IOERR_WRITE;
4412 }else if( len<HOSTIDLEN ){
4413 *pError = 0;
4414 rc = SQLITE_IOERR_WRITE;
4415 }
4416 close(fd); /* silently leak the fd if it fails */
4417 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4418 return rc;
4419 }
4420}
4421
4422static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4423 int len;
4424 int dbLen;
4425 int i;
4426
4427#ifdef LOCKPROXYDIR
4428 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4429#else
4430# ifdef _CS_DARWIN_USER_TEMP_DIR
4431 {
4432 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4433 len = strlcat(lPath, "sqliteplocks", maxLen);
4434 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4435 /* if mkdir fails, handle as lock file creation failure */
drh715ff302008-12-03 22:32:44 +00004436# ifdef SQLITE_DEBUG
danielk197750c55a92009-05-08 11:34:37 +00004437 int err = errno;
drh715ff302008-12-03 22:32:44 +00004438 if( err!=EEXIST ){
4439 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4440 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4441 }
4442# endif
4443 }else{
4444 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4445 }
4446
4447 }
4448# else
4449 len = strlcpy(lPath, "/tmp/", maxLen);
4450# endif
4451#endif
4452
4453 if( lPath[len-1]!='/' ){
4454 len = strlcat(lPath, "/", maxLen);
4455 }
4456
4457 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004458 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004459 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4460 char c = dbPath[i];
4461 lPath[i+len] = (c=='/')?'_':c;
4462 }
4463 lPath[i+len]='\0';
4464 strlcat(lPath, ":auto:", maxLen);
4465 return SQLITE_OK;
4466}
4467
4468/*
4469** Create a new VFS file descriptor (stored in memory obtained from
4470** sqlite3_malloc) and open the file named "path" in the file descriptor.
4471**
4472** The caller is responsible not only for closing the file descriptor
4473** but also for freeing the memory associated with the file descriptor.
4474*/
4475static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4476 int fd;
4477 int dirfd = -1;
4478 unixFile *pNew;
4479 int rc = SQLITE_OK;
4480 sqlite3_vfs dummyVfs;
4481
4482 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4483 if( fd<0 ){
4484 return SQLITE_CANTOPEN;
4485 }
4486
4487 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4488 if( pNew==NULL ){
4489 rc = SQLITE_NOMEM;
4490 goto end_create_proxy;
4491 }
4492 memset(pNew, 0, sizeof(unixFile));
4493
drh1875f7a2008-12-08 18:19:17 +00004494 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004495 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4496 if( rc==SQLITE_OK ){
4497 *ppFile = pNew;
4498 return SQLITE_OK;
4499 }
4500end_create_proxy:
4501 close(fd); /* silently leak fd if error, we're already in error */
4502 sqlite3_free(pNew);
4503 return rc;
4504}
4505
4506/* takes the conch by taking a shared lock and read the contents conch, if
4507** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4508** lockPath means that the lockPath in the conch file will be used if the
4509** host IDs match, or a new lock path will be generated automatically
4510** and written to the conch file.
4511*/
4512static int proxyTakeConch(unixFile *pFile){
4513 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4514
4515 if( pCtx->conchHeld>0 ){
4516 return SQLITE_OK;
4517 }else{
4518 unixFile *conchFile = pCtx->conchFile;
4519 char testValue[CONCHLEN];
4520 char conchValue[CONCHLEN];
4521 char lockPath[MAXPATHLEN];
4522 char *tLockPath = NULL;
4523 int rc = SQLITE_OK;
4524 int readRc = SQLITE_OK;
4525 int syncPerms = 0;
4526
4527 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4528 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4529
4530 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4531 if( rc==SQLITE_OK ){
4532 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004533 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004534 rc = proxyGetHostID(testValue, &pError);
4535 if( (rc&0xff)==SQLITE_IOERR ){
4536 pFile->lastErrno = pError;
4537 }
4538 if( pCtx->lockProxyPath ){
4539 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4540 }
4541 }
4542 if( rc!=SQLITE_OK ){
4543 goto end_takeconch;
4544 }
4545
4546 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4547 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4548 if( readRc!=SQLITE_OK ){
4549 if( (rc&0xff)==SQLITE_IOERR ){
4550 pFile->lastErrno = conchFile->lastErrno;
4551 }
4552 rc = readRc;
4553 goto end_takeconch;
4554 }
4555 /* if the conch has data compare the contents */
4556 if( !pCtx->lockProxyPath ){
4557 /* for auto-named local lock file, just check the host ID and we'll
4558 ** use the local lock file path that's already in there */
4559 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4560 tLockPath = (char *)&conchValue[HOSTIDLEN];
4561 goto end_takeconch;
4562 }
4563 }else{
4564 /* we've got the conch if conchValue matches our path and host ID */
4565 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4566 goto end_takeconch;
4567 }
4568 }
4569 }else{
4570 /* a short read means we're "creating" the conch (even though it could
4571 ** have been user-intervention), if we acquire the exclusive lock,
4572 ** we'll try to match the current on-disk permissions of the database
4573 */
4574 syncPerms = 1;
4575 }
4576
4577 /* either conch was emtpy or didn't match */
4578 if( !pCtx->lockProxyPath ){
4579 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4580 tLockPath = lockPath;
4581 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4582 }
4583
4584 /* update conch with host and path (this will fail if other process
4585 ** has a shared lock already) */
4586 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4587 if( rc==SQLITE_OK ){
4588 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4589 if( rc==SQLITE_OK && syncPerms ){
4590 struct stat buf;
4591 int err = fstat(pFile->h, &buf);
4592 if( err==0 ){
4593 /* try to match the database file permissions, ignore failure */
4594#ifndef SQLITE_PROXY_DEBUG
4595 fchmod(conchFile->h, buf.st_mode);
4596#else
4597 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4598 int code = errno;
4599 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4600 buf.st_mode, code, strerror(code));
4601 } else {
4602 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4603 }
4604 }else{
4605 int code = errno;
4606 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4607 err, code, strerror(code));
4608#endif
4609 }
4610 }
4611 }
4612 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4613
4614end_takeconch:
4615 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4616 if( rc==SQLITE_OK && pFile->openFlags ){
4617 if( pFile->h>=0 ){
4618#ifdef STRICT_CLOSE_ERROR
4619 if( close(pFile->h) ){
4620 pFile->lastErrno = errno;
4621 return SQLITE_IOERR_CLOSE;
4622 }
4623#else
4624 close(pFile->h); /* silently leak fd if fail */
4625#endif
4626 }
4627 pFile->h = -1;
4628 int fd = open(pCtx->dbPath, pFile->openFlags,
4629 SQLITE_DEFAULT_FILE_PERMISSIONS);
4630 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4631 if( fd>=0 ){
4632 pFile->h = fd;
4633 }else{
drh1875f7a2008-12-08 18:19:17 +00004634 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4635 during locking */
drh715ff302008-12-03 22:32:44 +00004636 }
4637 }
4638 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4639 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004640 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004641 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4642 }
4643 if( rc==SQLITE_OK ){
4644 pCtx->conchHeld = 1;
4645
4646 if( tLockPath ){
4647 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4648 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4649 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4650 pCtx->lockProxyPath;
4651 }
4652 }
4653 } else {
4654 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4655 }
4656 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4657 return rc;
4658 }
4659}
4660
4661/*
4662** If pFile holds a lock on a conch file, then release that lock.
4663*/
4664static int proxyReleaseConch(unixFile *pFile){
4665 int rc; /* Subroutine return code */
4666 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4667 unixFile *conchFile; /* Name of the conch file */
4668
4669 pCtx = (proxyLockingContext *)pFile->lockingContext;
4670 conchFile = pCtx->conchFile;
4671 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4672 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4673 getpid());
4674 pCtx->conchHeld = 0;
4675 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4676 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4677 (rc==SQLITE_OK ? "ok" : "failed"));
4678 return rc;
4679}
4680
4681/*
4682** Given the name of a database file, compute the name of its conch file.
4683** Store the conch filename in memory obtained from sqlite3_malloc().
4684** Make *pConchPath point to the new name. Return SQLITE_OK on success
4685** or SQLITE_NOMEM if unable to obtain memory.
4686**
4687** The caller is responsible for ensuring that the allocated memory
4688** space is eventually freed.
4689**
4690** *pConchPath is set to NULL if a memory allocation error occurs.
4691*/
4692static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4693 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004694 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004695 char *conchPath; /* buffer in which to construct conch name */
4696
4697 /* Allocate space for the conch filename and initialize the name to
4698 ** the name of the original database file. */
4699 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4700 if( conchPath==0 ){
4701 return SQLITE_NOMEM;
4702 }
4703 memcpy(conchPath, dbPath, len+1);
4704
4705 /* now insert a "." before the last / character */
4706 for( i=(len-1); i>=0; i-- ){
4707 if( conchPath[i]=='/' ){
4708 i++;
4709 break;
4710 }
4711 }
4712 conchPath[i]='.';
4713 while ( i<len ){
4714 conchPath[i+1]=dbPath[i];
4715 i++;
4716 }
4717
4718 /* append the "-conch" suffix to the file */
4719 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004720 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004721
4722 return SQLITE_OK;
4723}
4724
4725
4726/* Takes a fully configured proxy locking-style unix file and switches
4727** the local lock file path
4728*/
4729static int switchLockProxyPath(unixFile *pFile, const char *path) {
4730 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4731 char *oldPath = pCtx->lockProxyPath;
4732 int rc = SQLITE_OK;
4733
4734 if( pFile->locktype!=NO_LOCK ){
4735 return SQLITE_BUSY;
4736 }
4737
4738 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4739 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4740 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4741 return SQLITE_OK;
4742 }else{
4743 unixFile *lockProxy = pCtx->lockProxy;
4744 pCtx->lockProxy=NULL;
4745 pCtx->conchHeld = 0;
4746 if( lockProxy!=NULL ){
4747 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4748 if( rc ) return rc;
4749 sqlite3_free(lockProxy);
4750 }
4751 sqlite3_free(oldPath);
4752 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4753 }
4754
4755 return rc;
4756}
4757
4758/*
4759** pFile is a file that has been opened by a prior xOpen call. dbPath
4760** is a string buffer at least MAXPATHLEN+1 characters in size.
4761**
4762** This routine find the filename associated with pFile and writes it
4763** int dbPath.
4764*/
4765static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004766#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004767 if( pFile->pMethod == &afpIoMethods ){
4768 /* afp style keeps a reference to the db path in the filePath field
4769 ** of the struct */
drhea678832008-12-10 19:26:22 +00004770 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004771 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4772 }else
4773#endif
4774 if( pFile->pMethod == &dotlockIoMethods ){
4775 /* dot lock style uses the locking context to store the dot lock
4776 ** file path */
4777 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4778 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4779 }else{
4780 /* all other styles use the locking context to store the db file path */
4781 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4782 strcpy(dbPath, (char *)pFile->lockingContext);
4783 }
4784 return SQLITE_OK;
4785}
4786
4787/*
4788** Takes an already filled in unix file and alters it so all file locking
4789** will be performed on the local proxy lock file. The following fields
4790** are preserved in the locking context so that they can be restored and
4791** the unix structure properly cleaned up at close time:
4792** ->lockingContext
4793** ->pMethod
4794*/
4795static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4796 proxyLockingContext *pCtx;
4797 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4798 char *lockPath=NULL;
4799 int rc = SQLITE_OK;
4800
4801 if( pFile->locktype!=NO_LOCK ){
4802 return SQLITE_BUSY;
4803 }
4804 proxyGetDbPathForUnixFile(pFile, dbPath);
4805 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4806 lockPath=NULL;
4807 }else{
4808 lockPath=(char *)path;
4809 }
4810
4811 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4812 (lockPath ? lockPath : ":auto:"), getpid());
4813
4814 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4815 if( pCtx==0 ){
4816 return SQLITE_NOMEM;
4817 }
4818 memset(pCtx, 0, sizeof(*pCtx));
4819
4820 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4821 if( rc==SQLITE_OK ){
4822 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4823 }
4824 if( rc==SQLITE_OK && lockPath ){
4825 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4826 }
4827
4828 if( rc==SQLITE_OK ){
4829 /* all memory is allocated, proxys are created and assigned,
4830 ** switch the locking context and pMethod then return.
4831 */
4832 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4833 pCtx->oldLockingContext = pFile->lockingContext;
4834 pFile->lockingContext = pCtx;
4835 pCtx->pOldMethod = pFile->pMethod;
4836 pFile->pMethod = &proxyIoMethods;
4837 }else{
4838 if( pCtx->conchFile ){
4839 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4840 if( rc ) return rc;
4841 sqlite3_free(pCtx->conchFile);
4842 }
4843 sqlite3_free(pCtx->conchFilePath);
4844 sqlite3_free(pCtx);
4845 }
4846 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4847 (rc==SQLITE_OK ? "ok" : "failed"));
4848 return rc;
4849}
4850
4851
4852/*
4853** This routine handles sqlite3_file_control() calls that are specific
4854** to proxy locking.
4855*/
4856static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4857 switch( op ){
4858 case SQLITE_GET_LOCKPROXYFILE: {
4859 unixFile *pFile = (unixFile*)id;
4860 if( pFile->pMethod == &proxyIoMethods ){
4861 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4862 proxyTakeConch(pFile);
4863 if( pCtx->lockProxyPath ){
4864 *(const char **)pArg = pCtx->lockProxyPath;
4865 }else{
4866 *(const char **)pArg = ":auto: (not held)";
4867 }
4868 } else {
4869 *(const char **)pArg = NULL;
4870 }
4871 return SQLITE_OK;
4872 }
4873 case SQLITE_SET_LOCKPROXYFILE: {
4874 unixFile *pFile = (unixFile*)id;
4875 int rc = SQLITE_OK;
4876 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4877 if( pArg==NULL || (const char *)pArg==0 ){
4878 if( isProxyStyle ){
4879 /* turn off proxy locking - not supported */
4880 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4881 }else{
4882 /* turn off proxy locking - already off - NOOP */
4883 rc = SQLITE_OK;
4884 }
4885 }else{
4886 const char *proxyPath = (const char *)pArg;
4887 if( isProxyStyle ){
4888 proxyLockingContext *pCtx =
4889 (proxyLockingContext*)pFile->lockingContext;
4890 if( !strcmp(pArg, ":auto:")
4891 || (pCtx->lockProxyPath &&
4892 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4893 ){
4894 rc = SQLITE_OK;
4895 }else{
4896 rc = switchLockProxyPath(pFile, proxyPath);
4897 }
4898 }else{
4899 /* turn on proxy file locking */
4900 rc = proxyTransformUnixFile(pFile, proxyPath);
4901 }
4902 }
4903 return rc;
4904 }
4905 default: {
4906 assert( 0 ); /* The call assures that only valid opcodes are sent */
4907 }
4908 }
4909 /*NOTREACHED*/
4910 return SQLITE_ERROR;
4911}
4912
4913/*
4914** Within this division (the proxying locking implementation) the procedures
4915** above this point are all utilities. The lock-related methods of the
4916** proxy-locking sqlite3_io_method object follow.
4917*/
4918
4919
4920/*
4921** This routine checks if there is a RESERVED lock held on the specified
4922** file by this or any other process. If such a lock is held, set *pResOut
4923** to a non-zero value otherwise *pResOut is set to zero. The return value
4924** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4925*/
4926static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4927 unixFile *pFile = (unixFile*)id;
4928 int rc = proxyTakeConch(pFile);
4929 if( rc==SQLITE_OK ){
4930 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4931 unixFile *proxy = pCtx->lockProxy;
4932 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4933 }
4934 return rc;
4935}
4936
4937/*
4938** Lock the file with the lock specified by parameter locktype - one
4939** of the following:
4940**
4941** (1) SHARED_LOCK
4942** (2) RESERVED_LOCK
4943** (3) PENDING_LOCK
4944** (4) EXCLUSIVE_LOCK
4945**
4946** Sometimes when requesting one lock state, additional lock states
4947** are inserted in between. The locking might fail on one of the later
4948** transitions leaving the lock state different from what it started but
4949** still short of its goal. The following chart shows the allowed
4950** transitions and the inserted intermediate states:
4951**
4952** UNLOCKED -> SHARED
4953** SHARED -> RESERVED
4954** SHARED -> (PENDING) -> EXCLUSIVE
4955** RESERVED -> (PENDING) -> EXCLUSIVE
4956** PENDING -> EXCLUSIVE
4957**
4958** This routine will only increase a lock. Use the sqlite3OsUnlock()
4959** routine to lower a locking level.
4960*/
4961static int proxyLock(sqlite3_file *id, int locktype) {
4962 unixFile *pFile = (unixFile*)id;
4963 int rc = proxyTakeConch(pFile);
4964 if( rc==SQLITE_OK ){
4965 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4966 unixFile *proxy = pCtx->lockProxy;
4967 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4968 pFile->locktype = proxy->locktype;
4969 }
4970 return rc;
4971}
4972
4973
4974/*
4975** Lower the locking level on file descriptor pFile to locktype. locktype
4976** must be either NO_LOCK or SHARED_LOCK.
4977**
4978** If the locking level of the file descriptor is already at or below
4979** the requested locking level, this routine is a no-op.
4980*/
4981static int proxyUnlock(sqlite3_file *id, int locktype) {
4982 unixFile *pFile = (unixFile*)id;
4983 int rc = proxyTakeConch(pFile);
4984 if( rc==SQLITE_OK ){
4985 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4986 unixFile *proxy = pCtx->lockProxy;
4987 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
4988 pFile->locktype = proxy->locktype;
4989 }
4990 return rc;
4991}
4992
4993/*
4994** Close a file that uses proxy locks.
4995*/
4996static int proxyClose(sqlite3_file *id) {
4997 if( id ){
4998 unixFile *pFile = (unixFile*)id;
4999 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5000 unixFile *lockProxy = pCtx->lockProxy;
5001 unixFile *conchFile = pCtx->conchFile;
5002 int rc = SQLITE_OK;
5003
5004 if( lockProxy ){
5005 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5006 if( rc ) return rc;
5007 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5008 if( rc ) return rc;
5009 sqlite3_free(lockProxy);
5010 pCtx->lockProxy = 0;
5011 }
5012 if( conchFile ){
5013 if( pCtx->conchHeld ){
5014 rc = proxyReleaseConch(pFile);
5015 if( rc ) return rc;
5016 }
5017 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5018 if( rc ) return rc;
5019 sqlite3_free(conchFile);
5020 }
5021 sqlite3_free(pCtx->lockProxyPath);
5022 sqlite3_free(pCtx->conchFilePath);
5023 sqlite3_free(pCtx->dbPath);
5024 /* restore the original locking context and pMethod then close it */
5025 pFile->lockingContext = pCtx->oldLockingContext;
5026 pFile->pMethod = pCtx->pOldMethod;
5027 sqlite3_free(pCtx);
5028 return pFile->pMethod->xClose(id);
5029 }
5030 return SQLITE_OK;
5031}
5032
5033
5034
drhd2cb50b2009-01-09 21:41:17 +00005035#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005036/*
5037** The proxy locking style is intended for use with AFP filesystems.
5038** And since AFP is only supported on MacOSX, the proxy locking is also
5039** restricted to MacOSX.
5040**
5041**
5042******************* End of the proxy lock implementation **********************
5043******************************************************************************/
5044
drh734c9862008-11-28 15:37:20 +00005045/*
danielk1977e339d652008-06-28 11:23:00 +00005046** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005047**
5048** This routine registers all VFS implementations for unix-like operating
5049** systems. This routine, and the sqlite3_os_end() routine that follows,
5050** should be the only routines in this file that are visible from other
5051** files.
drh6b9d6dd2008-12-03 19:34:47 +00005052**
5053** This routine is called once during SQLite initialization and by a
5054** single thread. The memory allocation and mutex subsystems have not
5055** necessarily been initialized when this routine is called, and so they
5056** should not be used.
drh153c62c2007-08-24 03:51:33 +00005057*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005058int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005059 /*
5060 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005061 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5062 ** to the "finder" function. (pAppData is a pointer to a pointer because
5063 ** silly C90 rules prohibit a void* from being cast to a function pointer
5064 ** and so we have to go through the intermediate pointer to avoid problems
5065 ** when compiling with -pedantic-errors on GCC.)
5066 **
5067 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005068 ** finder-function. The finder-function returns a pointer to the
5069 ** sqlite_io_methods object that implements the desired locking
5070 ** behaviors. See the division above that contains the IOMETHODS
5071 ** macro for addition information on finder-functions.
5072 **
5073 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5074 ** object. But the "autolockIoFinder" available on MacOSX does a little
5075 ** more than that; it looks at the filesystem type that hosts the
5076 ** database file and tries to choose an locking method appropriate for
5077 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005078 */
drh7708e972008-11-29 00:56:52 +00005079 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005080 1, /* iVersion */ \
5081 sizeof(unixFile), /* szOsFile */ \
5082 MAX_PATHNAME, /* mxPathname */ \
5083 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005084 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005085 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005086 unixOpen, /* xOpen */ \
5087 unixDelete, /* xDelete */ \
5088 unixAccess, /* xAccess */ \
5089 unixFullPathname, /* xFullPathname */ \
5090 unixDlOpen, /* xDlOpen */ \
5091 unixDlError, /* xDlError */ \
5092 unixDlSym, /* xDlSym */ \
5093 unixDlClose, /* xDlClose */ \
5094 unixRandomness, /* xRandomness */ \
5095 unixSleep, /* xSleep */ \
5096 unixCurrentTime, /* xCurrentTime */ \
5097 unixGetLastError /* xGetLastError */ \
5098 }
5099
drh6b9d6dd2008-12-03 19:34:47 +00005100 /*
5101 ** All default VFSes for unix are contained in the following array.
5102 **
5103 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5104 ** by the SQLite core when the VFS is registered. So the following
5105 ** array cannot be const.
5106 */
danielk1977e339d652008-06-28 11:23:00 +00005107 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005108#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005109 UNIXVFS("unix", autolockIoFinder ),
5110#else
5111 UNIXVFS("unix", posixIoFinder ),
5112#endif
5113 UNIXVFS("unix-none", nolockIoFinder ),
5114 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005115#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005116 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005117#endif
5118#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005119 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005120#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005121 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005122#endif
chw78a13182009-04-07 05:35:03 +00005123#endif
drhd2cb50b2009-01-09 21:41:17 +00005124#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005125 UNIXVFS("unix-afp", afpIoFinder ),
5126 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005127#endif
drh153c62c2007-08-24 03:51:33 +00005128 };
drh6b9d6dd2008-12-03 19:34:47 +00005129 unsigned int i; /* Loop counter */
5130
5131 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005132 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005133 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005134 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005135 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005136}
danielk1977e339d652008-06-28 11:23:00 +00005137
5138/*
drh6b9d6dd2008-12-03 19:34:47 +00005139** Shutdown the operating system interface.
5140**
5141** Some operating systems might need to do some cleanup in this routine,
5142** to release dynamically allocated objects. But not on unix.
5143** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005144*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005145int sqlite3_os_end(void){
5146 return SQLITE_OK;
5147}
drhdce8bdb2007-08-16 13:01:44 +00005148
danielk197729bafea2008-06-26 10:41:19 +00005149#endif /* SQLITE_OS_UNIX */