blob: dd746e6db61ea5fe0b28c7c75b8edfba181af674 [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**
danielk197709480a92009-02-09 05:32:32 +000046** $Id: os_unix.c,v 1.240 2009/02/09 05:32:32 danielk1977 Exp $
drhbbd42a62004-05-22 17:41:58 +000047*/
drhbbd42a62004-05-22 17:41:58 +000048#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000049#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000050
danielk1977e339d652008-06-28 11:23:00 +000051/*
drh6b9d6dd2008-12-03 19:34:47 +000052** There are various methods for file locking used for concurrency
53** control:
danielk1977e339d652008-06-28 11:23:00 +000054**
drh734c9862008-11-28 15:37:20 +000055** 1. POSIX locking (the default),
56** 2. No locking,
57** 3. Dot-file locking,
58** 4. flock() locking,
59** 5. AFP locking (OSX only),
60** 6. Named POSIX semaphores (VXWorks only),
61** 7. proxy locking. (OSX only)
62**
63** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
64** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
65** selection of the appropriate locking style based on the filesystem
66** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000067*/
drh40bbb0a2008-09-23 10:23:26 +000068#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000069# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000070# define SQLITE_ENABLE_LOCKING_STYLE 1
71# else
72# define SQLITE_ENABLE_LOCKING_STYLE 0
73# endif
74#endif
drhbfe66312006-10-03 17:40:40 +000075
drh9cbe6352005-11-29 03:13:21 +000076/*
drh6c7d5c52008-11-21 20:32:33 +000077** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000078** vxworks, or 0 otherwise.
79*/
drh6c7d5c52008-11-21 20:32:33 +000080#ifndef OS_VXWORKS
81# if defined(__RTP__) || defined(_WRS_KERNEL)
82# define OS_VXWORKS 1
83# else
84# define OS_VXWORKS 0
85# endif
danielk1977397d65f2008-11-19 11:35:39 +000086#endif
87
88/*
drh9cbe6352005-11-29 03:13:21 +000089** These #defines should enable >2GB file support on Posix if the
90** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000091** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000092**
93** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
94** on the compiler command line. This is necessary if you are compiling
95** on a recent machine (ex: RedHat 7.2) but you want your code to work
96** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
97** without this option, LFS is enable. But LFS does not exist in the kernel
98** in RedHat 6.0, so the code won't work. Hence, for maximum binary
99** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000100**
101** The previous paragraph was written in 2005. (This paragraph is written
102** on 2008-11-28.) These days, all Linux kernels support large files, so
103** you should probably leave LFS enabled. But some embedded platforms might
104** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000105*/
106#ifndef SQLITE_DISABLE_LFS
107# define _LARGE_FILE 1
108# ifndef _FILE_OFFSET_BITS
109# define _FILE_OFFSET_BITS 64
110# endif
111# define _LARGEFILE_SOURCE 1
112#endif
drhbbd42a62004-05-22 17:41:58 +0000113
drh9cbe6352005-11-29 03:13:21 +0000114/*
115** standard include files.
116*/
117#include <sys/types.h>
118#include <sys/stat.h>
119#include <fcntl.h>
120#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000122#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000123#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000124
drh40bbb0a2008-09-23 10:23:26 +0000125#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000127# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <semaphore.h>
129# include <limits.h>
130# else
drh9b35ea62008-11-29 02:20:26 +0000131# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# include <sys/param.h>
133# include <sys/mount.h>
134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
137/*
drhf1a221e2006-01-15 17:27:17 +0000138** If we are to be thread-safe, include the pthreads header and define
139** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000140*/
drhd677b3d2007-08-20 22:48:41 +0000141#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000142# include <pthread.h>
143# define SQLITE_UNIX_THREADS 1
144#endif
145
146/*
147** Default permissions when creating a new file
148*/
149#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
150# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
151#endif
152
danielk1977b4b47412007-08-17 15:53:36 +0000153/*
aswiftaebf4132008-11-21 00:10:35 +0000154 ** Default permissions when creating auto proxy dir
155 */
156#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
157# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
158#endif
159
160/*
danielk1977b4b47412007-08-17 15:53:36 +0000161** Maximum supported path-length.
162*/
163#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000164
drh734c9862008-11-28 15:37:20 +0000165/*
drh734c9862008-11-28 15:37:20 +0000166** Only set the lastErrno if the error code is a real error and not
167** a normal expected return code of SQLITE_BUSY or SQLITE_OK
168*/
169#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
170
drh9cbe6352005-11-29 03:13:21 +0000171
172/*
drh9b35ea62008-11-29 02:20:26 +0000173** The unixFile structure is subclass of sqlite3_file specific to the unix
174** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000175*/
drh054889e2005-11-30 03:20:31 +0000176typedef struct unixFile unixFile;
177struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000178 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000179 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
180 struct unixLockInfo *pLock; /* Info about locks on this inode */
181 int h; /* The file descriptor */
182 int dirfd; /* File descriptor for the directory */
183 unsigned char locktype; /* The type of lock held on this fd */
184 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000185 void *lockingContext; /* Locking style specific state */
drh734c9862008-11-28 15:37:20 +0000186 int openFlags; /* The flags specified at open */
187#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000188 pthread_t tid; /* The thread that "owns" this unixFile */
189#endif
190#if OS_VXWORKS
191 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000192 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000193#endif
drh8f941bc2009-01-14 23:03:40 +0000194#ifndef NDEBUG
195 /* The next group of variables are used to track whether or not the
196 ** transaction counter in bytes 24-27 of database files are updated
197 ** whenever any part of the database changes. An assertion fault will
198 ** occur if a file is updated without also updating the transaction
199 ** counter. This test is made to avoid new problems similar to the
200 ** one described by ticket #3584.
201 */
202 unsigned char transCntrChng; /* True if the transaction counter changed */
203 unsigned char dbUpdate; /* True if any part of database file changed */
204 unsigned char inNormalWrite; /* True if in a normal write operation */
205#endif
danielk1977967a4a12007-08-20 14:23:44 +0000206#ifdef SQLITE_TEST
207 /* In test mode, increase the size of this structure a bit so that
208 ** it is larger than the struct CrashFile defined in test6.c.
209 */
210 char aPadding[32];
211#endif
drh9cbe6352005-11-29 03:13:21 +0000212};
213
drh0ccebe72005-06-07 22:22:50 +0000214/*
drh198bf392006-01-06 21:52:49 +0000215** Include code that is common to all os_*.c files
216*/
217#include "os_common.h"
218
219/*
drh0ccebe72005-06-07 22:22:50 +0000220** Define various macros that are missing from some systems.
221*/
drhbbd42a62004-05-22 17:41:58 +0000222#ifndef O_LARGEFILE
223# define O_LARGEFILE 0
224#endif
225#ifdef SQLITE_DISABLE_LFS
226# undef O_LARGEFILE
227# define O_LARGEFILE 0
228#endif
229#ifndef O_NOFOLLOW
230# define O_NOFOLLOW 0
231#endif
232#ifndef O_BINARY
233# define O_BINARY 0
234#endif
235
236/*
237** The DJGPP compiler environment looks mostly like Unix, but it
238** lacks the fcntl() system call. So redefine fcntl() to be something
239** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000240** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000241*/
242#ifdef __DJGPP__
243# define fcntl(A,B,C) 0
244#endif
245
246/*
drh2b4b5962005-06-15 17:47:55 +0000247** The threadid macro resolves to the thread-id or to 0. Used for
248** testing and debugging only.
249*/
drhd677b3d2007-08-20 22:48:41 +0000250#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000251#define threadid pthread_self()
252#else
253#define threadid 0
254#endif
255
danielk197713adf8a2004-06-03 16:08:41 +0000256
drh107886a2008-11-21 22:21:50 +0000257/*
258** Helper functions to obtain and relinquish the global mutex.
259*/
260static void unixEnterMutex(void){
261 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
262}
263static void unixLeaveMutex(void){
264 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
265}
266
drh734c9862008-11-28 15:37:20 +0000267
268#ifdef SQLITE_DEBUG
269/*
270** Helper function for printing out trace information from debugging
271** binaries. This returns the string represetation of the supplied
272** integer lock-type.
273*/
274static const char *locktypeName(int locktype){
275 switch( locktype ){
276 case NO_LOCK: return "NONE";
277 case SHARED_LOCK: return "SHARED";
278 case RESERVED_LOCK: return "RESERVED";
279 case PENDING_LOCK: return "PENDING";
280 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
281 }
282 return "ERROR";
283}
284#endif
285
286#ifdef SQLITE_LOCK_TRACE
287/*
288** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000289**
drh734c9862008-11-28 15:37:20 +0000290** This routine is used for troubleshooting locks on multithreaded
291** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
292** command-line option on the compiler. This code is normally
293** turned off.
294*/
295static int lockTrace(int fd, int op, struct flock *p){
296 char *zOpName, *zType;
297 int s;
298 int savedErrno;
299 if( op==F_GETLK ){
300 zOpName = "GETLK";
301 }else if( op==F_SETLK ){
302 zOpName = "SETLK";
303 }else{
304 s = fcntl(fd, op, p);
305 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
306 return s;
307 }
308 if( p->l_type==F_RDLCK ){
309 zType = "RDLCK";
310 }else if( p->l_type==F_WRLCK ){
311 zType = "WRLCK";
312 }else if( p->l_type==F_UNLCK ){
313 zType = "UNLCK";
314 }else{
315 assert( 0 );
316 }
317 assert( p->l_whence==SEEK_SET );
318 s = fcntl(fd, op, p);
319 savedErrno = errno;
320 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
321 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
322 (int)p->l_pid, s);
323 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
324 struct flock l2;
325 l2 = *p;
326 fcntl(fd, F_GETLK, &l2);
327 if( l2.l_type==F_RDLCK ){
328 zType = "RDLCK";
329 }else if( l2.l_type==F_WRLCK ){
330 zType = "WRLCK";
331 }else if( l2.l_type==F_UNLCK ){
332 zType = "UNLCK";
333 }else{
334 assert( 0 );
335 }
336 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
337 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
338 }
339 errno = savedErrno;
340 return s;
341}
342#define fcntl lockTrace
343#endif /* SQLITE_LOCK_TRACE */
344
345
346
347/*
348** This routine translates a standard POSIX errno code into something
349** useful to the clients of the sqlite3 functions. Specifically, it is
350** intended to translate a variety of "try again" errors into SQLITE_BUSY
351** and a variety of "please close the file descriptor NOW" errors into
352** SQLITE_IOERR
353**
354** Errors during initialization of locks, or file system support for locks,
355** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
356*/
357static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
358 switch (posixError) {
359 case 0:
360 return SQLITE_OK;
361
362 case EAGAIN:
363 case ETIMEDOUT:
364 case EBUSY:
365 case EINTR:
366 case ENOLCK:
367 /* random NFS retry error, unless during file system support
368 * introspection, in which it actually means what it says */
369 return SQLITE_BUSY;
370
371 case EACCES:
372 /* EACCES is like EAGAIN during locking operations, but not any other time*/
373 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
374 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
375 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
376 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
377 return SQLITE_BUSY;
378 }
379 /* else fall through */
380 case EPERM:
381 return SQLITE_PERM;
382
383 case EDEADLK:
384 return SQLITE_IOERR_BLOCKED;
385
386#if EOPNOTSUPP!=ENOTSUP
387 case EOPNOTSUPP:
388 /* something went terribly awry, unless during file system support
389 * introspection, in which it actually means what it says */
390#endif
391#ifdef ENOTSUP
392 case ENOTSUP:
393 /* invalid fd, unless during file system support introspection, in which
394 * it actually means what it says */
395#endif
396 case EIO:
397 case EBADF:
398 case EINVAL:
399 case ENOTCONN:
400 case ENODEV:
401 case ENXIO:
402 case ENOENT:
403 case ESTALE:
404 case ENOSYS:
405 /* these should force the client to close the file and reconnect */
406
407 default:
408 return sqliteIOErr;
409 }
410}
411
412
413
414/******************************************************************************
415****************** Begin Unique File ID Utility Used By VxWorks ***************
416**
417** On most versions of unix, we can get a unique ID for a file by concatenating
418** the device number and the inode number. But this does not work on VxWorks.
419** On VxWorks, a unique file id must be based on the canonical filename.
420**
421** A pointer to an instance of the following structure can be used as a
422** unique file ID in VxWorks. Each instance of this structure contains
423** a copy of the canonical filename. There is also a reference count.
424** The structure is reclaimed when the number of pointers to it drops to
425** zero.
426**
427** There are never very many files open at one time and lookups are not
428** a performance-critical path, so it is sufficient to put these
429** structures on a linked list.
430*/
431struct vxworksFileId {
432 struct vxworksFileId *pNext; /* Next in a list of them all */
433 int nRef; /* Number of references to this one */
434 int nName; /* Length of the zCanonicalName[] string */
435 char *zCanonicalName; /* Canonical filename */
436};
437
438#if OS_VXWORKS
439/*
drh9b35ea62008-11-29 02:20:26 +0000440** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000441** variable:
442*/
443static struct vxworksFileId *vxworksFileList = 0;
444
445/*
446** Simplify a filename into its canonical form
447** by making the following changes:
448**
449** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000450** * convert /./ into just /
451** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000452**
453** Changes are made in-place. Return the new name length.
454**
455** The original filename is in z[0..n-1]. Return the number of
456** characters in the simplified name.
457*/
458static int vxworksSimplifyName(char *z, int n){
459 int i, j;
460 while( n>1 && z[n-1]=='/' ){ n--; }
461 for(i=j=0; i<n; i++){
462 if( z[i]=='/' ){
463 if( z[i+1]=='/' ) continue;
464 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
465 i += 1;
466 continue;
467 }
468 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
469 while( j>0 && z[j-1]!='/' ){ j--; }
470 if( j>0 ){ j--; }
471 i += 2;
472 continue;
473 }
474 }
475 z[j++] = z[i];
476 }
477 z[j] = 0;
478 return j;
479}
480
481/*
482** Find a unique file ID for the given absolute pathname. Return
483** a pointer to the vxworksFileId object. This pointer is the unique
484** file ID.
485**
486** The nRef field of the vxworksFileId object is incremented before
487** the object is returned. A new vxworksFileId object is created
488** and added to the global list if necessary.
489**
490** If a memory allocation error occurs, return NULL.
491*/
492static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
493 struct vxworksFileId *pNew; /* search key and new file ID */
494 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
495 int n; /* Length of zAbsoluteName string */
496
497 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000498 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000499 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
500 if( pNew==0 ) return 0;
501 pNew->zCanonicalName = (char*)&pNew[1];
502 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
503 n = vxworksSimplifyName(pNew->zCanonicalName, n);
504
505 /* Search for an existing entry that matching the canonical name.
506 ** If found, increment the reference count and return a pointer to
507 ** the existing file ID.
508 */
509 unixEnterMutex();
510 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
511 if( pCandidate->nName==n
512 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
513 ){
514 sqlite3_free(pNew);
515 pCandidate->nRef++;
516 unixLeaveMutex();
517 return pCandidate;
518 }
519 }
520
521 /* No match was found. We will make a new file ID */
522 pNew->nRef = 1;
523 pNew->nName = n;
524 pNew->pNext = vxworksFileList;
525 vxworksFileList = pNew;
526 unixLeaveMutex();
527 return pNew;
528}
529
530/*
531** Decrement the reference count on a vxworksFileId object. Free
532** the object when the reference count reaches zero.
533*/
534static void vxworksReleaseFileId(struct vxworksFileId *pId){
535 unixEnterMutex();
536 assert( pId->nRef>0 );
537 pId->nRef--;
538 if( pId->nRef==0 ){
539 struct vxworksFileId **pp;
540 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
541 assert( *pp==pId );
542 *pp = pId->pNext;
543 sqlite3_free(pId);
544 }
545 unixLeaveMutex();
546}
547#endif /* OS_VXWORKS */
548/*************** End of Unique File ID Utility Used By VxWorks ****************
549******************************************************************************/
550
551
552/******************************************************************************
553*************************** Posix Advisory Locking ****************************
554**
drh9b35ea62008-11-29 02:20:26 +0000555** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000556** section 6.5.2.2 lines 483 through 490 specify that when a process
557** sets or clears a lock, that operation overrides any prior locks set
558** by the same process. It does not explicitly say so, but this implies
559** that it overrides locks set by the same process using a different
560** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000561**
562** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000563** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
564**
565** Suppose ./file1 and ./file2 are really the same file (because
566** one is a hard or symbolic link to the other) then if you set
567** an exclusive lock on fd1, then try to get an exclusive lock
568** on fd2, it works. I would have expected the second lock to
569** fail since there was already a lock on the file due to fd1.
570** But not so. Since both locks came from the same process, the
571** second overrides the first, even though they were on different
572** file descriptors opened on different file names.
573**
drh734c9862008-11-28 15:37:20 +0000574** This means that we cannot use POSIX locks to synchronize file access
575** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000576** to synchronize access for threads in separate processes, but not
577** threads within the same process.
578**
579** To work around the problem, SQLite has to manage file locks internally
580** on its own. Whenever a new database is opened, we have to find the
581** specific inode of the database file (the inode is determined by the
582** st_dev and st_ino fields of the stat structure that fstat() fills in)
583** and check for locks already existing on that inode. When locks are
584** created or removed, we have to look at our own internal record of the
585** locks to see if another thread has previously set a lock on that same
586** inode.
587**
drh9b35ea62008-11-29 02:20:26 +0000588** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
589** For VxWorks, we have to use the alternative unique ID system based on
590** canonical filename and implemented in the previous division.)
591**
danielk1977ad94b582007-08-20 06:44:22 +0000592** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000593** descriptor. It is now a structure that holds the integer file
594** descriptor and a pointer to a structure that describes the internal
595** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000596** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000597** point to the same locking structure. The locking structure keeps
598** a reference count (so we will know when to delete it) and a "cnt"
599** field that tells us its internal lock status. cnt==0 means the
600** file is unlocked. cnt==-1 means the file has an exclusive lock.
601** cnt>0 means there are cnt shared locks on the file.
602**
603** Any attempt to lock or unlock a file first checks the locking
604** structure. The fcntl() system call is only invoked to set a
605** POSIX lock if the internal lock structure transitions between
606** a locked and an unlocked state.
607**
drh734c9862008-11-28 15:37:20 +0000608** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000609**
610** If you close a file descriptor that points to a file that has locks,
611** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000612** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000613** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000614** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000615** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000616** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000617** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000618** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000619** be closed and that list is walked (and cleared) when the last lock
620** clears.
621**
drh9b35ea62008-11-29 02:20:26 +0000622** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000623**
drh9b35ea62008-11-29 02:20:26 +0000624** Many older versions of linux use the LinuxThreads library which is
625** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000626** A cannot be modified or overridden by a different thread B.
627** Only thread A can modify the lock. Locking behavior is correct
628** if the appliation uses the newer Native Posix Thread Library (NPTL)
629** on linux - with NPTL a lock created by thread A can override locks
630** in thread B. But there is no way to know at compile-time which
631** threading library is being used. So there is no way to know at
632** compile-time whether or not thread A can override locks on thread B.
633** We have to do a run-time check to discover the behavior of the
634** current process.
drh5fdae772004-06-29 03:29:00 +0000635**
drh734c9862008-11-28 15:37:20 +0000636** On systems where thread A is unable to modify locks created by
637** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000638** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000639** structure to record this information. And on those systems it
640** is illegal to begin a transaction in one thread and finish it
641** in another. For this latter restriction, there is no work-around.
642** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000643*/
644
645/*
drh6c7d5c52008-11-21 20:32:33 +0000646** Set or check the unixFile.tid field. This field is set when an unixFile
647** is first opened. All subsequent uses of the unixFile verify that the
648** same thread is operating on the unixFile. Some operating systems do
649** not allow locks to be overridden by other threads and that restriction
650** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000651** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000652**
653** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
654** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000655** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000656** or if no locks are held. But the unixFile.pLock field needs to be
657** recomputed because its key includes the thread-id. See the
658** transferOwnership() function below for additional information
659*/
drh734c9862008-11-28 15:37:20 +0000660#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000661# define SET_THREADID(X) (X)->tid = pthread_self()
662# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
663 !pthread_equal((X)->tid, pthread_self()))
664#else
665# define SET_THREADID(X)
666# define CHECK_THREADID(X) 0
667#endif
668
669/*
drhbbd42a62004-05-22 17:41:58 +0000670** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000671** to locate a particular unixOpenCnt structure given its inode. This
672** is the same as the unixLockKey except that the thread ID is omitted.
673*/
674struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000675 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000676#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000677 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000678#else
drh107886a2008-11-21 22:21:50 +0000679 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000680#endif
681};
682
683/*
684** An instance of the following structure serves as the key used
685** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000686**
drh734c9862008-11-28 15:37:20 +0000687** If threads cannot override each others locks (LinuxThreads), then we
688** set the unixLockKey.tid field to the thread ID. If threads can override
689** each others locks (Posix and NPTL) then tid is always set to zero.
690** tid is omitted if we compile without threading support or on an OS
691** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000692*/
drh6c7d5c52008-11-21 20:32:33 +0000693struct unixLockKey {
694 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000695#if SQLITE_THREADSAFE && defined(__linux__)
696 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000697#endif
drhbbd42a62004-05-22 17:41:58 +0000698};
699
700/*
701** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000702** inode. Or, on LinuxThreads, there is one of these structures for
703** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000704**
danielk1977ad94b582007-08-20 06:44:22 +0000705** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000706** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000707** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000708*/
drh6c7d5c52008-11-21 20:32:33 +0000709struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000710 struct unixLockKey lockKey; /* The lookup key */
711 int cnt; /* Number of SHARED locks held */
712 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
713 int nRef; /* Number of pointers to this structure */
714 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
715 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000716};
717
718/*
719** An instance of the following structure is allocated for each open
720** inode. This structure keeps track of the number of locks on that
721** inode. If a close is attempted against an inode that is holding
722** locks, the close is deferred until all locks clear by adding the
723** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000724**
725** TODO: Consider changing this so that there is only a single file
726** descriptor for each open file, even when it is opened multiple times.
727** The close() system call would only occur when the last database
728** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000729*/
drh6c7d5c52008-11-21 20:32:33 +0000730struct unixOpenCnt {
731 struct unixFileId fileId; /* The lookup key */
732 int nRef; /* Number of pointers to this structure */
733 int nLock; /* Number of outstanding locks */
734 int nPending; /* Number of pending close() operations */
735 int *aPending; /* Malloced space holding fd's awaiting a close() */
736#if OS_VXWORKS
737 sem_t *pSem; /* Named POSIX semaphore */
chw97185482008-11-17 08:05:31 +0000738 char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
739#endif
drh6c7d5c52008-11-21 20:32:33 +0000740 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000741};
742
drhda0e7682008-07-30 15:27:54 +0000743/*
drh9b35ea62008-11-29 02:20:26 +0000744** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
745** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000746** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000747** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000748*/
drh6c7d5c52008-11-21 20:32:33 +0000749static struct unixLockInfo *lockList = 0;
750static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000751
drh5fdae772004-06-29 03:29:00 +0000752/*
drh9b35ea62008-11-29 02:20:26 +0000753** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000754** locks.
755**
drh9b35ea62008-11-29 02:20:26 +0000756** 0: No. Threads cannot override each others locks. (LinuxThreads)
757** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000758** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000759**
drh5062d3a2006-01-31 23:03:35 +0000760** On some systems, we know at compile-time if threads can override each
761** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
762** will be set appropriately. On other systems, we have to check at
763** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
764** undefined.
765**
drhf1a221e2006-01-15 17:27:17 +0000766** This variable normally has file scope only. But during testing, we make
767** it a global so that the test code can change its value in order to verify
768** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000769*/
drh715ff302008-12-03 22:32:44 +0000770#if SQLITE_THREADSAFE && defined(__linux__)
771# ifndef SQLITE_THREAD_OVERRIDE_LOCK
772# define SQLITE_THREAD_OVERRIDE_LOCK -1
773# endif
774# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000775int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000776# else
drh5062d3a2006-01-31 23:03:35 +0000777static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000778# endif
drh029b44b2006-01-15 00:13:15 +0000779#endif
drh5fdae772004-06-29 03:29:00 +0000780
781/*
782** This structure holds information passed into individual test
783** threads by the testThreadLockingBehavior() routine.
784*/
785struct threadTestData {
786 int fd; /* File to be locked */
787 struct flock lock; /* The locking operation */
788 int result; /* Result of the locking operation */
789};
790
drh6c7d5c52008-11-21 20:32:33 +0000791#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000792/*
danielk197741a6a612008-11-11 18:34:35 +0000793** This function is used as the main routine for a thread launched by
794** testThreadLockingBehavior(). It tests whether the shared-lock obtained
795** by the main thread in testThreadLockingBehavior() conflicts with a
796** hypothetical write-lock obtained by this thread on the same file.
797**
798** The write-lock is not actually acquired, as this is not possible if
799** the file is open in read-only mode (see ticket #3472).
800*/
drh5fdae772004-06-29 03:29:00 +0000801static void *threadLockingTest(void *pArg){
802 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000803 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000804 return pArg;
805}
drh6c7d5c52008-11-21 20:32:33 +0000806#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000807
drh6c7d5c52008-11-21 20:32:33 +0000808
809#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000810/*
811** This procedure attempts to determine whether or not threads
812** can override each others locks then sets the
813** threadsOverrideEachOthersLocks variable appropriately.
814*/
danielk19774d5238f2006-01-27 06:32:00 +0000815static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000816 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000817 int rc;
818 struct threadTestData d;
819 struct flock l;
820 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000821
822 fd = dup(fd_orig);
823 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000824 memset(&l, 0, sizeof(l));
825 l.l_type = F_RDLCK;
826 l.l_len = 1;
827 l.l_start = 0;
828 l.l_whence = SEEK_SET;
829 rc = fcntl(fd_orig, F_SETLK, &l);
830 if( rc!=0 ) return;
831 memset(&d, 0, sizeof(d));
832 d.fd = fd;
833 d.lock = l;
834 d.lock.l_type = F_WRLCK;
835 pthread_create(&t, 0, threadLockingTest, &d);
836 pthread_join(t, 0);
drh5fdae772004-06-29 03:29:00 +0000837 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000838 if( d.result!=0 ) return;
839 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000840}
drh6c7d5c52008-11-21 20:32:33 +0000841#endif /* SQLITE_THERADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000842
drhbbd42a62004-05-22 17:41:58 +0000843/*
drh6c7d5c52008-11-21 20:32:33 +0000844** Release a unixLockInfo structure previously allocated by findLockInfo().
845*/
846static void releaseLockInfo(struct unixLockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000847 if( pLock ){
848 pLock->nRef--;
849 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000850 if( pLock->pPrev ){
851 assert( pLock->pPrev->pNext==pLock );
852 pLock->pPrev->pNext = pLock->pNext;
853 }else{
854 assert( lockList==pLock );
855 lockList = pLock->pNext;
856 }
857 if( pLock->pNext ){
858 assert( pLock->pNext->pPrev==pLock );
859 pLock->pNext->pPrev = pLock->pPrev;
860 }
danielk1977e339d652008-06-28 11:23:00 +0000861 sqlite3_free(pLock);
862 }
drhbbd42a62004-05-22 17:41:58 +0000863 }
864}
865
866/*
drh6c7d5c52008-11-21 20:32:33 +0000867** Release a unixOpenCnt structure previously allocated by findLockInfo().
drhbbd42a62004-05-22 17:41:58 +0000868*/
drh6c7d5c52008-11-21 20:32:33 +0000869static void releaseOpenCnt(struct unixOpenCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000870 if( pOpen ){
871 pOpen->nRef--;
872 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000873 if( pOpen->pPrev ){
874 assert( pOpen->pPrev->pNext==pOpen );
875 pOpen->pPrev->pNext = pOpen->pNext;
876 }else{
877 assert( openList==pOpen );
878 openList = pOpen->pNext;
879 }
880 if( pOpen->pNext ){
881 assert( pOpen->pNext->pPrev==pOpen );
882 pOpen->pNext->pPrev = pOpen->pPrev;
883 }
884 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000885 sqlite3_free(pOpen);
886 }
drhbbd42a62004-05-22 17:41:58 +0000887 }
888}
889
drh6c7d5c52008-11-21 20:32:33 +0000890/*
891** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
892** describes that file descriptor. Create new ones if necessary. The
893** return values might be uninitialized if an error occurs.
894**
895** Return an appropriate error code.
896*/
897static int findLockInfo(
898 unixFile *pFile, /* Unix file with file desc used in the key */
899 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
900 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
901){
902 int rc; /* System call return code */
903 int fd; /* The file descriptor for pFile */
904 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
905 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
906 struct stat statbuf; /* Low-level file information */
907 struct unixLockInfo *pLock; /* Candidate unixLockInfo object */
908 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
909
910 /* Get low-level information about the file that we can used to
911 ** create a unique name for the file.
912 */
913 fd = pFile->h;
914 rc = fstat(fd, &statbuf);
915 if( rc!=0 ){
916 pFile->lastErrno = errno;
917#ifdef EOVERFLOW
918 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
919#endif
920 return SQLITE_IOERR;
921 }
922
drheb0d74f2009-02-03 15:27:02 +0000923#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000924 /* On OS X on an msdos filesystem, the inode number is reported
925 ** incorrectly for zero-size files. See ticket #3260. To work
926 ** around this problem (we consider it a bug in OS X, not SQLite)
927 ** we always increase the file size to 1 by writing a single byte
928 ** prior to accessing the inode number. The one byte written is
929 ** an ASCII 'S' character which also happens to be the first byte
930 ** in the header of every SQLite database. In this way, if there
931 ** is a race condition such that another thread has already populated
932 ** the first page of the database, no damage is done.
933 */
934 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000935 rc = write(fd, "S", 1);
936 if( rc!=1 ){
937 return SQLITE_IOERR;
938 }
drh6c7d5c52008-11-21 20:32:33 +0000939 rc = fstat(fd, &statbuf);
940 if( rc!=0 ){
941 pFile->lastErrno = errno;
942 return SQLITE_IOERR;
943 }
944 }
drheb0d74f2009-02-03 15:27:02 +0000945#endif
drh6c7d5c52008-11-21 20:32:33 +0000946
947 memset(&lockKey, 0, sizeof(lockKey));
948 lockKey.fid.dev = statbuf.st_dev;
949#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000950 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000951#else
952 lockKey.fid.ino = statbuf.st_ino;
953#endif
drh734c9862008-11-28 15:37:20 +0000954#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000955 if( threadsOverrideEachOthersLocks<0 ){
956 testThreadLockingBehavior(fd);
957 }
958 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
959#endif
960 fileId = lockKey.fid;
961 if( ppLock!=0 ){
962 pLock = lockList;
963 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
964 pLock = pLock->pNext;
965 }
966 if( pLock==0 ){
967 pLock = sqlite3_malloc( sizeof(*pLock) );
968 if( pLock==0 ){
969 rc = SQLITE_NOMEM;
970 goto exit_findlockinfo;
971 }
972 pLock->lockKey = lockKey;
973 pLock->nRef = 1;
974 pLock->cnt = 0;
975 pLock->locktype = 0;
976 pLock->pNext = lockList;
977 pLock->pPrev = 0;
978 if( lockList ) lockList->pPrev = pLock;
979 lockList = pLock;
980 }else{
981 pLock->nRef++;
982 }
983 *ppLock = pLock;
984 }
985 if( ppOpen!=0 ){
986 pOpen = openList;
987 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
988 pOpen = pOpen->pNext;
989 }
990 if( pOpen==0 ){
991 pOpen = sqlite3_malloc( sizeof(*pOpen) );
992 if( pOpen==0 ){
993 releaseLockInfo(pLock);
994 rc = SQLITE_NOMEM;
995 goto exit_findlockinfo;
996 }
997 pOpen->fileId = fileId;
998 pOpen->nRef = 1;
999 pOpen->nLock = 0;
1000 pOpen->nPending = 0;
1001 pOpen->aPending = 0;
1002 pOpen->pNext = openList;
1003 pOpen->pPrev = 0;
1004 if( openList ) openList->pPrev = pOpen;
1005 openList = pOpen;
1006#if OS_VXWORKS
1007 pOpen->pSem = NULL;
1008 pOpen->aSemName[0] = '\0';
1009#endif
1010 }else{
1011 pOpen->nRef++;
1012 }
1013 *ppOpen = pOpen;
1014 }
1015
1016exit_findlockinfo:
1017 return rc;
1018}
drh6c7d5c52008-11-21 20:32:33 +00001019
drh7708e972008-11-29 00:56:52 +00001020/*
1021** If we are currently in a different thread than the thread that the
1022** unixFile argument belongs to, then transfer ownership of the unixFile
1023** over to the current thread.
1024**
1025** A unixFile is only owned by a thread on systems that use LinuxThreads.
1026**
1027** Ownership transfer is only allowed if the unixFile is currently unlocked.
1028** If the unixFile is locked and an ownership is wrong, then return
1029** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1030*/
1031#if SQLITE_THREADSAFE && defined(__linux__)
1032static int transferOwnership(unixFile *pFile){
1033 int rc;
1034 pthread_t hSelf;
1035 if( threadsOverrideEachOthersLocks ){
1036 /* Ownership transfers not needed on this system */
1037 return SQLITE_OK;
1038 }
1039 hSelf = pthread_self();
1040 if( pthread_equal(pFile->tid, hSelf) ){
1041 /* We are still in the same thread */
1042 OSTRACE1("No-transfer, same thread\n");
1043 return SQLITE_OK;
1044 }
1045 if( pFile->locktype!=NO_LOCK ){
1046 /* We cannot change ownership while we are holding a lock! */
1047 return SQLITE_MISUSE;
1048 }
1049 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1050 pFile->h, pFile->tid, hSelf);
1051 pFile->tid = hSelf;
1052 if (pFile->pLock != NULL) {
1053 releaseLockInfo(pFile->pLock);
1054 rc = findLockInfo(pFile, &pFile->pLock, 0);
1055 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1056 locktypeName(pFile->locktype),
1057 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1058 return rc;
1059 } else {
1060 return SQLITE_OK;
1061 }
1062}
1063#else /* if not SQLITE_THREADSAFE */
1064 /* On single-threaded builds, ownership transfer is a no-op */
1065# define transferOwnership(X) SQLITE_OK
1066#endif /* SQLITE_THREADSAFE */
1067
aswift5b1a2562008-08-22 00:22:35 +00001068
1069/*
danielk197713adf8a2004-06-03 16:08:41 +00001070** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001071** file by this or any other process. If such a lock is held, set *pResOut
1072** to a non-zero value otherwise *pResOut is set to zero. The return value
1073** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001074*/
danielk1977861f7452008-06-05 11:39:11 +00001075static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001076 int rc = SQLITE_OK;
1077 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001078 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001079
danielk1977861f7452008-06-05 11:39:11 +00001080 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1081
drh054889e2005-11-30 03:20:31 +00001082 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001083 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001084
1085 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001086 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001087 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001088 }
1089
drh2ac3ee92004-06-07 16:27:46 +00001090 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001091 */
danielk197709480a92009-02-09 05:32:32 +00001092#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001093 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001094 struct flock lock;
1095 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001096 lock.l_start = RESERVED_BYTE;
1097 lock.l_len = 1;
1098 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001099 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1100 int tErrno = errno;
1101 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1102 pFile->lastErrno = tErrno;
1103 } else if( lock.l_type!=F_UNLCK ){
1104 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001105 }
1106 }
danielk197709480a92009-02-09 05:32:32 +00001107#endif
danielk197713adf8a2004-06-03 16:08:41 +00001108
drh6c7d5c52008-11-21 20:32:33 +00001109 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001110 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001111
aswift5b1a2562008-08-22 00:22:35 +00001112 *pResOut = reserved;
1113 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001114}
1115
1116/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001117** Lock the file with the lock specified by parameter locktype - one
1118** of the following:
1119**
drh2ac3ee92004-06-07 16:27:46 +00001120** (1) SHARED_LOCK
1121** (2) RESERVED_LOCK
1122** (3) PENDING_LOCK
1123** (4) EXCLUSIVE_LOCK
1124**
drhb3e04342004-06-08 00:47:47 +00001125** Sometimes when requesting one lock state, additional lock states
1126** are inserted in between. The locking might fail on one of the later
1127** transitions leaving the lock state different from what it started but
1128** still short of its goal. The following chart shows the allowed
1129** transitions and the inserted intermediate states:
1130**
1131** UNLOCKED -> SHARED
1132** SHARED -> RESERVED
1133** SHARED -> (PENDING) -> EXCLUSIVE
1134** RESERVED -> (PENDING) -> EXCLUSIVE
1135** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001136**
drha6abd042004-06-09 17:37:22 +00001137** This routine will only increase a lock. Use the sqlite3OsUnlock()
1138** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001139*/
danielk197762079062007-08-15 17:08:46 +00001140static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001141 /* The following describes the implementation of the various locks and
1142 ** lock transitions in terms of the POSIX advisory shared and exclusive
1143 ** lock primitives (called read-locks and write-locks below, to avoid
1144 ** confusion with SQLite lock names). The algorithms are complicated
1145 ** slightly in order to be compatible with windows systems simultaneously
1146 ** accessing the same database file, in case that is ever required.
1147 **
1148 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1149 ** byte', each single bytes at well known offsets, and the 'shared byte
1150 ** range', a range of 510 bytes at a well known offset.
1151 **
1152 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1153 ** byte'. If this is successful, a random byte from the 'shared byte
1154 ** range' is read-locked and the lock on the 'pending byte' released.
1155 **
danielk197790ba3bd2004-06-25 08:32:25 +00001156 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1157 ** A RESERVED lock is implemented by grabbing a write-lock on the
1158 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001159 **
1160 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001161 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1162 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1163 ** obtained, but existing SHARED locks are allowed to persist. A process
1164 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1165 ** This property is used by the algorithm for rolling back a journal file
1166 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001167 **
danielk197790ba3bd2004-06-25 08:32:25 +00001168 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1169 ** implemented by obtaining a write-lock on the entire 'shared byte
1170 ** range'. Since all other locks require a read-lock on one of the bytes
1171 ** within this range, this ensures that no other locks are held on the
1172 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001173 **
1174 ** The reason a single byte cannot be used instead of the 'shared byte
1175 ** range' is that some versions of windows do not support read-locks. By
1176 ** locking a random byte from a range, concurrent SHARED locks may exist
1177 ** even if the locking primitive used is always a write-lock.
1178 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001179 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001180 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001181 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001182 struct flock lock;
1183 int s;
1184
drh054889e2005-11-30 03:20:31 +00001185 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001186 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001187 locktypeName(locktype), locktypeName(pFile->locktype),
1188 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001189
1190 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001191 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001192 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001193 */
drh054889e2005-11-30 03:20:31 +00001194 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001195 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001196 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001197 return SQLITE_OK;
1198 }
1199
drhb3e04342004-06-08 00:47:47 +00001200 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001201 */
drh054889e2005-11-30 03:20:31 +00001202 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001203 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001204 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001205
drh054889e2005-11-30 03:20:31 +00001206 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001207 */
drh6c7d5c52008-11-21 20:32:33 +00001208 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001209
drh029b44b2006-01-15 00:13:15 +00001210 /* Make sure the current thread owns the pFile.
1211 */
1212 rc = transferOwnership(pFile);
1213 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001214 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001215 return rc;
1216 }
drh64b1bea2006-01-15 02:30:57 +00001217 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001218
danielk1977ad94b582007-08-20 06:44:22 +00001219 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001220 ** handle that precludes the requested lock, return BUSY.
1221 */
drh054889e2005-11-30 03:20:31 +00001222 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001223 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001224 ){
1225 rc = SQLITE_BUSY;
1226 goto end_lock;
1227 }
1228
1229 /* If a SHARED lock is requested, and some thread using this PID already
1230 ** has a SHARED or RESERVED lock, then increment reference counts and
1231 ** return SQLITE_OK.
1232 */
1233 if( locktype==SHARED_LOCK &&
1234 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1235 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001236 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001237 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001238 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001239 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001240 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001241 goto end_lock;
1242 }
1243
danielk197713adf8a2004-06-03 16:08:41 +00001244 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001245
danielk19779a1d0ab2004-06-01 14:09:28 +00001246 lock.l_whence = SEEK_SET;
1247
drh3cde3bb2004-06-12 02:17:14 +00001248 /* A PENDING lock is needed before acquiring a SHARED lock and before
1249 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1250 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001251 */
drh3cde3bb2004-06-12 02:17:14 +00001252 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001253 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001254 ){
danielk1977489468c2004-06-28 08:25:47 +00001255 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001256 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001257 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001258 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001259 int tErrno = errno;
1260 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1261 if( IS_LOCK_ERROR(rc) ){
1262 pFile->lastErrno = tErrno;
1263 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001264 goto end_lock;
1265 }
drh3cde3bb2004-06-12 02:17:14 +00001266 }
1267
1268
1269 /* If control gets to this point, then actually go ahead and make
1270 ** operating system calls for the specified lock.
1271 */
1272 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001273 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001274 assert( pLock->cnt==0 );
1275 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001276
drh2ac3ee92004-06-07 16:27:46 +00001277 /* Now get the read-lock */
1278 lock.l_start = SHARED_FIRST;
1279 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001280 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1281 tErrno = errno;
1282 }
drh2ac3ee92004-06-07 16:27:46 +00001283 /* Drop the temporary PENDING lock */
1284 lock.l_start = PENDING_BYTE;
1285 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001286 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001287 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001288 if( s != -1 ){
1289 /* This could happen with a network mount */
1290 tErrno = errno;
1291 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1292 if( IS_LOCK_ERROR(rc) ){
1293 pFile->lastErrno = tErrno;
1294 }
1295 goto end_lock;
1296 }
drh2b4b5962005-06-15 17:47:55 +00001297 }
drhe2396a12007-03-29 20:19:58 +00001298 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001299 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1300 if( IS_LOCK_ERROR(rc) ){
1301 pFile->lastErrno = tErrno;
1302 }
drhbbd42a62004-05-22 17:41:58 +00001303 }else{
drh054889e2005-11-30 03:20:31 +00001304 pFile->locktype = SHARED_LOCK;
1305 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001306 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001307 }
drh3cde3bb2004-06-12 02:17:14 +00001308 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1309 /* We are trying for an exclusive lock but another thread in this
1310 ** same process is still holding a shared lock. */
1311 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001312 }else{
drh3cde3bb2004-06-12 02:17:14 +00001313 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001314 ** assumed that there is a SHARED or greater lock on the file
1315 ** already.
1316 */
drh054889e2005-11-30 03:20:31 +00001317 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001318 lock.l_type = F_WRLCK;
1319 switch( locktype ){
1320 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001321 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001322 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001324 lock.l_start = SHARED_FIRST;
1325 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001326 break;
1327 default:
1328 assert(0);
1329 }
drh054889e2005-11-30 03:20:31 +00001330 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001331 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001332 int tErrno = errno;
1333 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1334 if( IS_LOCK_ERROR(rc) ){
1335 pFile->lastErrno = tErrno;
1336 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001337 }
drhbbd42a62004-05-22 17:41:58 +00001338 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001339
drh8f941bc2009-01-14 23:03:40 +00001340
1341#ifndef NDEBUG
1342 /* Set up the transaction-counter change checking flags when
1343 ** transitioning from a SHARED to a RESERVED lock. The change
1344 ** from SHARED to RESERVED marks the beginning of a normal
1345 ** write operation (not a hot journal rollback).
1346 */
1347 if( rc==SQLITE_OK
1348 && pFile->locktype<=SHARED_LOCK
1349 && locktype==RESERVED_LOCK
1350 ){
1351 pFile->transCntrChng = 0;
1352 pFile->dbUpdate = 0;
1353 pFile->inNormalWrite = 1;
1354 }
1355#endif
1356
1357
danielk1977ecb2a962004-06-02 06:30:16 +00001358 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001359 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001360 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001361 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001362 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001363 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001364 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001365
1366end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001367 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001368 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001369 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001370 return rc;
1371}
1372
1373/*
drh054889e2005-11-30 03:20:31 +00001374** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001375** must be either NO_LOCK or SHARED_LOCK.
1376**
1377** If the locking level of the file descriptor is already at or below
1378** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001379*/
danielk197762079062007-08-15 17:08:46 +00001380static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001381 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001382 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001383 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001384 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001385 int h;
drha6abd042004-06-09 17:37:22 +00001386
drh054889e2005-11-30 03:20:31 +00001387 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001388 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001389 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001390
1391 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001392 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001393 return SQLITE_OK;
1394 }
drhf1a221e2006-01-15 17:27:17 +00001395 if( CHECK_THREADID(pFile) ){
1396 return SQLITE_MISUSE;
1397 }
drh6c7d5c52008-11-21 20:32:33 +00001398 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001399 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001400 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001401 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001402 if( pFile->locktype>SHARED_LOCK ){
1403 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001404 SimulateIOErrorBenign(1);
1405 SimulateIOError( h=(-1) )
1406 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001407
1408#ifndef NDEBUG
1409 /* When reducing a lock such that other processes can start
1410 ** reading the database file again, make sure that the
1411 ** transaction counter was updated if any part of the database
1412 ** file changed. If the transaction counter is not updated,
1413 ** other connections to the same file might not realize that
1414 ** the file has changed and hence might not know to flush their
1415 ** cache. The use of a stale cache can lead to database corruption.
1416 */
1417 assert( pFile->inNormalWrite==0
1418 || pFile->dbUpdate==0
1419 || pFile->transCntrChng==1 );
1420 pFile->inNormalWrite = 0;
1421#endif
1422
1423
drh9c105bb2004-10-02 20:38:28 +00001424 if( locktype==SHARED_LOCK ){
1425 lock.l_type = F_RDLCK;
1426 lock.l_whence = SEEK_SET;
1427 lock.l_start = SHARED_FIRST;
1428 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001429 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001430 int tErrno = errno;
1431 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1432 if( IS_LOCK_ERROR(rc) ){
1433 pFile->lastErrno = tErrno;
1434 }
danielk197709480a92009-02-09 05:32:32 +00001435 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001436 }
1437 }
drhbbd42a62004-05-22 17:41:58 +00001438 lock.l_type = F_UNLCK;
1439 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001440 lock.l_start = PENDING_BYTE;
1441 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001442 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001443 pLock->locktype = SHARED_LOCK;
1444 }else{
aswift5b1a2562008-08-22 00:22:35 +00001445 int tErrno = errno;
1446 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1447 if( IS_LOCK_ERROR(rc) ){
1448 pFile->lastErrno = tErrno;
1449 }
1450 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001451 }
drhbbd42a62004-05-22 17:41:58 +00001452 }
drha6abd042004-06-09 17:37:22 +00001453 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001454 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001455
drha6abd042004-06-09 17:37:22 +00001456 /* Decrement the shared lock counter. Release the lock using an
1457 ** OS call only when all threads in this same process have released
1458 ** the lock.
1459 */
1460 pLock->cnt--;
1461 if( pLock->cnt==0 ){
1462 lock.l_type = F_UNLCK;
1463 lock.l_whence = SEEK_SET;
1464 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001465 SimulateIOErrorBenign(1);
1466 SimulateIOError( h=(-1) )
1467 SimulateIOErrorBenign(0);
1468 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001469 pLock->locktype = NO_LOCK;
1470 }else{
aswift5b1a2562008-08-22 00:22:35 +00001471 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001472 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001473 if( IS_LOCK_ERROR(rc) ){
1474 pFile->lastErrno = tErrno;
1475 }
drh1aa5af12008-03-07 19:51:14 +00001476 pLock->cnt = 1;
aswift5b1a2562008-08-22 00:22:35 +00001477 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001478 }
drha6abd042004-06-09 17:37:22 +00001479 }
1480
drhbbd42a62004-05-22 17:41:58 +00001481 /* Decrement the count of locks against this same file. When the
1482 ** count reaches zero, close any other file descriptors whose close
1483 ** was deferred because of outstanding locks.
1484 */
drh1aa5af12008-03-07 19:51:14 +00001485 if( rc==SQLITE_OK ){
1486 pOpen = pFile->pOpen;
1487 pOpen->nLock--;
1488 assert( pOpen->nLock>=0 );
1489 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1490 int i;
1491 for(i=0; i<pOpen->nPending; i++){
aswiftaebf4132008-11-21 00:10:35 +00001492 /* close pending fds, but if closing fails don't free the array
1493 ** assign -1 to the successfully closed descriptors and record the
1494 ** error. The next attempt to unlock will try again. */
1495 if( pOpen->aPending[i] < 0 ) continue;
1496 if( close(pOpen->aPending[i]) ){
1497 pFile->lastErrno = errno;
1498 rc = SQLITE_IOERR_CLOSE;
1499 }else{
1500 pOpen->aPending[i] = -1;
1501 }
drh1aa5af12008-03-07 19:51:14 +00001502 }
aswiftaebf4132008-11-21 00:10:35 +00001503 if( rc==SQLITE_OK ){
1504 sqlite3_free(pOpen->aPending);
1505 pOpen->nPending = 0;
1506 pOpen->aPending = 0;
1507 }
drhbbd42a62004-05-22 17:41:58 +00001508 }
drhbbd42a62004-05-22 17:41:58 +00001509 }
1510 }
aswift5b1a2562008-08-22 00:22:35 +00001511
1512end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001513 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001514 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001515 return rc;
drhbbd42a62004-05-22 17:41:58 +00001516}
1517
1518/*
danielk1977e339d652008-06-28 11:23:00 +00001519** This function performs the parts of the "close file" operation
1520** common to all locking schemes. It closes the directory and file
1521** handles, if they are valid, and sets all fields of the unixFile
1522** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001523**
1524** It is *not* necessary to hold the mutex when this routine is called,
1525** even on VxWorks. A mutex will be acquired on VxWorks by the
1526** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001527*/
1528static int closeUnixFile(sqlite3_file *id){
1529 unixFile *pFile = (unixFile*)id;
1530 if( pFile ){
1531 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001532 int err = close(pFile->dirfd);
1533 if( err ){
1534 pFile->lastErrno = errno;
1535 return SQLITE_IOERR_DIR_CLOSE;
1536 }else{
1537 pFile->dirfd=-1;
1538 }
danielk1977e339d652008-06-28 11:23:00 +00001539 }
1540 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001541 int err = close(pFile->h);
1542 if( err ){
1543 pFile->lastErrno = errno;
1544 return SQLITE_IOERR_CLOSE;
1545 }
danielk1977e339d652008-06-28 11:23:00 +00001546 }
drh6c7d5c52008-11-21 20:32:33 +00001547#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001548 if( pFile->pId ){
1549 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001550 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001551 }
drh107886a2008-11-21 22:21:50 +00001552 vxworksReleaseFileId(pFile->pId);
1553 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001554 }
1555#endif
danielk1977e339d652008-06-28 11:23:00 +00001556 OSTRACE2("CLOSE %-3d\n", pFile->h);
1557 OpenCounter(-1);
1558 memset(pFile, 0, sizeof(unixFile));
1559 }
1560 return SQLITE_OK;
1561}
1562
1563/*
danielk1977e3026632004-06-22 11:29:02 +00001564** Close a file.
1565*/
danielk197762079062007-08-15 17:08:46 +00001566static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001567 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001568 if( id ){
1569 unixFile *pFile = (unixFile *)id;
1570 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001571 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001572 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001573 /* If there are outstanding locks, do not actually close the file just
1574 ** yet because that would clear those locks. Instead, add the file
1575 ** descriptor to pOpen->aPending. It will be automatically closed when
1576 ** the last lock is cleared.
1577 */
1578 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001579 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001580 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001581 if( aNew==0 ){
1582 /* If a malloc fails, just leak the file descriptor */
1583 }else{
1584 pOpen->aPending = aNew;
1585 pOpen->aPending[pOpen->nPending] = pFile->h;
1586 pOpen->nPending++;
1587 pFile->h = -1;
1588 }
danielk1977e3026632004-06-22 11:29:02 +00001589 }
danielk1977e339d652008-06-28 11:23:00 +00001590 releaseLockInfo(pFile->pLock);
1591 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001592 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001593 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001594 }
aswiftaebf4132008-11-21 00:10:35 +00001595 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001596}
1597
drh734c9862008-11-28 15:37:20 +00001598/************** End of the posix advisory lock implementation *****************
1599******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001600
drh734c9862008-11-28 15:37:20 +00001601/******************************************************************************
1602****************************** No-op Locking **********************************
1603**
1604** Of the various locking implementations available, this is by far the
1605** simplest: locking is ignored. No attempt is made to lock the database
1606** file for reading or writing.
1607**
1608** This locking mode is appropriate for use on read-only databases
1609** (ex: databases that are burned into CD-ROM, for example.) It can
1610** also be used if the application employs some external mechanism to
1611** prevent simultaneous access of the same database by two or more
1612** database connections. But there is a serious risk of database
1613** corruption if this locking mode is used in situations where multiple
1614** database connections are accessing the same database file at the same
1615** time and one or more of those connections are writing.
1616*/
drhbfe66312006-10-03 17:40:40 +00001617
drh734c9862008-11-28 15:37:20 +00001618static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1619 UNUSED_PARAMETER(NotUsed);
1620 *pResOut = 0;
1621 return SQLITE_OK;
1622}
drh734c9862008-11-28 15:37:20 +00001623static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1624 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1625 return SQLITE_OK;
1626}
drh734c9862008-11-28 15:37:20 +00001627static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1628 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1629 return SQLITE_OK;
1630}
1631
1632/*
drh9b35ea62008-11-29 02:20:26 +00001633** Close the file.
drh734c9862008-11-28 15:37:20 +00001634*/
1635static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001636 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001637}
1638
1639/******************* End of the no-op lock implementation *********************
1640******************************************************************************/
1641
1642/******************************************************************************
1643************************* Begin dot-file Locking ******************************
1644**
1645** The dotfile locking implementation uses the existing of separate lock
1646** files in order to control access to the database. This works on just
1647** about every filesystem imaginable. But there are serious downsides:
1648**
1649** (1) There is zero concurrency. A single reader blocks all other
1650** connections from reading or writing the database.
1651**
1652** (2) An application crash or power loss can leave stale lock files
1653** sitting around that need to be cleared manually.
1654**
1655** Nevertheless, a dotlock is an appropriate locking mode for use if no
1656** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001657**
1658** Dotfile locking works by creating a file in the same directory as the
1659** database and with the same name but with a ".lock" extension added.
1660** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1661** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001662*/
1663
1664/*
1665** The file suffix added to the data base filename in order to create the
1666** lock file.
1667*/
1668#define DOTLOCK_SUFFIX ".lock"
1669
drh7708e972008-11-29 00:56:52 +00001670/*
1671** This routine checks if there is a RESERVED lock held on the specified
1672** file by this or any other process. If such a lock is held, set *pResOut
1673** to a non-zero value otherwise *pResOut is set to zero. The return value
1674** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1675**
1676** In dotfile locking, either a lock exists or it does not. So in this
1677** variation of CheckReservedLock(), *pResOut is set to true if any lock
1678** is held on the file and false if the file is unlocked.
1679*/
drh734c9862008-11-28 15:37:20 +00001680static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1681 int rc = SQLITE_OK;
1682 int reserved = 0;
1683 unixFile *pFile = (unixFile*)id;
1684
1685 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1686
1687 assert( pFile );
1688
1689 /* Check if a thread in this process holds such a lock */
1690 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001691 /* Either this connection or some other connection in the same process
1692 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001693 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001694 }else{
1695 /* The lock is held if and only if the lockfile exists */
1696 const char *zLockFile = (const char*)pFile->lockingContext;
1697 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001698 }
1699 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001700 *pResOut = reserved;
1701 return rc;
1702}
1703
drh7708e972008-11-29 00:56:52 +00001704/*
1705** Lock the file with the lock specified by parameter locktype - one
1706** of the following:
1707**
1708** (1) SHARED_LOCK
1709** (2) RESERVED_LOCK
1710** (3) PENDING_LOCK
1711** (4) EXCLUSIVE_LOCK
1712**
1713** Sometimes when requesting one lock state, additional lock states
1714** are inserted in between. The locking might fail on one of the later
1715** transitions leaving the lock state different from what it started but
1716** still short of its goal. The following chart shows the allowed
1717** transitions and the inserted intermediate states:
1718**
1719** UNLOCKED -> SHARED
1720** SHARED -> RESERVED
1721** SHARED -> (PENDING) -> EXCLUSIVE
1722** RESERVED -> (PENDING) -> EXCLUSIVE
1723** PENDING -> EXCLUSIVE
1724**
1725** This routine will only increase a lock. Use the sqlite3OsUnlock()
1726** routine to lower a locking level.
1727**
1728** With dotfile locking, we really only support state (4): EXCLUSIVE.
1729** But we track the other locking levels internally.
1730*/
drh734c9862008-11-28 15:37:20 +00001731static int dotlockLock(sqlite3_file *id, int locktype) {
1732 unixFile *pFile = (unixFile*)id;
1733 int fd;
1734 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001735 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001736
drh7708e972008-11-29 00:56:52 +00001737
1738 /* If we have any lock, then the lock file already exists. All we have
1739 ** to do is adjust our internal record of the lock level.
1740 */
1741 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001742 pFile->locktype = locktype;
1743#if !OS_VXWORKS
1744 /* Always update the timestamp on the old file */
1745 utimes(zLockFile, NULL);
1746#endif
drh7708e972008-11-29 00:56:52 +00001747 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001748 }
1749
1750 /* grab an exclusive lock */
1751 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1752 if( fd<0 ){
1753 /* failed to open/create the file, someone else may have stolen the lock */
1754 int tErrno = errno;
1755 if( EEXIST == tErrno ){
1756 rc = SQLITE_BUSY;
1757 } else {
1758 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1759 if( IS_LOCK_ERROR(rc) ){
1760 pFile->lastErrno = tErrno;
1761 }
1762 }
drh7708e972008-11-29 00:56:52 +00001763 return rc;
drh734c9862008-11-28 15:37:20 +00001764 }
1765 if( close(fd) ){
1766 pFile->lastErrno = errno;
1767 rc = SQLITE_IOERR_CLOSE;
1768 }
1769
1770 /* got it, set the type and return ok */
1771 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001772 return rc;
1773}
1774
drh7708e972008-11-29 00:56:52 +00001775/*
1776** Lower the locking level on file descriptor pFile to locktype. locktype
1777** must be either NO_LOCK or SHARED_LOCK.
1778**
1779** If the locking level of the file descriptor is already at or below
1780** the requested locking level, this routine is a no-op.
1781**
1782** When the locking level reaches NO_LOCK, delete the lock file.
1783*/
drh734c9862008-11-28 15:37:20 +00001784static int dotlockUnlock(sqlite3_file *id, int locktype) {
1785 unixFile *pFile = (unixFile*)id;
1786 char *zLockFile = (char *)pFile->lockingContext;
1787
1788 assert( pFile );
1789 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1790 pFile->locktype, getpid());
1791 assert( locktype<=SHARED_LOCK );
1792
1793 /* no-op if possible */
1794 if( pFile->locktype==locktype ){
1795 return SQLITE_OK;
1796 }
drh7708e972008-11-29 00:56:52 +00001797
1798 /* To downgrade to shared, simply update our internal notion of the
1799 ** lock state. No need to mess with the file on disk.
1800 */
1801 if( locktype==SHARED_LOCK ){
1802 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001803 return SQLITE_OK;
1804 }
1805
drh7708e972008-11-29 00:56:52 +00001806 /* To fully unlock the database, delete the lock file */
1807 assert( locktype==NO_LOCK );
1808 if( unlink(zLockFile) ){
drh734c9862008-11-28 15:37:20 +00001809 int rc, tErrno = errno;
1810 if( ENOENT != tErrno ){
1811 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1812 }
1813 if( IS_LOCK_ERROR(rc) ){
1814 pFile->lastErrno = tErrno;
1815 }
1816 return rc;
1817 }
1818 pFile->locktype = NO_LOCK;
1819 return SQLITE_OK;
1820}
1821
1822/*
drh9b35ea62008-11-29 02:20:26 +00001823** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001824*/
1825static int dotlockClose(sqlite3_file *id) {
1826 int rc;
1827 if( id ){
1828 unixFile *pFile = (unixFile*)id;
1829 dotlockUnlock(id, NO_LOCK);
1830 sqlite3_free(pFile->lockingContext);
1831 }
drh734c9862008-11-28 15:37:20 +00001832 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001833 return rc;
1834}
1835/****************** End of the dot-file lock implementation *******************
1836******************************************************************************/
1837
1838/******************************************************************************
1839************************** Begin flock Locking ********************************
1840**
1841** Use the flock() system call to do file locking.
1842**
drh6b9d6dd2008-12-03 19:34:47 +00001843** flock() locking is like dot-file locking in that the various
1844** fine-grain locking levels supported by SQLite are collapsed into
1845** a single exclusive lock. In other words, SHARED, RESERVED, and
1846** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1847** still works when you do this, but concurrency is reduced since
1848** only a single process can be reading the database at a time.
1849**
drh734c9862008-11-28 15:37:20 +00001850** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1851** compiling for VXWORKS.
1852*/
1853#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001854
drh6b9d6dd2008-12-03 19:34:47 +00001855/*
1856** This routine checks if there is a RESERVED lock held on the specified
1857** file by this or any other process. If such a lock is held, set *pResOut
1858** to a non-zero value otherwise *pResOut is set to zero. The return value
1859** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1860*/
drh734c9862008-11-28 15:37:20 +00001861static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1862 int rc = SQLITE_OK;
1863 int reserved = 0;
1864 unixFile *pFile = (unixFile*)id;
1865
1866 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1867
1868 assert( pFile );
1869
1870 /* Check if a thread in this process holds such a lock */
1871 if( pFile->locktype>SHARED_LOCK ){
1872 reserved = 1;
1873 }
1874
1875 /* Otherwise see if some other process holds it. */
1876 if( !reserved ){
1877 /* attempt to get the lock */
1878 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1879 if( !lrc ){
1880 /* got the lock, unlock it */
1881 lrc = flock(pFile->h, LOCK_UN);
1882 if ( lrc ) {
1883 int tErrno = errno;
1884 /* unlock failed with an error */
1885 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1886 if( IS_LOCK_ERROR(lrc) ){
1887 pFile->lastErrno = tErrno;
1888 rc = lrc;
1889 }
1890 }
1891 } else {
1892 int tErrno = errno;
1893 reserved = 1;
1894 /* someone else might have it reserved */
1895 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1896 if( IS_LOCK_ERROR(lrc) ){
1897 pFile->lastErrno = tErrno;
1898 rc = lrc;
1899 }
1900 }
1901 }
1902 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1903
1904#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1905 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1906 rc = SQLITE_OK;
1907 reserved=1;
1908 }
1909#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1910 *pResOut = reserved;
1911 return rc;
1912}
1913
drh6b9d6dd2008-12-03 19:34:47 +00001914/*
1915** Lock the file with the lock specified by parameter locktype - one
1916** of the following:
1917**
1918** (1) SHARED_LOCK
1919** (2) RESERVED_LOCK
1920** (3) PENDING_LOCK
1921** (4) EXCLUSIVE_LOCK
1922**
1923** Sometimes when requesting one lock state, additional lock states
1924** are inserted in between. The locking might fail on one of the later
1925** transitions leaving the lock state different from what it started but
1926** still short of its goal. The following chart shows the allowed
1927** transitions and the inserted intermediate states:
1928**
1929** UNLOCKED -> SHARED
1930** SHARED -> RESERVED
1931** SHARED -> (PENDING) -> EXCLUSIVE
1932** RESERVED -> (PENDING) -> EXCLUSIVE
1933** PENDING -> EXCLUSIVE
1934**
1935** flock() only really support EXCLUSIVE locks. We track intermediate
1936** lock states in the sqlite3_file structure, but all locks SHARED or
1937** above are really EXCLUSIVE locks and exclude all other processes from
1938** access the file.
1939**
1940** This routine will only increase a lock. Use the sqlite3OsUnlock()
1941** routine to lower a locking level.
1942*/
drh734c9862008-11-28 15:37:20 +00001943static int flockLock(sqlite3_file *id, int locktype) {
1944 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001945 unixFile *pFile = (unixFile*)id;
1946
1947 assert( pFile );
1948
1949 /* if we already have a lock, it is exclusive.
1950 ** Just adjust level and punt on outta here. */
1951 if (pFile->locktype > NO_LOCK) {
1952 pFile->locktype = locktype;
1953 return SQLITE_OK;
1954 }
1955
1956 /* grab an exclusive lock */
1957
1958 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1959 int tErrno = errno;
1960 /* didn't get, must be busy */
1961 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1962 if( IS_LOCK_ERROR(rc) ){
1963 pFile->lastErrno = tErrno;
1964 }
1965 } else {
1966 /* got it, set the type and return ok */
1967 pFile->locktype = locktype;
1968 }
1969 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1970 rc==SQLITE_OK ? "ok" : "failed");
1971#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1972 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1973 rc = SQLITE_BUSY;
1974 }
1975#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1976 return rc;
1977}
1978
drh6b9d6dd2008-12-03 19:34:47 +00001979
1980/*
1981** Lower the locking level on file descriptor pFile to locktype. locktype
1982** must be either NO_LOCK or SHARED_LOCK.
1983**
1984** If the locking level of the file descriptor is already at or below
1985** the requested locking level, this routine is a no-op.
1986*/
drh734c9862008-11-28 15:37:20 +00001987static int flockUnlock(sqlite3_file *id, int locktype) {
1988 unixFile *pFile = (unixFile*)id;
1989
1990 assert( pFile );
1991 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1992 pFile->locktype, getpid());
1993 assert( locktype<=SHARED_LOCK );
1994
1995 /* no-op if possible */
1996 if( pFile->locktype==locktype ){
1997 return SQLITE_OK;
1998 }
1999
2000 /* shared can just be set because we always have an exclusive */
2001 if (locktype==SHARED_LOCK) {
2002 pFile->locktype = locktype;
2003 return SQLITE_OK;
2004 }
2005
2006 /* no, really, unlock. */
2007 int rc = flock(pFile->h, LOCK_UN);
2008 if (rc) {
2009 int r, tErrno = errno;
2010 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2011 if( IS_LOCK_ERROR(r) ){
2012 pFile->lastErrno = tErrno;
2013 }
2014#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2015 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2016 r = SQLITE_BUSY;
2017 }
2018#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2019
2020 return r;
2021 } else {
2022 pFile->locktype = NO_LOCK;
2023 return SQLITE_OK;
2024 }
2025}
2026
2027/*
2028** Close a file.
2029*/
2030static int flockClose(sqlite3_file *id) {
2031 if( id ){
2032 flockUnlock(id, NO_LOCK);
2033 }
2034 return closeUnixFile(id);
2035}
2036
2037#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2038
2039/******************* End of the flock lock implementation *********************
2040******************************************************************************/
2041
2042/******************************************************************************
2043************************ Begin Named Semaphore Locking ************************
2044**
2045** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002046**
2047** Semaphore locking is like dot-lock and flock in that it really only
2048** supports EXCLUSIVE locking. Only a single process can read or write
2049** the database file at a time. This reduces potential concurrency, but
2050** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002051*/
2052#if OS_VXWORKS
2053
drh6b9d6dd2008-12-03 19:34:47 +00002054/*
2055** This routine checks if there is a RESERVED lock held on the specified
2056** file by this or any other process. If such a lock is held, set *pResOut
2057** to a non-zero value otherwise *pResOut is set to zero. The return value
2058** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2059*/
drh734c9862008-11-28 15:37:20 +00002060static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2061 int rc = SQLITE_OK;
2062 int reserved = 0;
2063 unixFile *pFile = (unixFile*)id;
2064
2065 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2066
2067 assert( pFile );
2068
2069 /* Check if a thread in this process holds such a lock */
2070 if( pFile->locktype>SHARED_LOCK ){
2071 reserved = 1;
2072 }
2073
2074 /* Otherwise see if some other process holds it. */
2075 if( !reserved ){
2076 sem_t *pSem = pFile->pOpen->pSem;
2077 struct stat statBuf;
2078
2079 if( sem_trywait(pSem)==-1 ){
2080 int tErrno = errno;
2081 if( EAGAIN != tErrno ){
2082 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2083 pFile->lastErrno = tErrno;
2084 } else {
2085 /* someone else has the lock when we are in NO_LOCK */
2086 reserved = (pFile->locktype < SHARED_LOCK);
2087 }
2088 }else{
2089 /* we could have it if we want it */
2090 sem_post(pSem);
2091 }
2092 }
2093 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2094
2095 *pResOut = reserved;
2096 return rc;
2097}
2098
drh6b9d6dd2008-12-03 19:34:47 +00002099/*
2100** Lock the file with the lock specified by parameter locktype - one
2101** of the following:
2102**
2103** (1) SHARED_LOCK
2104** (2) RESERVED_LOCK
2105** (3) PENDING_LOCK
2106** (4) EXCLUSIVE_LOCK
2107**
2108** Sometimes when requesting one lock state, additional lock states
2109** are inserted in between. The locking might fail on one of the later
2110** transitions leaving the lock state different from what it started but
2111** still short of its goal. The following chart shows the allowed
2112** transitions and the inserted intermediate states:
2113**
2114** UNLOCKED -> SHARED
2115** SHARED -> RESERVED
2116** SHARED -> (PENDING) -> EXCLUSIVE
2117** RESERVED -> (PENDING) -> EXCLUSIVE
2118** PENDING -> EXCLUSIVE
2119**
2120** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2121** lock states in the sqlite3_file structure, but all locks SHARED or
2122** above are really EXCLUSIVE locks and exclude all other processes from
2123** access the file.
2124**
2125** This routine will only increase a lock. Use the sqlite3OsUnlock()
2126** routine to lower a locking level.
2127*/
drh734c9862008-11-28 15:37:20 +00002128static int semLock(sqlite3_file *id, int locktype) {
2129 unixFile *pFile = (unixFile*)id;
2130 int fd;
2131 sem_t *pSem = pFile->pOpen->pSem;
2132 int rc = SQLITE_OK;
2133
2134 /* if we already have a lock, it is exclusive.
2135 ** Just adjust level and punt on outta here. */
2136 if (pFile->locktype > NO_LOCK) {
2137 pFile->locktype = locktype;
2138 rc = SQLITE_OK;
2139 goto sem_end_lock;
2140 }
2141
2142 /* lock semaphore now but bail out when already locked. */
2143 if( sem_trywait(pSem)==-1 ){
2144 rc = SQLITE_BUSY;
2145 goto sem_end_lock;
2146 }
2147
2148 /* got it, set the type and return ok */
2149 pFile->locktype = locktype;
2150
2151 sem_end_lock:
2152 return rc;
2153}
2154
drh6b9d6dd2008-12-03 19:34:47 +00002155/*
2156** Lower the locking level on file descriptor pFile to locktype. locktype
2157** must be either NO_LOCK or SHARED_LOCK.
2158**
2159** If the locking level of the file descriptor is already at or below
2160** the requested locking level, this routine is a no-op.
2161*/
drh734c9862008-11-28 15:37:20 +00002162static int semUnlock(sqlite3_file *id, int locktype) {
2163 unixFile *pFile = (unixFile*)id;
2164 sem_t *pSem = pFile->pOpen->pSem;
2165
2166 assert( pFile );
2167 assert( pSem );
2168 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2169 pFile->locktype, getpid());
2170 assert( locktype<=SHARED_LOCK );
2171
2172 /* no-op if possible */
2173 if( pFile->locktype==locktype ){
2174 return SQLITE_OK;
2175 }
2176
2177 /* shared can just be set because we always have an exclusive */
2178 if (locktype==SHARED_LOCK) {
2179 pFile->locktype = locktype;
2180 return SQLITE_OK;
2181 }
2182
2183 /* no, really unlock. */
2184 if ( sem_post(pSem)==-1 ) {
2185 int rc, tErrno = errno;
2186 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2187 if( IS_LOCK_ERROR(rc) ){
2188 pFile->lastErrno = tErrno;
2189 }
2190 return rc;
2191 }
2192 pFile->locktype = NO_LOCK;
2193 return SQLITE_OK;
2194}
2195
2196/*
2197 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002198 */
drh734c9862008-11-28 15:37:20 +00002199static int semClose(sqlite3_file *id) {
2200 if( id ){
2201 unixFile *pFile = (unixFile*)id;
2202 semUnlock(id, NO_LOCK);
2203 assert( pFile );
2204 unixEnterMutex();
2205 releaseLockInfo(pFile->pLock);
2206 releaseOpenCnt(pFile->pOpen);
2207 closeUnixFile(id);
2208 unixLeaveMutex();
2209 }
2210 return SQLITE_OK;
2211}
2212
2213#endif /* OS_VXWORKS */
2214/*
2215** Named semaphore locking is only available on VxWorks.
2216**
2217*************** End of the named semaphore lock implementation ****************
2218******************************************************************************/
2219
2220
2221/******************************************************************************
2222*************************** Begin AFP Locking *********************************
2223**
2224** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2225** on Apple Macintosh computers - both OS9 and OSX.
2226**
2227** Third-party implementations of AFP are available. But this code here
2228** only works on OSX.
2229*/
2230
drhd2cb50b2009-01-09 21:41:17 +00002231#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002232/*
2233** The afpLockingContext structure contains all afp lock specific state
2234*/
drhbfe66312006-10-03 17:40:40 +00002235typedef struct afpLockingContext afpLockingContext;
2236struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002237 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002238 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002239};
2240
2241struct ByteRangeLockPB2
2242{
2243 unsigned long long offset; /* offset to first byte to lock */
2244 unsigned long long length; /* nbr of bytes to lock */
2245 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2246 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2247 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2248 int fd; /* file desc to assoc this lock with */
2249};
2250
drhfd131da2007-08-07 17:13:03 +00002251#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002252
drh6b9d6dd2008-12-03 19:34:47 +00002253/*
2254** This is a utility for setting or clearing a bit-range lock on an
2255** AFP filesystem.
2256**
2257** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2258*/
2259static int afpSetLock(
2260 const char *path, /* Name of the file to be locked or unlocked */
2261 unixFile *pFile, /* Open file descriptor on path */
2262 unsigned long long offset, /* First byte to be locked */
2263 unsigned long long length, /* Number of bytes to lock */
2264 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002265){
drh6b9d6dd2008-12-03 19:34:47 +00002266 struct ByteRangeLockPB2 pb;
2267 int err;
drhbfe66312006-10-03 17:40:40 +00002268
2269 pb.unLockFlag = setLockFlag ? 0 : 1;
2270 pb.startEndFlag = 0;
2271 pb.offset = offset;
2272 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002273 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002274
2275 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002276 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2277 offset, length);
drhbfe66312006-10-03 17:40:40 +00002278 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2279 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002280 int rc;
2281 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002282 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2283 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002284#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2285 rc = SQLITE_BUSY;
2286#else
drh734c9862008-11-28 15:37:20 +00002287 rc = sqliteErrorFromPosixError(tErrno,
2288 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002289#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002290 if( IS_LOCK_ERROR(rc) ){
2291 pFile->lastErrno = tErrno;
2292 }
2293 return rc;
drhbfe66312006-10-03 17:40:40 +00002294 } else {
aswift5b1a2562008-08-22 00:22:35 +00002295 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002296 }
2297}
2298
drh6b9d6dd2008-12-03 19:34:47 +00002299/*
2300** This routine checks if there is a RESERVED lock held on the specified
2301** file by this or any other process. If such a lock is held, set *pResOut
2302** to a non-zero value otherwise *pResOut is set to zero. The return value
2303** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2304*/
danielk1977e339d652008-06-28 11:23:00 +00002305static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002306 int rc = SQLITE_OK;
2307 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002308 unixFile *pFile = (unixFile*)id;
2309
aswift5b1a2562008-08-22 00:22:35 +00002310 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2311
2312 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002313 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2314
2315 /* Check if a thread in this process holds such a lock */
2316 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002317 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002318 }
2319
2320 /* Otherwise see if some other process holds it.
2321 */
aswift5b1a2562008-08-22 00:22:35 +00002322 if( !reserved ){
2323 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002324 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002325 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002326 /* if we succeeded in taking the reserved lock, unlock it to restore
2327 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002328 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002329 } else {
2330 /* if we failed to get the lock then someone else must have it */
2331 reserved = 1;
2332 }
2333 if( IS_LOCK_ERROR(lrc) ){
2334 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002335 }
2336 }
drhbfe66312006-10-03 17:40:40 +00002337
aswift5b1a2562008-08-22 00:22:35 +00002338 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2339
2340 *pResOut = reserved;
2341 return rc;
drhbfe66312006-10-03 17:40:40 +00002342}
2343
drh6b9d6dd2008-12-03 19:34:47 +00002344/*
2345** Lock the file with the lock specified by parameter locktype - one
2346** of the following:
2347**
2348** (1) SHARED_LOCK
2349** (2) RESERVED_LOCK
2350** (3) PENDING_LOCK
2351** (4) EXCLUSIVE_LOCK
2352**
2353** Sometimes when requesting one lock state, additional lock states
2354** are inserted in between. The locking might fail on one of the later
2355** transitions leaving the lock state different from what it started but
2356** still short of its goal. The following chart shows the allowed
2357** transitions and the inserted intermediate states:
2358**
2359** UNLOCKED -> SHARED
2360** SHARED -> RESERVED
2361** SHARED -> (PENDING) -> EXCLUSIVE
2362** RESERVED -> (PENDING) -> EXCLUSIVE
2363** PENDING -> EXCLUSIVE
2364**
2365** This routine will only increase a lock. Use the sqlite3OsUnlock()
2366** routine to lower a locking level.
2367*/
danielk1977e339d652008-06-28 11:23:00 +00002368static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002369 int rc = SQLITE_OK;
2370 unixFile *pFile = (unixFile*)id;
2371 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002372
2373 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002374 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002375 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2376
drhbfe66312006-10-03 17:40:40 +00002377 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002378 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002379 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002380 */
drhbfe66312006-10-03 17:40:40 +00002381 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002382 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002383 locktypeName(locktype));
2384 return SQLITE_OK;
2385 }
2386
2387 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002388 */
drhbfe66312006-10-03 17:40:40 +00002389 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2390 assert( locktype!=PENDING_LOCK );
2391 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2392
2393 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002394 */
drh6c7d5c52008-11-21 20:32:33 +00002395 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002396
2397 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002398 */
drhbfe66312006-10-03 17:40:40 +00002399 rc = transferOwnership(pFile);
2400 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002401 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002402 return rc;
2403 }
2404
2405 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002406 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2407 ** be released.
2408 */
drhbfe66312006-10-03 17:40:40 +00002409 if( locktype==SHARED_LOCK
2410 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002411 ){
2412 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002413 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002414 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002415 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002416 goto afp_end_lock;
2417 }
2418 }
2419
2420 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002421 ** operating system calls for the specified lock.
2422 */
drhbfe66312006-10-03 17:40:40 +00002423 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002424 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002425
aswift5b1a2562008-08-22 00:22:35 +00002426 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002427 /* note that the quality of the randomness doesn't matter that much */
2428 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002429 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002430 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002431 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002432 if( IS_LOCK_ERROR(lrc1) ){
2433 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002434 }
aswift5b1a2562008-08-22 00:22:35 +00002435 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002436 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002437
aswift5b1a2562008-08-22 00:22:35 +00002438 if( IS_LOCK_ERROR(lrc1) ) {
2439 pFile->lastErrno = lrc1Errno;
2440 rc = lrc1;
2441 goto afp_end_lock;
2442 } else if( IS_LOCK_ERROR(lrc2) ){
2443 rc = lrc2;
2444 goto afp_end_lock;
2445 } else if( lrc1 != SQLITE_OK ) {
2446 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002447 } else {
2448 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002449 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002450 }
2451 }else{
2452 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2453 ** assumed that there is a SHARED or greater lock on the file
2454 ** already.
2455 */
2456 int failed = 0;
2457 assert( 0!=pFile->locktype );
2458 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2459 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002460 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002461 }
2462 if (!failed && locktype == EXCLUSIVE_LOCK) {
2463 /* Acquire an EXCLUSIVE lock */
2464
2465 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002466 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002467 */
drh6b9d6dd2008-12-03 19:34:47 +00002468 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002469 context->sharedByte, 1, 0)) ){
2470 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002471 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002472 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002473 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002474 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002475 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2476 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2477 ** a critical I/O error
2478 */
2479 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2480 SQLITE_IOERR_LOCK;
2481 goto afp_end_lock;
2482 }
2483 }else{
aswift5b1a2562008-08-22 00:22:35 +00002484 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002485 }
2486 }
aswift5b1a2562008-08-22 00:22:35 +00002487 if( failed ){
2488 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002489 }
2490 }
2491
2492 if( rc==SQLITE_OK ){
2493 pFile->locktype = locktype;
2494 }else if( locktype==EXCLUSIVE_LOCK ){
2495 pFile->locktype = PENDING_LOCK;
2496 }
2497
2498afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002499 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002500 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002501 rc==SQLITE_OK ? "ok" : "failed");
2502 return rc;
2503}
2504
2505/*
drh339eb0b2008-03-07 15:34:11 +00002506** Lower the locking level on file descriptor pFile to locktype. locktype
2507** must be either NO_LOCK or SHARED_LOCK.
2508**
2509** If the locking level of the file descriptor is already at or below
2510** the requested locking level, this routine is a no-op.
2511*/
danielk1977e339d652008-06-28 11:23:00 +00002512static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002513 int rc = SQLITE_OK;
2514 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002515 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002516
2517 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002518 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002519 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002520
drhbfe66312006-10-03 17:40:40 +00002521 assert( locktype<=SHARED_LOCK );
2522 if( pFile->locktype<=locktype ){
2523 return SQLITE_OK;
2524 }
2525 if( CHECK_THREADID(pFile) ){
2526 return SQLITE_MISUSE;
2527 }
drh6c7d5c52008-11-21 20:32:33 +00002528 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002529 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002530
2531 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002532 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002533 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2534 /* only re-establish the shared lock if necessary */
2535 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002536 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002537 }
2538 }
2539 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002540 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002541 }
2542 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002543 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002544 }
2545 }else if( locktype==NO_LOCK ){
2546 /* clear the shared lock */
2547 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002548 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002549 }
drhbfe66312006-10-03 17:40:40 +00002550
aswiftaebf4132008-11-21 00:10:35 +00002551 if( rc==SQLITE_OK ){
2552 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002553 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002554 pOpen->nLock--;
2555 assert( pOpen->nLock>=0 );
2556 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2557 int i;
2558 for(i=0; i<pOpen->nPending; i++){
2559 if( pOpen->aPending[i] < 0 ) continue;
2560 if( close(pOpen->aPending[i]) ){
2561 pFile->lastErrno = errno;
2562 rc = SQLITE_IOERR_CLOSE;
2563 }else{
2564 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002565 }
aswiftaebf4132008-11-21 00:10:35 +00002566 }
2567 if( rc==SQLITE_OK ){
2568 sqlite3_free(pOpen->aPending);
2569 pOpen->nPending = 0;
2570 pOpen->aPending = 0;
2571 }
drhbfe66312006-10-03 17:40:40 +00002572 }
2573 }
drhbfe66312006-10-03 17:40:40 +00002574 }
drh6c7d5c52008-11-21 20:32:33 +00002575 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002576 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002577 return rc;
2578}
2579
2580/*
drh339eb0b2008-03-07 15:34:11 +00002581** Close a file & cleanup AFP specific locking context
2582*/
danielk1977e339d652008-06-28 11:23:00 +00002583static int afpClose(sqlite3_file *id) {
2584 if( id ){
2585 unixFile *pFile = (unixFile*)id;
2586 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002587 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002588 if( pFile->pOpen && pFile->pOpen->nLock ){
2589 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002590 ** yet because that would clear those locks. Instead, add the file
2591 ** descriptor to pOpen->aPending. It will be automatically closed when
2592 ** the last lock is cleared.
2593 */
aswiftaebf4132008-11-21 00:10:35 +00002594 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002595 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002596 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2597 if( aNew==0 ){
2598 /* If a malloc fails, just leak the file descriptor */
2599 }else{
2600 pOpen->aPending = aNew;
2601 pOpen->aPending[pOpen->nPending] = pFile->h;
2602 pOpen->nPending++;
2603 pFile->h = -1;
2604 }
2605 }
2606 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002607 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002608 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002609 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002610 }
aswiftaebf4132008-11-21 00:10:35 +00002611 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002612}
2613
drhd2cb50b2009-01-09 21:41:17 +00002614#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002615/*
2616** The code above is the AFP lock implementation. The code is specific
2617** to MacOSX and does not work on other unix platforms. No alternative
2618** is available. If you don't compile for a mac, then the "unix-afp"
2619** VFS is not available.
2620**
2621********************* End of the AFP lock implementation **********************
2622******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002623
drh734c9862008-11-28 15:37:20 +00002624
2625/******************************************************************************
2626**************** Non-locking sqlite3_file methods *****************************
2627**
2628** The next division contains implementations for all methods of the
2629** sqlite3_file object other than the locking methods. The locking
2630** methods were defined in divisions above (one locking method per
2631** division). Those methods that are common to all locking modes
2632** are gather together into this division.
2633*/
drhbfe66312006-10-03 17:40:40 +00002634
2635/*
drh734c9862008-11-28 15:37:20 +00002636** Seek to the offset passed as the second argument, then read cnt
2637** bytes into pBuf. Return the number of bytes actually read.
2638**
2639** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2640** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2641** one system to another. Since SQLite does not define USE_PREAD
2642** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2643** See tickets #2741 and #2681.
2644**
2645** To avoid stomping the errno value on a failed read the lastErrno value
2646** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002647*/
drh734c9862008-11-28 15:37:20 +00002648static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2649 int got;
2650 i64 newOffset;
2651 TIMER_START;
2652#if defined(USE_PREAD)
2653 got = pread(id->h, pBuf, cnt, offset);
2654 SimulateIOError( got = -1 );
2655#elif defined(USE_PREAD64)
2656 got = pread64(id->h, pBuf, cnt, offset);
2657 SimulateIOError( got = -1 );
2658#else
2659 newOffset = lseek(id->h, offset, SEEK_SET);
2660 SimulateIOError( newOffset-- );
2661 if( newOffset!=offset ){
2662 if( newOffset == -1 ){
2663 ((unixFile*)id)->lastErrno = errno;
2664 }else{
2665 ((unixFile*)id)->lastErrno = 0;
2666 }
2667 return -1;
2668 }
2669 got = read(id->h, pBuf, cnt);
2670#endif
2671 TIMER_END;
2672 if( got<0 ){
2673 ((unixFile*)id)->lastErrno = errno;
2674 }
2675 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2676 return got;
drhbfe66312006-10-03 17:40:40 +00002677}
2678
2679/*
drh734c9862008-11-28 15:37:20 +00002680** Read data from a file into a buffer. Return SQLITE_OK if all
2681** bytes were read successfully and SQLITE_IOERR if anything goes
2682** wrong.
drh339eb0b2008-03-07 15:34:11 +00002683*/
drh734c9862008-11-28 15:37:20 +00002684static int unixRead(
2685 sqlite3_file *id,
2686 void *pBuf,
2687 int amt,
2688 sqlite3_int64 offset
2689){
2690 int got;
2691 assert( id );
2692 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
2693 if( got==amt ){
2694 return SQLITE_OK;
2695 }else if( got<0 ){
2696 /* lastErrno set by seekAndRead */
2697 return SQLITE_IOERR_READ;
2698 }else{
2699 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2700 /* Unread parts of the buffer must be zero-filled */
2701 memset(&((char*)pBuf)[got], 0, amt-got);
2702 return SQLITE_IOERR_SHORT_READ;
2703 }
2704}
2705
2706/*
2707** Seek to the offset in id->offset then read cnt bytes into pBuf.
2708** Return the number of bytes actually read. Update the offset.
2709**
2710** To avoid stomping the errno value on a failed write the lastErrno value
2711** is set before returning.
2712*/
2713static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2714 int got;
2715 i64 newOffset;
2716 TIMER_START;
2717#if defined(USE_PREAD)
2718 got = pwrite(id->h, pBuf, cnt, offset);
2719#elif defined(USE_PREAD64)
2720 got = pwrite64(id->h, pBuf, cnt, offset);
2721#else
2722 newOffset = lseek(id->h, offset, SEEK_SET);
2723 if( newOffset!=offset ){
2724 if( newOffset == -1 ){
2725 ((unixFile*)id)->lastErrno = errno;
2726 }else{
2727 ((unixFile*)id)->lastErrno = 0;
2728 }
2729 return -1;
2730 }
2731 got = write(id->h, pBuf, cnt);
2732#endif
2733 TIMER_END;
2734 if( got<0 ){
2735 ((unixFile*)id)->lastErrno = errno;
2736 }
2737
2738 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2739 return got;
2740}
2741
2742
2743/*
2744** Write data from a buffer into a file. Return SQLITE_OK on success
2745** or some other error code on failure.
2746*/
2747static int unixWrite(
2748 sqlite3_file *id,
2749 const void *pBuf,
2750 int amt,
2751 sqlite3_int64 offset
2752){
2753 int wrote = 0;
2754 assert( id );
2755 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002756
2757#ifndef NDEBUG
2758 /* If we are doing a normal write to a database file (as opposed to
2759 ** doing a hot-journal rollback or a write to some file other than a
2760 ** normal database file) then record the fact that the database
2761 ** has changed. If the transaction counter is modified, record that
2762 ** fact too.
2763 */
2764 if( ((unixFile*)id)->inNormalWrite ){
2765 unixFile *pFile = (unixFile*)id;
2766 pFile->dbUpdate = 1; /* The database has been modified */
2767 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002768 int rc;
drh8f941bc2009-01-14 23:03:40 +00002769 char oldCntr[4];
2770 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002771 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002772 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002773 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002774 pFile->transCntrChng = 1; /* The transaction counter has changed */
2775 }
2776 }
2777 }
2778#endif
2779
drh734c9862008-11-28 15:37:20 +00002780 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2781 amt -= wrote;
2782 offset += wrote;
2783 pBuf = &((char*)pBuf)[wrote];
2784 }
2785 SimulateIOError(( wrote=(-1), amt=1 ));
2786 SimulateDiskfullError(( wrote=0, amt=1 ));
2787 if( amt>0 ){
2788 if( wrote<0 ){
2789 /* lastErrno set by seekAndWrite */
2790 return SQLITE_IOERR_WRITE;
2791 }else{
2792 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2793 return SQLITE_FULL;
2794 }
2795 }
2796 return SQLITE_OK;
2797}
2798
2799#ifdef SQLITE_TEST
2800/*
2801** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002802** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002803*/
2804int sqlite3_sync_count = 0;
2805int sqlite3_fullsync_count = 0;
2806#endif
2807
2808/*
2809** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
2810** Otherwise use fsync() in its place.
2811*/
2812#ifndef HAVE_FDATASYNC
2813# define fdatasync fsync
2814#endif
2815
2816/*
2817** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2818** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2819** only available on Mac OS X. But that could change.
2820*/
2821#ifdef F_FULLFSYNC
2822# define HAVE_FULLFSYNC 1
2823#else
2824# define HAVE_FULLFSYNC 0
2825#endif
2826
2827
2828/*
2829** The fsync() system call does not work as advertised on many
2830** unix systems. The following procedure is an attempt to make
2831** it work better.
2832**
2833** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2834** for testing when we want to run through the test suite quickly.
2835** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2836** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2837** or power failure will likely corrupt the database file.
2838*/
2839static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002840 int rc;
drh734c9862008-11-28 15:37:20 +00002841
2842 /* The following "ifdef/elif/else/" block has the same structure as
2843 ** the one below. It is replicated here solely to avoid cluttering
2844 ** up the real code with the UNUSED_PARAMETER() macros.
2845 */
2846#ifdef SQLITE_NO_SYNC
2847 UNUSED_PARAMETER(fd);
2848 UNUSED_PARAMETER(fullSync);
2849 UNUSED_PARAMETER(dataOnly);
2850#elif HAVE_FULLFSYNC
2851 UNUSED_PARAMETER(dataOnly);
2852#else
2853 UNUSED_PARAMETER(fullSync);
2854#endif
2855
2856 /* Record the number of times that we do a normal fsync() and
2857 ** FULLSYNC. This is used during testing to verify that this procedure
2858 ** gets called with the correct arguments.
2859 */
2860#ifdef SQLITE_TEST
2861 if( fullSync ) sqlite3_fullsync_count++;
2862 sqlite3_sync_count++;
2863#endif
2864
2865 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2866 ** no-op
2867 */
2868#ifdef SQLITE_NO_SYNC
2869 rc = SQLITE_OK;
2870#elif HAVE_FULLFSYNC
2871 if( fullSync ){
2872 rc = fcntl(fd, F_FULLFSYNC, 0);
2873 }else{
2874 rc = 1;
2875 }
2876 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002877 ** It shouldn't be possible for fullfsync to fail on the local
2878 ** file system (on OSX), so failure indicates that FULLFSYNC
2879 ** isn't supported for this file system. So, attempt an fsync
2880 ** and (for now) ignore the overhead of a superfluous fcntl call.
2881 ** It'd be better to detect fullfsync support once and avoid
2882 ** the fcntl call every time sync is called.
2883 */
drh734c9862008-11-28 15:37:20 +00002884 if( rc ) rc = fsync(fd);
2885
2886#else
2887 if( dataOnly ){
2888 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002889#if OS_VXWORKS
2890 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002891 rc = fsync(fd);
2892 }
drhc7288ee2009-01-15 04:30:02 +00002893#endif
drh734c9862008-11-28 15:37:20 +00002894 }else{
2895 rc = fsync(fd);
2896 }
2897#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2898
2899 if( OS_VXWORKS && rc!= -1 ){
2900 rc = 0;
2901 }
chw97185482008-11-17 08:05:31 +00002902 return rc;
drhbfe66312006-10-03 17:40:40 +00002903}
2904
drh734c9862008-11-28 15:37:20 +00002905/*
2906** Make sure all writes to a particular file are committed to disk.
2907**
2908** If dataOnly==0 then both the file itself and its metadata (file
2909** size, access time, etc) are synced. If dataOnly!=0 then only the
2910** file data is synced.
2911**
2912** Under Unix, also make sure that the directory entry for the file
2913** has been created by fsync-ing the directory that contains the file.
2914** If we do not do this and we encounter a power failure, the directory
2915** entry for the journal might not exist after we reboot. The next
2916** SQLite to access the file will not know that the journal exists (because
2917** the directory entry for the journal was never created) and the transaction
2918** will not roll back - possibly leading to database corruption.
2919*/
2920static int unixSync(sqlite3_file *id, int flags){
2921 int rc;
2922 unixFile *pFile = (unixFile*)id;
2923
2924 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2925 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2926
2927 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2928 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2929 || (flags&0x0F)==SQLITE_SYNC_FULL
2930 );
2931
2932 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2933 ** line is to test that doing so does not cause any problems.
2934 */
2935 SimulateDiskfullError( return SQLITE_FULL );
2936
2937 assert( pFile );
2938 OSTRACE2("SYNC %-3d\n", pFile->h);
2939 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2940 SimulateIOError( rc=1 );
2941 if( rc ){
2942 pFile->lastErrno = errno;
2943 return SQLITE_IOERR_FSYNC;
2944 }
2945 if( pFile->dirfd>=0 ){
2946 int err;
2947 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2948 HAVE_FULLFSYNC, isFullsync);
2949#ifndef SQLITE_DISABLE_DIRSYNC
2950 /* The directory sync is only attempted if full_fsync is
2951 ** turned off or unavailable. If a full_fsync occurred above,
2952 ** then the directory sync is superfluous.
2953 */
2954 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2955 /*
2956 ** We have received multiple reports of fsync() returning
2957 ** errors when applied to directories on certain file systems.
2958 ** A failed directory sync is not a big deal. So it seems
2959 ** better to ignore the error. Ticket #1657
2960 */
2961 /* pFile->lastErrno = errno; */
2962 /* return SQLITE_IOERR; */
2963 }
2964#endif
2965 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2966 if( err==0 ){ /* directory when we are done */
2967 pFile->dirfd = -1;
2968 }else{
2969 pFile->lastErrno = errno;
2970 rc = SQLITE_IOERR_DIR_CLOSE;
2971 }
2972 }
2973 return rc;
2974}
2975
2976/*
2977** Truncate an open file to a specified size
2978*/
2979static int unixTruncate(sqlite3_file *id, i64 nByte){
2980 int rc;
2981 assert( id );
2982 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2983 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2984 if( rc ){
2985 ((unixFile*)id)->lastErrno = errno;
2986 return SQLITE_IOERR_TRUNCATE;
2987 }else{
2988 return SQLITE_OK;
2989 }
2990}
2991
2992/*
2993** Determine the current size of a file in bytes
2994*/
2995static int unixFileSize(sqlite3_file *id, i64 *pSize){
2996 int rc;
2997 struct stat buf;
2998 assert( id );
2999 rc = fstat(((unixFile*)id)->h, &buf);
3000 SimulateIOError( rc=1 );
3001 if( rc!=0 ){
3002 ((unixFile*)id)->lastErrno = errno;
3003 return SQLITE_IOERR_FSTAT;
3004 }
3005 *pSize = buf.st_size;
3006
3007 /* When opening a zero-size database, the findLockInfo() procedure
3008 ** writes a single byte into that file in order to work around a bug
3009 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3010 ** layers, we need to report this file size as zero even though it is
3011 ** really 1. Ticket #3260.
3012 */
3013 if( *pSize==1 ) *pSize = 0;
3014
3015
3016 return SQLITE_OK;
3017}
3018
drhd2cb50b2009-01-09 21:41:17 +00003019#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003020/*
3021** Handler for proxy-locking file-control verbs. Defined below in the
3022** proxying locking division.
3023*/
3024static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003025#endif
drh715ff302008-12-03 22:32:44 +00003026
danielk1977ad94b582007-08-20 06:44:22 +00003027
danielk1977e3026632004-06-22 11:29:02 +00003028/*
drh9e33c2c2007-08-31 18:34:59 +00003029** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003030*/
drhcc6bb3e2007-08-31 16:11:35 +00003031static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003032 switch( op ){
3033 case SQLITE_FCNTL_LOCKSTATE: {
3034 *(int*)pArg = ((unixFile*)id)->locktype;
3035 return SQLITE_OK;
3036 }
drh7708e972008-11-29 00:56:52 +00003037 case SQLITE_LAST_ERRNO: {
3038 *(int*)pArg = ((unixFile*)id)->lastErrno;
3039 return SQLITE_OK;
3040 }
drh8f941bc2009-01-14 23:03:40 +00003041#ifndef NDEBUG
3042 /* The pager calls this method to signal that it has done
3043 ** a rollback and that the database is therefore unchanged and
3044 ** it hence it is OK for the transaction change counter to be
3045 ** unchanged.
3046 */
3047 case SQLITE_FCNTL_DB_UNCHANGED: {
3048 ((unixFile*)id)->dbUpdate = 0;
3049 return SQLITE_OK;
3050 }
3051#endif
drhd2cb50b2009-01-09 21:41:17 +00003052#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003053 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003054 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003055 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003056 }
drhd2cb50b2009-01-09 21:41:17 +00003057#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003058 }
drhcc6bb3e2007-08-31 16:11:35 +00003059 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003060}
3061
3062/*
danielk1977a3d4c882007-03-23 10:08:38 +00003063** Return the sector size in bytes of the underlying block device for
3064** the specified file. This is almost always 512 bytes, but may be
3065** larger for some devices.
3066**
3067** SQLite code assumes this function cannot fail. It also assumes that
3068** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003069** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003070** same for both.
3071*/
danielk1977397d65f2008-11-19 11:35:39 +00003072static int unixSectorSize(sqlite3_file *NotUsed){
3073 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003074 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003075}
3076
danielk197790949c22007-08-17 16:50:38 +00003077/*
danielk1977397d65f2008-11-19 11:35:39 +00003078** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003079*/
danielk1977397d65f2008-11-19 11:35:39 +00003080static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3081 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003082 return 0;
3083}
3084
drh734c9862008-11-28 15:37:20 +00003085/*
3086** Here ends the implementation of all sqlite3_file methods.
3087**
3088********************** End sqlite3_file Methods *******************************
3089******************************************************************************/
3090
3091/*
drh6b9d6dd2008-12-03 19:34:47 +00003092** This division contains definitions of sqlite3_io_methods objects that
3093** implement various file locking strategies. It also contains definitions
3094** of "finder" functions. A finder-function is used to locate the appropriate
3095** sqlite3_io_methods object for a particular database file. The pAppData
3096** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3097** the correct finder-function for that VFS.
3098**
3099** Most finder functions return a pointer to a fixed sqlite3_io_methods
3100** object. The only interesting finder-function is autolockIoFinder, which
3101** looks at the filesystem type and tries to guess the best locking
3102** strategy from that.
3103**
drh1875f7a2008-12-08 18:19:17 +00003104** For finder-funtion F, two objects are created:
3105**
3106** (1) The real finder-function named "FImpt()".
3107**
3108** (2) A constant pointer to this functio named just "F".
3109**
3110**
3111** A pointer to the F pointer is used as the pAppData value for VFS
3112** objects. We have to do this instead of letting pAppData point
3113** directly at the finder-function since C90 rules prevent a void*
3114** from be cast into a function pointer.
3115**
drh6b9d6dd2008-12-03 19:34:47 +00003116**
drh7708e972008-11-29 00:56:52 +00003117** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003118**
drh7708e972008-11-29 00:56:52 +00003119** * A constant sqlite3_io_methods object call METHOD that has locking
3120** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3121**
3122** * An I/O method finder function called FINDER that returns a pointer
3123** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003124*/
drh7708e972008-11-29 00:56:52 +00003125#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3126static const sqlite3_io_methods METHOD = { \
3127 1, /* iVersion */ \
3128 CLOSE, /* xClose */ \
3129 unixRead, /* xRead */ \
3130 unixWrite, /* xWrite */ \
3131 unixTruncate, /* xTruncate */ \
3132 unixSync, /* xSync */ \
3133 unixFileSize, /* xFileSize */ \
3134 LOCK, /* xLock */ \
3135 UNLOCK, /* xUnlock */ \
3136 CKLOCK, /* xCheckReservedLock */ \
3137 unixFileControl, /* xFileControl */ \
3138 unixSectorSize, /* xSectorSize */ \
3139 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3140}; \
drh1875f7a2008-12-08 18:19:17 +00003141static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003142 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3143 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003144} \
3145static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3146 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003147
3148/*
3149** Here are all of the sqlite3_io_methods objects for each of the
3150** locking strategies. Functions that return pointers to these methods
3151** are also created.
3152*/
3153IOMETHODS(
3154 posixIoFinder, /* Finder function name */
3155 posixIoMethods, /* sqlite3_io_methods object name */
3156 unixClose, /* xClose method */
3157 unixLock, /* xLock method */
3158 unixUnlock, /* xUnlock method */
3159 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003160)
drh7708e972008-11-29 00:56:52 +00003161IOMETHODS(
3162 nolockIoFinder, /* Finder function name */
3163 nolockIoMethods, /* sqlite3_io_methods object name */
3164 nolockClose, /* xClose method */
3165 nolockLock, /* xLock method */
3166 nolockUnlock, /* xUnlock method */
3167 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003168)
drh7708e972008-11-29 00:56:52 +00003169IOMETHODS(
3170 dotlockIoFinder, /* Finder function name */
3171 dotlockIoMethods, /* sqlite3_io_methods object name */
3172 dotlockClose, /* xClose method */
3173 dotlockLock, /* xLock method */
3174 dotlockUnlock, /* xUnlock method */
3175 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003176)
drh7708e972008-11-29 00:56:52 +00003177
3178#if SQLITE_ENABLE_LOCKING_STYLE
3179IOMETHODS(
3180 flockIoFinder, /* Finder function name */
3181 flockIoMethods, /* sqlite3_io_methods object name */
3182 flockClose, /* xClose method */
3183 flockLock, /* xLock method */
3184 flockUnlock, /* xUnlock method */
3185 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003186)
drh7708e972008-11-29 00:56:52 +00003187#endif
3188
drh6c7d5c52008-11-21 20:32:33 +00003189#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003190IOMETHODS(
3191 semIoFinder, /* Finder function name */
3192 semIoMethods, /* sqlite3_io_methods object name */
3193 semClose, /* xClose method */
3194 semLock, /* xLock method */
3195 semUnlock, /* xUnlock method */
3196 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003197)
aswiftaebf4132008-11-21 00:10:35 +00003198#endif
drh7708e972008-11-29 00:56:52 +00003199
drhd2cb50b2009-01-09 21:41:17 +00003200#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003201IOMETHODS(
3202 afpIoFinder, /* Finder function name */
3203 afpIoMethods, /* sqlite3_io_methods object name */
3204 afpClose, /* xClose method */
3205 afpLock, /* xLock method */
3206 afpUnlock, /* xUnlock method */
3207 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003208)
drh715ff302008-12-03 22:32:44 +00003209#endif
3210
3211/*
3212** The proxy locking method is a "super-method" in the sense that it
3213** opens secondary file descriptors for the conch and lock files and
3214** it uses proxy, dot-file, AFP, and flock() locking methods on those
3215** secondary files. For this reason, the division that implements
3216** proxy locking is located much further down in the file. But we need
3217** to go ahead and define the sqlite3_io_methods and finder function
3218** for proxy locking here. So we forward declare the I/O methods.
3219*/
drhd2cb50b2009-01-09 21:41:17 +00003220#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003221static int proxyClose(sqlite3_file*);
3222static int proxyLock(sqlite3_file*, int);
3223static int proxyUnlock(sqlite3_file*, int);
3224static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003225IOMETHODS(
3226 proxyIoFinder, /* Finder function name */
3227 proxyIoMethods, /* sqlite3_io_methods object name */
3228 proxyClose, /* xClose method */
3229 proxyLock, /* xLock method */
3230 proxyUnlock, /* xUnlock method */
3231 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003232)
aswiftaebf4132008-11-21 00:10:35 +00003233#endif
drh7708e972008-11-29 00:56:52 +00003234
3235
drhd2cb50b2009-01-09 21:41:17 +00003236#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003237/*
drh6b9d6dd2008-12-03 19:34:47 +00003238** This "finder" function attempts to determine the best locking strategy
3239** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003240** object that implements that strategy.
3241**
3242** This is for MacOSX only.
3243*/
drh1875f7a2008-12-08 18:19:17 +00003244static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003245 const char *filePath, /* name of the database file */
3246 int fd /* file descriptor open on the database file */
3247){
3248 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003249 const char *zFilesystem; /* Filesystem type name */
3250 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003251 } aMap[] = {
3252 { "hfs", &posixIoMethods },
3253 { "ufs", &posixIoMethods },
3254 { "afpfs", &afpIoMethods },
3255#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3256 { "smbfs", &afpIoMethods },
3257#else
3258 { "smbfs", &flockIoMethods },
3259#endif
3260 { "webdav", &nolockIoMethods },
3261 { 0, 0 }
3262 };
3263 int i;
3264 struct statfs fsInfo;
3265 struct flock lockInfo;
3266
3267 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003268 /* If filePath==NULL that means we are dealing with a transient file
3269 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003270 return &nolockIoMethods;
3271 }
3272 if( statfs(filePath, &fsInfo) != -1 ){
3273 if( fsInfo.f_flags & MNT_RDONLY ){
3274 return &nolockIoMethods;
3275 }
3276 for(i=0; aMap[i].zFilesystem; i++){
3277 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3278 return aMap[i].pMethods;
3279 }
3280 }
3281 }
3282
3283 /* Default case. Handles, amongst others, "nfs".
3284 ** Test byte-range lock using fcntl(). If the call succeeds,
3285 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003286 */
drh7708e972008-11-29 00:56:52 +00003287 lockInfo.l_len = 1;
3288 lockInfo.l_start = 0;
3289 lockInfo.l_whence = SEEK_SET;
3290 lockInfo.l_type = F_RDLCK;
3291 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3292 return &posixIoMethods;
3293 }else{
3294 return &dotlockIoMethods;
3295 }
3296}
danielk1977852e2322008-12-22 03:36:59 +00003297static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003298 = autolockIoFinderImpl;
3299
drhd2cb50b2009-01-09 21:41:17 +00003300#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003301
3302/*
3303** An abstract type for a pointer to a IO method finder function:
3304*/
3305typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3306
aswiftaebf4132008-11-21 00:10:35 +00003307
drh734c9862008-11-28 15:37:20 +00003308/****************************************************************************
3309**************************** sqlite3_vfs methods ****************************
3310**
3311** This division contains the implementation of methods on the
3312** sqlite3_vfs object.
3313*/
3314
danielk1977a3d4c882007-03-23 10:08:38 +00003315/*
danielk1977e339d652008-06-28 11:23:00 +00003316** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003317*/
3318static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003319 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003320 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003321 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003322 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003323 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003324 int noLock, /* Omit locking if true */
3325 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003326){
drh7708e972008-11-29 00:56:52 +00003327 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003328 unixFile *pNew = (unixFile *)pId;
3329 int rc = SQLITE_OK;
3330
danielk197717b90b52008-06-06 11:11:25 +00003331 assert( pNew->pLock==NULL );
3332 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003333
drh715ff302008-12-03 22:32:44 +00003334 /* Parameter isDelete is only used on vxworks.
3335 ** Express this explicitly here to prevent compiler warnings
3336 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003337 */
drh7708e972008-11-29 00:56:52 +00003338#if !OS_VXWORKS
3339 UNUSED_PARAMETER(isDelete);
3340#endif
danielk1977a03396a2008-11-19 14:35:46 +00003341
drh218c5082008-03-07 00:27:10 +00003342 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003343 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003344 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003345 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003346
drh6c7d5c52008-11-21 20:32:33 +00003347#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003348 pNew->pId = vxworksFindFileId(zFilename);
3349 if( pNew->pId==0 ){
3350 noLock = 1;
3351 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003352 }
3353#endif
3354
drhda0e7682008-07-30 15:27:54 +00003355 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003356 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003357 }else{
drh1875f7a2008-12-08 18:19:17 +00003358 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003359#if SQLITE_ENABLE_LOCKING_STYLE
3360 /* Cache zFilename in the locking context (AFP and dotlock override) for
3361 ** proxyLock activation is possible (remote proxy is based on db name)
3362 ** zFilename remains valid until file is closed, to support */
3363 pNew->lockingContext = (void*)zFilename;
3364#endif
drhda0e7682008-07-30 15:27:54 +00003365 }
danielk1977e339d652008-06-28 11:23:00 +00003366
drh7708e972008-11-29 00:56:52 +00003367 if( pLockingStyle == &posixIoMethods ){
3368 unixEnterMutex();
3369 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3370 unixLeaveMutex();
3371 }
danielk1977e339d652008-06-28 11:23:00 +00003372
drhd2cb50b2009-01-09 21:41:17 +00003373#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003374 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003375 /* AFP locking uses the file path so it needs to be included in
3376 ** the afpLockingContext.
3377 */
3378 afpLockingContext *pCtx;
3379 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3380 if( pCtx==0 ){
3381 rc = SQLITE_NOMEM;
3382 }else{
3383 /* NB: zFilename exists and remains valid until the file is closed
3384 ** according to requirement F11141. So we do not need to make a
3385 ** copy of the filename. */
3386 pCtx->dbPath = zFilename;
3387 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003388 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003389 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3390 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003391 }
drh7708e972008-11-29 00:56:52 +00003392 }
3393#endif
danielk1977e339d652008-06-28 11:23:00 +00003394
drh7708e972008-11-29 00:56:52 +00003395 else if( pLockingStyle == &dotlockIoMethods ){
3396 /* Dotfile locking uses the file path so it needs to be included in
3397 ** the dotlockLockingContext
3398 */
3399 char *zLockFile;
3400 int nFilename;
drhea678832008-12-10 19:26:22 +00003401 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003402 zLockFile = (char *)sqlite3_malloc(nFilename);
3403 if( zLockFile==0 ){
3404 rc = SQLITE_NOMEM;
3405 }else{
3406 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003407 }
drh7708e972008-11-29 00:56:52 +00003408 pNew->lockingContext = zLockFile;
3409 }
danielk1977e339d652008-06-28 11:23:00 +00003410
drh6c7d5c52008-11-21 20:32:33 +00003411#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003412 else if( pLockingStyle == &semIoMethods ){
3413 /* Named semaphore locking uses the file path so it needs to be
3414 ** included in the semLockingContext
3415 */
3416 unixEnterMutex();
3417 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3418 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3419 char *zSemName = pNew->pOpen->aSemName;
3420 int n;
3421 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3422 pNew->pId->zCanonicalName);
3423 for( n=0; zSemName[n]; n++ )
3424 if( zSemName[n]=='/' ) zSemName[n] = '_';
3425 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3426 if( pNew->pOpen->pSem == SEM_FAILED ){
3427 rc = SQLITE_NOMEM;
3428 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003429 }
chw97185482008-11-17 08:05:31 +00003430 }
drh7708e972008-11-29 00:56:52 +00003431 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003432 }
drh7708e972008-11-29 00:56:52 +00003433#endif
aswift5b1a2562008-08-22 00:22:35 +00003434
3435 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003436#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003437 if( rc!=SQLITE_OK ){
3438 unlink(zFilename);
3439 isDelete = 0;
3440 }
3441 pNew->isDelete = isDelete;
3442#endif
danielk1977e339d652008-06-28 11:23:00 +00003443 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003444 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003445 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003446 }else{
drh7708e972008-11-29 00:56:52 +00003447 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003448 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003449 }
danielk1977e339d652008-06-28 11:23:00 +00003450 return rc;
drh054889e2005-11-30 03:20:31 +00003451}
drh9c06c952005-11-26 00:25:00 +00003452
danielk1977ad94b582007-08-20 06:44:22 +00003453/*
3454** Open a file descriptor to the directory containing file zFilename.
3455** If successful, *pFd is set to the opened file descriptor and
3456** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3457** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3458** value.
3459**
3460** If SQLITE_OK is returned, the caller is responsible for closing
3461** the file descriptor *pFd using close().
3462*/
danielk1977fee2d252007-08-18 10:59:19 +00003463static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003464 int ii;
drh777b17a2007-09-20 10:02:54 +00003465 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003466 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003467
drh153c62c2007-08-24 03:51:33 +00003468 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003469 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003470 if( ii>0 ){
3471 zDirname[ii] = '\0';
3472 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003473 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003474#ifdef FD_CLOEXEC
3475 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3476#endif
3477 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3478 }
3479 }
danielk1977fee2d252007-08-18 10:59:19 +00003480 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003481 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003482}
3483
danielk1977b4b47412007-08-17 15:53:36 +00003484/*
danielk197717b90b52008-06-06 11:11:25 +00003485** Create a temporary file name in zBuf. zBuf must be allocated
3486** by the calling process and must be big enough to hold at least
3487** pVfs->mxPathname bytes.
3488*/
3489static int getTempname(int nBuf, char *zBuf){
3490 static const char *azDirs[] = {
3491 0,
aswiftaebf4132008-11-21 00:10:35 +00003492 0,
danielk197717b90b52008-06-06 11:11:25 +00003493 "/var/tmp",
3494 "/usr/tmp",
3495 "/tmp",
3496 ".",
3497 };
3498 static const unsigned char zChars[] =
3499 "abcdefghijklmnopqrstuvwxyz"
3500 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3501 "0123456789";
drh41022642008-11-21 00:24:42 +00003502 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003503 struct stat buf;
3504 const char *zDir = ".";
3505
3506 /* It's odd to simulate an io-error here, but really this is just
3507 ** using the io-error infrastructure to test that SQLite handles this
3508 ** function failing.
3509 */
3510 SimulateIOError( return SQLITE_IOERR );
3511
3512 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003513 if (NULL == azDirs[1]) {
3514 azDirs[1] = getenv("TMPDIR");
3515 }
3516
3517 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003518 if( azDirs[i]==0 ) continue;
3519 if( stat(azDirs[i], &buf) ) continue;
3520 if( !S_ISDIR(buf.st_mode) ) continue;
3521 if( access(azDirs[i], 07) ) continue;
3522 zDir = azDirs[i];
3523 break;
3524 }
3525
3526 /* Check that the output buffer is large enough for the temporary file
3527 ** name. If it is not, return SQLITE_ERROR.
3528 */
danielk197700e13612008-11-17 19:18:54 +00003529 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003530 return SQLITE_ERROR;
3531 }
3532
3533 do{
3534 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003535 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003536 sqlite3_randomness(15, &zBuf[j]);
3537 for(i=0; i<15; i++, j++){
3538 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3539 }
3540 zBuf[j] = 0;
3541 }while( access(zBuf,0)==0 );
3542 return SQLITE_OK;
3543}
3544
drhd2cb50b2009-01-09 21:41:17 +00003545#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003546/*
3547** Routine to transform a unixFile into a proxy-locking unixFile.
3548** Implementation in the proxy-lock division, but used by unixOpen()
3549** if SQLITE_PREFER_PROXY_LOCKING is defined.
3550*/
3551static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003552#endif
drhc66d5b62008-12-03 22:48:32 +00003553
danielk197717b90b52008-06-06 11:11:25 +00003554
3555/*
danielk1977ad94b582007-08-20 06:44:22 +00003556** Open the file zPath.
3557**
danielk1977b4b47412007-08-17 15:53:36 +00003558** Previously, the SQLite OS layer used three functions in place of this
3559** one:
3560**
3561** sqlite3OsOpenReadWrite();
3562** sqlite3OsOpenReadOnly();
3563** sqlite3OsOpenExclusive();
3564**
3565** These calls correspond to the following combinations of flags:
3566**
3567** ReadWrite() -> (READWRITE | CREATE)
3568** ReadOnly() -> (READONLY)
3569** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3570**
3571** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3572** true, the file was configured to be automatically deleted when the
3573** file handle closed. To achieve the same effect using this new
3574** interface, add the DELETEONCLOSE flag to those specified above for
3575** OpenExclusive().
3576*/
3577static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003578 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3579 const char *zPath, /* Pathname of file to be opened */
3580 sqlite3_file *pFile, /* The file descriptor to be filled in */
3581 int flags, /* Input flags to control the opening */
3582 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003583){
danielk1977fee2d252007-08-18 10:59:19 +00003584 int fd = 0; /* File descriptor returned by open() */
3585 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003586 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003587 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003588 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003589 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003590
3591 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3592 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3593 int isCreate = (flags & SQLITE_OPEN_CREATE);
3594 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3595 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3596
danielk1977fee2d252007-08-18 10:59:19 +00003597 /* If creating a master or main-file journal, this function will open
3598 ** a file-descriptor on the directory too. The first time unixSync()
3599 ** is called the directory file descriptor will be fsync()ed and close()d.
3600 */
3601 int isOpenDirectory = (isCreate &&
3602 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3603 );
3604
danielk197717b90b52008-06-06 11:11:25 +00003605 /* If argument zPath is a NULL pointer, this function is required to open
3606 ** a temporary file. Use this buffer to store the file name in.
3607 */
3608 char zTmpname[MAX_PATHNAME+1];
3609 const char *zName = zPath;
3610
danielk1977fee2d252007-08-18 10:59:19 +00003611 /* Check the following statements are true:
3612 **
3613 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3614 ** (b) if CREATE is set, then READWRITE must also be set, and
3615 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003616 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003617 */
danielk1977b4b47412007-08-17 15:53:36 +00003618 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003619 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003620 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003621 assert(isDelete==0 || isCreate);
3622
drh33f4e022007-09-03 15:19:34 +00003623 /* The main DB, main journal, and master journal are never automatically
3624 ** deleted
3625 */
3626 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3627 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3628 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003629
danielk1977fee2d252007-08-18 10:59:19 +00003630 /* Assert that the upper layer has set one of the "file-type" flags. */
3631 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3632 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3633 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003634 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003635 );
3636
danielk1977e339d652008-06-28 11:23:00 +00003637 memset(pFile, 0, sizeof(unixFile));
3638
danielk197717b90b52008-06-06 11:11:25 +00003639 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003640 assert(isDelete && !isOpenDirectory);
3641 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3642 if( rc!=SQLITE_OK ){
3643 return rc;
3644 }
3645 zName = zTmpname;
3646 }
3647
drh734c9862008-11-28 15:37:20 +00003648 if( isReadonly ) openFlags |= O_RDONLY;
3649 if( isReadWrite ) openFlags |= O_RDWR;
3650 if( isCreate ) openFlags |= O_CREAT;
3651 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3652 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003653
drh734c9862008-11-28 15:37:20 +00003654 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3655 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003656 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003657 /* Failed to open the file for read/write access. Try read-only. */
3658 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3659 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003660 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003661 }
3662 if( fd<0 ){
3663 return SQLITE_CANTOPEN;
3664 }
3665 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003666#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003667 zPath = zName;
3668#else
danielk197717b90b52008-06-06 11:11:25 +00003669 unlink(zName);
chw97185482008-11-17 08:05:31 +00003670#endif
danielk1977b4b47412007-08-17 15:53:36 +00003671 }
drh41022642008-11-21 00:24:42 +00003672#if SQLITE_ENABLE_LOCKING_STYLE
3673 else{
drh734c9862008-11-28 15:37:20 +00003674 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003675 }
3676#endif
danielk1977b4b47412007-08-17 15:53:36 +00003677 if( pOutFlags ){
3678 *pOutFlags = flags;
3679 }
3680
3681 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00003682 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003683 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003684 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003685 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003686 return rc;
3687 }
3688 }
danielk1977e339d652008-06-28 11:23:00 +00003689
3690#ifdef FD_CLOEXEC
3691 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3692#endif
3693
drhda0e7682008-07-30 15:27:54 +00003694 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003695
3696#if SQLITE_PREFER_PROXY_LOCKING
3697 if( zPath!=NULL && !noLock ){
3698 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3699 int useProxy = 0;
3700
3701 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003702 ** 0 means never use proxy, NULL means use proxy for non-local files only
3703 */
aswiftaebf4132008-11-21 00:10:35 +00003704 if( envforce!=NULL ){
3705 useProxy = atoi(envforce)>0;
3706 }else{
3707 struct statfs fsInfo;
3708
3709 if( statfs(zPath, &fsInfo) == -1 ){
3710 ((unixFile*)pFile)->lastErrno = errno;
3711 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3712 close(fd); /* silently leak if fail, in error */
3713 return SQLITE_IOERR_ACCESS;
3714 }
3715 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3716 }
3717 if( useProxy ){
3718 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3719 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003720 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003721 }
3722 return rc;
3723 }
3724 }
3725#endif
3726
chw97185482008-11-17 08:05:31 +00003727 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003728}
3729
3730/*
danielk1977fee2d252007-08-18 10:59:19 +00003731** Delete the file at zPath. If the dirSync argument is true, fsync()
3732** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003733*/
drh6b9d6dd2008-12-03 19:34:47 +00003734static int unixDelete(
3735 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3736 const char *zPath, /* Name of file to be deleted */
3737 int dirSync /* If true, fsync() directory after deleting file */
3738){
danielk1977fee2d252007-08-18 10:59:19 +00003739 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003740 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003741 SimulateIOError(return SQLITE_IOERR_DELETE);
3742 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003743#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003744 if( dirSync ){
3745 int fd;
3746 rc = openDirectory(zPath, &fd);
3747 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003748#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003749 if( fsync(fd)==-1 )
3750#else
3751 if( fsync(fd) )
3752#endif
3753 {
danielk1977fee2d252007-08-18 10:59:19 +00003754 rc = SQLITE_IOERR_DIR_FSYNC;
3755 }
aswiftaebf4132008-11-21 00:10:35 +00003756 if( close(fd)&&!rc ){
3757 rc = SQLITE_IOERR_DIR_CLOSE;
3758 }
danielk1977fee2d252007-08-18 10:59:19 +00003759 }
3760 }
danielk1977d138dd82008-10-15 16:02:48 +00003761#endif
danielk1977fee2d252007-08-18 10:59:19 +00003762 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003763}
3764
danielk197790949c22007-08-17 16:50:38 +00003765/*
3766** Test the existance of or access permissions of file zPath. The
3767** test performed depends on the value of flags:
3768**
3769** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3770** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3771** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3772**
3773** Otherwise return 0.
3774*/
danielk1977861f7452008-06-05 11:39:11 +00003775static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003776 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3777 const char *zPath, /* Path of the file to examine */
3778 int flags, /* What do we want to learn about the zPath file? */
3779 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003780){
rse25c0d1a2007-09-20 08:38:14 +00003781 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003782 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003783 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003784 switch( flags ){
3785 case SQLITE_ACCESS_EXISTS:
3786 amode = F_OK;
3787 break;
3788 case SQLITE_ACCESS_READWRITE:
3789 amode = W_OK|R_OK;
3790 break;
drh50d3f902007-08-27 21:10:36 +00003791 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003792 amode = R_OK;
3793 break;
3794
3795 default:
3796 assert(!"Invalid flags argument");
3797 }
danielk1977861f7452008-06-05 11:39:11 +00003798 *pResOut = (access(zPath, amode)==0);
3799 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003800}
3801
danielk1977b4b47412007-08-17 15:53:36 +00003802
3803/*
3804** Turn a relative pathname into a full pathname. The relative path
3805** is stored as a nul-terminated string in the buffer pointed to by
3806** zPath.
3807**
3808** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3809** (in this case, MAX_PATHNAME bytes). The full-path is written to
3810** this buffer before returning.
3811*/
danielk1977adfb9b02007-09-17 07:02:56 +00003812static int unixFullPathname(
3813 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3814 const char *zPath, /* Possibly relative input path */
3815 int nOut, /* Size of output buffer in bytes */
3816 char *zOut /* Output buffer */
3817){
danielk1977843e65f2007-09-01 16:16:15 +00003818
3819 /* It's odd to simulate an io-error here, but really this is just
3820 ** using the io-error infrastructure to test that SQLite handles this
3821 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003822 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003823 */
3824 SimulateIOError( return SQLITE_ERROR );
3825
drh153c62c2007-08-24 03:51:33 +00003826 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003827 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003828
drh3c7f2dc2007-12-06 13:26:20 +00003829 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003830 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003831 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003832 }else{
3833 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003834 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003835 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003836 }
drhea678832008-12-10 19:26:22 +00003837 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003838 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003839 }
3840 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003841}
3842
drh0ccebe72005-06-07 22:22:50 +00003843
drh761df872006-12-21 01:29:22 +00003844#ifndef SQLITE_OMIT_LOAD_EXTENSION
3845/*
3846** Interfaces for opening a shared library, finding entry points
3847** within the shared library, and closing the shared library.
3848*/
3849#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003850static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3851 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003852 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3853}
danielk197795c8a542007-09-01 06:51:27 +00003854
3855/*
3856** SQLite calls this function immediately after a call to unixDlSym() or
3857** unixDlOpen() fails (returns a null pointer). If a more detailed error
3858** message is available, it is written to zBufOut. If no error message
3859** is available, zBufOut is left unmodified and SQLite uses a default
3860** error message.
3861*/
danielk1977397d65f2008-11-19 11:35:39 +00003862static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003863 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003864 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003865 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003866 zErr = dlerror();
3867 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003868 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003869 }
drh6c7d5c52008-11-21 20:32:33 +00003870 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003871}
drh1875f7a2008-12-08 18:19:17 +00003872static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3873 /*
3874 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3875 ** cast into a pointer to a function. And yet the library dlsym() routine
3876 ** returns a void* which is really a pointer to a function. So how do we
3877 ** use dlsym() with -pedantic-errors?
3878 **
3879 ** Variable x below is defined to be a pointer to a function taking
3880 ** parameters void* and const char* and returning a pointer to a function.
3881 ** We initialize x by assigning it a pointer to the dlsym() function.
3882 ** (That assignment requires a cast.) Then we call the function that
3883 ** x points to.
3884 **
3885 ** This work-around is unlikely to work correctly on any system where
3886 ** you really cannot cast a function pointer into void*. But then, on the
3887 ** other hand, dlsym() will not work on such a system either, so we have
3888 ** not really lost anything.
3889 */
3890 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003891 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003892 x = (void(*(*)(void*,const char*))(void))dlsym;
3893 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003894}
danielk1977397d65f2008-11-19 11:35:39 +00003895static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
3896 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003897 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003898}
danielk1977b4b47412007-08-17 15:53:36 +00003899#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3900 #define unixDlOpen 0
3901 #define unixDlError 0
3902 #define unixDlSym 0
3903 #define unixDlClose 0
3904#endif
3905
3906/*
danielk197790949c22007-08-17 16:50:38 +00003907** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003908*/
danielk1977397d65f2008-11-19 11:35:39 +00003909static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
3910 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00003911 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00003912
drhbbd42a62004-05-22 17:41:58 +00003913 /* We have to initialize zBuf to prevent valgrind from reporting
3914 ** errors. The reports issued by valgrind are incorrect - we would
3915 ** prefer that the randomness be increased by making use of the
3916 ** uninitialized space in zBuf - but valgrind errors tend to worry
3917 ** some users. Rather than argue, it seems easier just to initialize
3918 ** the whole array and silence valgrind, even if that means less randomness
3919 ** in the random seed.
3920 **
3921 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00003922 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00003923 ** tests repeatable.
3924 */
danielk1977b4b47412007-08-17 15:53:36 +00003925 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00003926#if !defined(SQLITE_TEST)
3927 {
drh842b8642005-01-21 17:53:17 +00003928 int pid, fd;
3929 fd = open("/dev/urandom", O_RDONLY);
3930 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00003931 time_t t;
3932 time(&t);
danielk197790949c22007-08-17 16:50:38 +00003933 memcpy(zBuf, &t, sizeof(t));
3934 pid = getpid();
3935 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00003936 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00003937 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00003938 }else{
drh72cbd072008-10-14 17:58:38 +00003939 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00003940 close(fd);
3941 }
drhbbd42a62004-05-22 17:41:58 +00003942 }
3943#endif
drh72cbd072008-10-14 17:58:38 +00003944 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00003945}
3946
danielk1977b4b47412007-08-17 15:53:36 +00003947
drhbbd42a62004-05-22 17:41:58 +00003948/*
3949** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00003950** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00003951** The return value is the number of microseconds of sleep actually
3952** requested from the underlying operating system, a number which
3953** might be greater than or equal to the argument, but not less
3954** than the argument.
drhbbd42a62004-05-22 17:41:58 +00003955*/
danielk1977397d65f2008-11-19 11:35:39 +00003956static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00003957#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003958 struct timespec sp;
3959
3960 sp.tv_sec = microseconds / 1000000;
3961 sp.tv_nsec = (microseconds % 1000000) * 1000;
3962 nanosleep(&sp, NULL);
danielk1977397d65f2008-11-19 11:35:39 +00003963 return microseconds;
3964#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00003965 usleep(microseconds);
3966 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00003967#else
danielk1977b4b47412007-08-17 15:53:36 +00003968 int seconds = (microseconds+999999)/1000000;
3969 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00003970 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00003971#endif
danielk1977397d65f2008-11-19 11:35:39 +00003972 UNUSED_PARAMETER(NotUsed);
drh88f474a2006-01-02 20:00:12 +00003973}
3974
3975/*
drh6b9d6dd2008-12-03 19:34:47 +00003976** The following variable, if set to a non-zero value, is interpreted as
3977** the number of seconds since 1970 and is used to set the result of
3978** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00003979*/
3980#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00003981int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00003982#endif
3983
3984/*
3985** Find the current time (in Universal Coordinated Time). Write the
3986** current time and date as a Julian Day number into *prNow and
3987** return 0. Return 1 if the time and date cannot be found.
3988*/
danielk1977397d65f2008-11-19 11:35:39 +00003989static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh6c7d5c52008-11-21 20:32:33 +00003990#if defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00003991 time_t t;
3992 time(&t);
3993 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00003994#elif OS_VXWORKS
3995 struct timespec sNow;
3996 clock_gettime(CLOCK_REALTIME, &sNow);
3997 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00003998#else
3999 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004000 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004001 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4002#endif
danielk1977397d65f2008-11-19 11:35:39 +00004003
drhbbd42a62004-05-22 17:41:58 +00004004#ifdef SQLITE_TEST
4005 if( sqlite3_current_time ){
4006 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4007 }
4008#endif
danielk1977397d65f2008-11-19 11:35:39 +00004009 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004010 return 0;
4011}
danielk1977b4b47412007-08-17 15:53:36 +00004012
drh6b9d6dd2008-12-03 19:34:47 +00004013/*
4014** We added the xGetLastError() method with the intention of providing
4015** better low-level error messages when operating-system problems come up
4016** during SQLite operation. But so far, none of that has been implemented
4017** in the core. So this routine is never called. For now, it is merely
4018** a place-holder.
4019*/
danielk1977397d65f2008-11-19 11:35:39 +00004020static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4021 UNUSED_PARAMETER(NotUsed);
4022 UNUSED_PARAMETER(NotUsed2);
4023 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004024 return 0;
4025}
4026
drh153c62c2007-08-24 03:51:33 +00004027/*
drh734c9862008-11-28 15:37:20 +00004028************************ End of sqlite3_vfs methods ***************************
4029******************************************************************************/
4030
drh715ff302008-12-03 22:32:44 +00004031/******************************************************************************
4032************************** Begin Proxy Locking ********************************
4033**
4034** Proxy locking is a "uber-locking-method" in this sense: It uses the
4035** other locking methods on secondary lock files. Proxy locking is a
4036** meta-layer over top of the primitive locking implemented above. For
4037** this reason, the division that implements of proxy locking is deferred
4038** until late in the file (here) after all of the other I/O methods have
4039** been defined - so that the primitive locking methods are available
4040** as services to help with the implementation of proxy locking.
4041**
4042****
4043**
4044** The default locking schemes in SQLite use byte-range locks on the
4045** database file to coordinate safe, concurrent access by multiple readers
4046** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4047** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4048** as POSIX read & write locks over fixed set of locations (via fsctl),
4049** on AFP and SMB only exclusive byte-range locks are available via fsctl
4050** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4051** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4052** address in the shared range is taken for a SHARED lock, the entire
4053** shared range is taken for an EXCLUSIVE lock):
4054**
4055** PENDING_BYTE 0x40000000
4056** RESERVED_BYTE 0x40000001
4057** SHARED_RANGE 0x40000002 -> 0x40000200
4058**
4059** This works well on the local file system, but shows a nearly 100x
4060** slowdown in read performance on AFP because the AFP client disables
4061** the read cache when byte-range locks are present. Enabling the read
4062** cache exposes a cache coherency problem that is present on all OS X
4063** supported network file systems. NFS and AFP both observe the
4064** close-to-open semantics for ensuring cache coherency
4065** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4066** address the requirements for concurrent database access by multiple
4067** readers and writers
4068** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4069**
4070** To address the performance and cache coherency issues, proxy file locking
4071** changes the way database access is controlled by limiting access to a
4072** single host at a time and moving file locks off of the database file
4073** and onto a proxy file on the local file system.
4074**
4075**
4076** Using proxy locks
4077** -----------------
4078**
4079** C APIs
4080**
4081** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4082** <proxy_path> | ":auto:");
4083** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4084**
4085**
4086** SQL pragmas
4087**
4088** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4089** PRAGMA [database.]lock_proxy_file
4090**
4091** Specifying ":auto:" means that if there is a conch file with a matching
4092** host ID in it, the proxy path in the conch file will be used, otherwise
4093** a proxy path based on the user's temp dir
4094** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4095** actual proxy file name is generated from the name and path of the
4096** database file. For example:
4097**
4098** For database path "/Users/me/foo.db"
4099** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4100**
4101** Once a lock proxy is configured for a database connection, it can not
4102** be removed, however it may be switched to a different proxy path via
4103** the above APIs (assuming the conch file is not being held by another
4104** connection or process).
4105**
4106**
4107** How proxy locking works
4108** -----------------------
4109**
4110** Proxy file locking relies primarily on two new supporting files:
4111**
4112** * conch file to limit access to the database file to a single host
4113** at a time
4114**
4115** * proxy file to act as a proxy for the advisory locks normally
4116** taken on the database
4117**
4118** The conch file - to use a proxy file, sqlite must first "hold the conch"
4119** by taking an sqlite-style shared lock on the conch file, reading the
4120** contents and comparing the host's unique host ID (see below) and lock
4121** proxy path against the values stored in the conch. The conch file is
4122** stored in the same directory as the database file and the file name
4123** is patterned after the database file name as ".<databasename>-conch".
4124** If the conch file does not exist, or it's contents do not match the
4125** host ID and/or proxy path, then the lock is escalated to an exclusive
4126** lock and the conch file contents is updated with the host ID and proxy
4127** path and the lock is downgraded to a shared lock again. If the conch
4128** is held by another process (with a shared lock), the exclusive lock
4129** will fail and SQLITE_BUSY is returned.
4130**
4131** The proxy file - a single-byte file used for all advisory file locks
4132** normally taken on the database file. This allows for safe sharing
4133** of the database file for multiple readers and writers on the same
4134** host (the conch ensures that they all use the same local lock file).
4135**
4136** There is a third file - the host ID file - used as a persistent record
4137** of a unique identifier for the host, a 128-byte unique host id file
4138** in the path defined by the HOSTIDPATH macro (default value is
4139** /Library/Caches/.com.apple.sqliteConchHostId).
4140**
4141** Requesting the lock proxy does not immediately take the conch, it is
4142** only taken when the first request to lock database file is made.
4143** This matches the semantics of the traditional locking behavior, where
4144** opening a connection to a database file does not take a lock on it.
4145** The shared lock and an open file descriptor are maintained until
4146** the connection to the database is closed.
4147**
4148** The proxy file and the lock file are never deleted so they only need
4149** to be created the first time they are used.
4150**
4151** Configuration options
4152** ---------------------
4153**
4154** SQLITE_PREFER_PROXY_LOCKING
4155**
4156** Database files accessed on non-local file systems are
4157** automatically configured for proxy locking, lock files are
4158** named automatically using the same logic as
4159** PRAGMA lock_proxy_file=":auto:"
4160**
4161** SQLITE_PROXY_DEBUG
4162**
4163** Enables the logging of error messages during host id file
4164** retrieval and creation
4165**
4166** HOSTIDPATH
4167**
4168** Overrides the default host ID file path location
4169**
4170** LOCKPROXYDIR
4171**
4172** Overrides the default directory used for lock proxy files that
4173** are named automatically via the ":auto:" setting
4174**
4175** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4176**
4177** Permissions to use when creating a directory for storing the
4178** lock proxy files, only used when LOCKPROXYDIR is not set.
4179**
4180**
4181** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4182** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4183** force proxy locking to be used for every database file opened, and 0
4184** will force automatic proxy locking to be disabled for all database
4185** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4186** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4187*/
4188
4189/*
4190** Proxy locking is only available on MacOSX
4191*/
drhd2cb50b2009-01-09 21:41:17 +00004192#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004193
4194#ifdef SQLITE_TEST
4195/* simulate multiple hosts by creating unique hostid file paths */
4196int sqlite3_hostid_num = 0;
4197#endif
4198
4199/*
4200** The proxyLockingContext has the path and file structures for the remote
4201** and local proxy files in it
4202*/
4203typedef struct proxyLockingContext proxyLockingContext;
4204struct proxyLockingContext {
4205 unixFile *conchFile; /* Open conch file */
4206 char *conchFilePath; /* Name of the conch file */
4207 unixFile *lockProxy; /* Open proxy lock file */
4208 char *lockProxyPath; /* Name of the proxy lock file */
4209 char *dbPath; /* Name of the open file */
4210 int conchHeld; /* True if the conch is currently held */
4211 void *oldLockingContext; /* Original lockingcontext to restore on close */
4212 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4213};
4214
4215/* HOSTIDLEN and CONCHLEN both include space for the string
4216** terminating nul
4217*/
4218#define HOSTIDLEN 128
4219#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4220#ifndef HOSTIDPATH
4221# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4222#endif
4223
4224/* basically a copy of unixRandomness with different
4225** test behavior built in */
4226static int proxyGenerateHostID(char *pHostID){
4227 int pid, fd, len;
4228 unsigned char *key = (unsigned char *)pHostID;
4229
4230 memset(key, 0, HOSTIDLEN);
4231 len = 0;
4232 fd = open("/dev/urandom", O_RDONLY);
4233 if( fd>=0 ){
4234 len = read(fd, key, HOSTIDLEN);
4235 close(fd); /* silently leak the fd if it fails */
4236 }
4237 if( len < HOSTIDLEN ){
4238 time_t t;
4239 time(&t);
4240 memcpy(key, &t, sizeof(t));
4241 pid = getpid();
4242 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4243 }
4244
4245#ifdef MAKE_PRETTY_HOSTID
4246 {
4247 int i;
4248 /* filter the bytes into printable ascii characters and NUL terminate */
4249 key[(HOSTIDLEN-1)] = 0x00;
4250 for( i=0; i<(HOSTIDLEN-1); i++ ){
4251 unsigned char pa = key[i]&0x7F;
4252 if( pa<0x20 ){
4253 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4254 }else if( pa==0x7F ){
4255 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4256 }
4257 }
4258 }
4259#endif
4260 return SQLITE_OK;
4261}
4262
4263/* writes the host id path to path, path should be an pre-allocated buffer
4264** with enough space for a path
4265*/
4266static void proxyGetHostIDPath(char *path, size_t len){
4267 strlcpy(path, HOSTIDPATH, len);
4268#ifdef SQLITE_TEST
4269 if( sqlite3_hostid_num>0 ){
4270 char suffix[2] = "1";
4271 suffix[0] = suffix[0] + sqlite3_hostid_num;
4272 strlcat(path, suffix, len);
4273 }
4274#endif
4275 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4276}
4277
4278/* get the host ID from a sqlite hostid file stored in the
4279** user-specific tmp directory, create the ID if it's not there already
4280*/
4281static int proxyGetHostID(char *pHostID, int *pError){
4282 int fd;
4283 char path[MAXPATHLEN];
4284 size_t len;
4285 int rc=SQLITE_OK;
4286
4287 proxyGetHostIDPath(path, MAXPATHLEN);
4288 /* try to create the host ID file, if it already exists read the contents */
4289 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4290 if( fd<0 ){
4291 int err=errno;
4292
4293 if( err!=EEXIST ){
4294#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4295 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4296 path, strerror(err));
4297#endif
4298 return SQLITE_PERM;
4299 }
4300 /* couldn't create the file, read it instead */
4301 fd = open(path, O_RDONLY|O_EXCL);
4302 if( fd<0 ){
4303#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4304 int err = errno;
4305 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4306 path, strerror(err));
4307#endif
4308 return SQLITE_PERM;
4309 }
4310 len = pread(fd, pHostID, HOSTIDLEN, 0);
4311 if( len<0 ){
4312 *pError = errno;
4313 rc = SQLITE_IOERR_READ;
4314 }else if( len<HOSTIDLEN ){
4315 *pError = 0;
4316 rc = SQLITE_IOERR_SHORT_READ;
4317 }
4318 close(fd); /* silently leak the fd if it fails */
4319 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4320 return rc;
4321 }else{
4322 /* we're creating the host ID file (use a random string of bytes) */
4323 proxyGenerateHostID(pHostID);
4324 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4325 if( len<0 ){
4326 *pError = errno;
4327 rc = SQLITE_IOERR_WRITE;
4328 }else if( len<HOSTIDLEN ){
4329 *pError = 0;
4330 rc = SQLITE_IOERR_WRITE;
4331 }
4332 close(fd); /* silently leak the fd if it fails */
4333 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4334 return rc;
4335 }
4336}
4337
4338static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4339 int len;
4340 int dbLen;
4341 int i;
4342
4343#ifdef LOCKPROXYDIR
4344 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4345#else
4346# ifdef _CS_DARWIN_USER_TEMP_DIR
4347 {
4348 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4349 len = strlcat(lPath, "sqliteplocks", maxLen);
4350 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4351 /* if mkdir fails, handle as lock file creation failure */
4352 int err = errno;
4353# ifdef SQLITE_DEBUG
4354 if( err!=EEXIST ){
4355 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4356 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4357 }
4358# endif
4359 }else{
4360 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4361 }
4362
4363 }
4364# else
4365 len = strlcpy(lPath, "/tmp/", maxLen);
4366# endif
4367#endif
4368
4369 if( lPath[len-1]!='/' ){
4370 len = strlcat(lPath, "/", maxLen);
4371 }
4372
4373 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004374 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004375 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4376 char c = dbPath[i];
4377 lPath[i+len] = (c=='/')?'_':c;
4378 }
4379 lPath[i+len]='\0';
4380 strlcat(lPath, ":auto:", maxLen);
4381 return SQLITE_OK;
4382}
4383
4384/*
4385** Create a new VFS file descriptor (stored in memory obtained from
4386** sqlite3_malloc) and open the file named "path" in the file descriptor.
4387**
4388** The caller is responsible not only for closing the file descriptor
4389** but also for freeing the memory associated with the file descriptor.
4390*/
4391static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4392 int fd;
4393 int dirfd = -1;
4394 unixFile *pNew;
4395 int rc = SQLITE_OK;
4396 sqlite3_vfs dummyVfs;
4397
4398 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4399 if( fd<0 ){
4400 return SQLITE_CANTOPEN;
4401 }
4402
4403 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4404 if( pNew==NULL ){
4405 rc = SQLITE_NOMEM;
4406 goto end_create_proxy;
4407 }
4408 memset(pNew, 0, sizeof(unixFile));
4409
drh1875f7a2008-12-08 18:19:17 +00004410 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004411 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4412 if( rc==SQLITE_OK ){
4413 *ppFile = pNew;
4414 return SQLITE_OK;
4415 }
4416end_create_proxy:
4417 close(fd); /* silently leak fd if error, we're already in error */
4418 sqlite3_free(pNew);
4419 return rc;
4420}
4421
4422/* takes the conch by taking a shared lock and read the contents conch, if
4423** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4424** lockPath means that the lockPath in the conch file will be used if the
4425** host IDs match, or a new lock path will be generated automatically
4426** and written to the conch file.
4427*/
4428static int proxyTakeConch(unixFile *pFile){
4429 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4430
4431 if( pCtx->conchHeld>0 ){
4432 return SQLITE_OK;
4433 }else{
4434 unixFile *conchFile = pCtx->conchFile;
4435 char testValue[CONCHLEN];
4436 char conchValue[CONCHLEN];
4437 char lockPath[MAXPATHLEN];
4438 char *tLockPath = NULL;
4439 int rc = SQLITE_OK;
4440 int readRc = SQLITE_OK;
4441 int syncPerms = 0;
4442
4443 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4444 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4445
4446 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4447 if( rc==SQLITE_OK ){
4448 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004449 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004450 rc = proxyGetHostID(testValue, &pError);
4451 if( (rc&0xff)==SQLITE_IOERR ){
4452 pFile->lastErrno = pError;
4453 }
4454 if( pCtx->lockProxyPath ){
4455 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4456 }
4457 }
4458 if( rc!=SQLITE_OK ){
4459 goto end_takeconch;
4460 }
4461
4462 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4463 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4464 if( readRc!=SQLITE_OK ){
4465 if( (rc&0xff)==SQLITE_IOERR ){
4466 pFile->lastErrno = conchFile->lastErrno;
4467 }
4468 rc = readRc;
4469 goto end_takeconch;
4470 }
4471 /* if the conch has data compare the contents */
4472 if( !pCtx->lockProxyPath ){
4473 /* for auto-named local lock file, just check the host ID and we'll
4474 ** use the local lock file path that's already in there */
4475 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4476 tLockPath = (char *)&conchValue[HOSTIDLEN];
4477 goto end_takeconch;
4478 }
4479 }else{
4480 /* we've got the conch if conchValue matches our path and host ID */
4481 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4482 goto end_takeconch;
4483 }
4484 }
4485 }else{
4486 /* a short read means we're "creating" the conch (even though it could
4487 ** have been user-intervention), if we acquire the exclusive lock,
4488 ** we'll try to match the current on-disk permissions of the database
4489 */
4490 syncPerms = 1;
4491 }
4492
4493 /* either conch was emtpy or didn't match */
4494 if( !pCtx->lockProxyPath ){
4495 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4496 tLockPath = lockPath;
4497 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4498 }
4499
4500 /* update conch with host and path (this will fail if other process
4501 ** has a shared lock already) */
4502 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4503 if( rc==SQLITE_OK ){
4504 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4505 if( rc==SQLITE_OK && syncPerms ){
4506 struct stat buf;
4507 int err = fstat(pFile->h, &buf);
4508 if( err==0 ){
4509 /* try to match the database file permissions, ignore failure */
4510#ifndef SQLITE_PROXY_DEBUG
4511 fchmod(conchFile->h, buf.st_mode);
4512#else
4513 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4514 int code = errno;
4515 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4516 buf.st_mode, code, strerror(code));
4517 } else {
4518 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4519 }
4520 }else{
4521 int code = errno;
4522 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4523 err, code, strerror(code));
4524#endif
4525 }
4526 }
4527 }
4528 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4529
4530end_takeconch:
4531 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4532 if( rc==SQLITE_OK && pFile->openFlags ){
4533 if( pFile->h>=0 ){
4534#ifdef STRICT_CLOSE_ERROR
4535 if( close(pFile->h) ){
4536 pFile->lastErrno = errno;
4537 return SQLITE_IOERR_CLOSE;
4538 }
4539#else
4540 close(pFile->h); /* silently leak fd if fail */
4541#endif
4542 }
4543 pFile->h = -1;
4544 int fd = open(pCtx->dbPath, pFile->openFlags,
4545 SQLITE_DEFAULT_FILE_PERMISSIONS);
4546 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4547 if( fd>=0 ){
4548 pFile->h = fd;
4549 }else{
drh1875f7a2008-12-08 18:19:17 +00004550 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4551 during locking */
drh715ff302008-12-03 22:32:44 +00004552 }
4553 }
4554 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4555 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004556 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004557 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4558 }
4559 if( rc==SQLITE_OK ){
4560 pCtx->conchHeld = 1;
4561
4562 if( tLockPath ){
4563 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4564 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4565 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4566 pCtx->lockProxyPath;
4567 }
4568 }
4569 } else {
4570 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4571 }
4572 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4573 return rc;
4574 }
4575}
4576
4577/*
4578** If pFile holds a lock on a conch file, then release that lock.
4579*/
4580static int proxyReleaseConch(unixFile *pFile){
4581 int rc; /* Subroutine return code */
4582 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4583 unixFile *conchFile; /* Name of the conch file */
4584
4585 pCtx = (proxyLockingContext *)pFile->lockingContext;
4586 conchFile = pCtx->conchFile;
4587 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4588 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4589 getpid());
4590 pCtx->conchHeld = 0;
4591 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4592 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4593 (rc==SQLITE_OK ? "ok" : "failed"));
4594 return rc;
4595}
4596
4597/*
4598** Given the name of a database file, compute the name of its conch file.
4599** Store the conch filename in memory obtained from sqlite3_malloc().
4600** Make *pConchPath point to the new name. Return SQLITE_OK on success
4601** or SQLITE_NOMEM if unable to obtain memory.
4602**
4603** The caller is responsible for ensuring that the allocated memory
4604** space is eventually freed.
4605**
4606** *pConchPath is set to NULL if a memory allocation error occurs.
4607*/
4608static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4609 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004610 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004611 char *conchPath; /* buffer in which to construct conch name */
4612
4613 /* Allocate space for the conch filename and initialize the name to
4614 ** the name of the original database file. */
4615 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4616 if( conchPath==0 ){
4617 return SQLITE_NOMEM;
4618 }
4619 memcpy(conchPath, dbPath, len+1);
4620
4621 /* now insert a "." before the last / character */
4622 for( i=(len-1); i>=0; i-- ){
4623 if( conchPath[i]=='/' ){
4624 i++;
4625 break;
4626 }
4627 }
4628 conchPath[i]='.';
4629 while ( i<len ){
4630 conchPath[i+1]=dbPath[i];
4631 i++;
4632 }
4633
4634 /* append the "-conch" suffix to the file */
4635 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004636 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004637
4638 return SQLITE_OK;
4639}
4640
4641
4642/* Takes a fully configured proxy locking-style unix file and switches
4643** the local lock file path
4644*/
4645static int switchLockProxyPath(unixFile *pFile, const char *path) {
4646 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4647 char *oldPath = pCtx->lockProxyPath;
4648 int rc = SQLITE_OK;
4649
4650 if( pFile->locktype!=NO_LOCK ){
4651 return SQLITE_BUSY;
4652 }
4653
4654 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4655 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4656 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4657 return SQLITE_OK;
4658 }else{
4659 unixFile *lockProxy = pCtx->lockProxy;
4660 pCtx->lockProxy=NULL;
4661 pCtx->conchHeld = 0;
4662 if( lockProxy!=NULL ){
4663 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4664 if( rc ) return rc;
4665 sqlite3_free(lockProxy);
4666 }
4667 sqlite3_free(oldPath);
4668 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4669 }
4670
4671 return rc;
4672}
4673
4674/*
4675** pFile is a file that has been opened by a prior xOpen call. dbPath
4676** is a string buffer at least MAXPATHLEN+1 characters in size.
4677**
4678** This routine find the filename associated with pFile and writes it
4679** int dbPath.
4680*/
4681static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004682#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004683 if( pFile->pMethod == &afpIoMethods ){
4684 /* afp style keeps a reference to the db path in the filePath field
4685 ** of the struct */
drhea678832008-12-10 19:26:22 +00004686 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004687 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4688 }else
4689#endif
4690 if( pFile->pMethod == &dotlockIoMethods ){
4691 /* dot lock style uses the locking context to store the dot lock
4692 ** file path */
4693 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4694 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4695 }else{
4696 /* all other styles use the locking context to store the db file path */
4697 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4698 strcpy(dbPath, (char *)pFile->lockingContext);
4699 }
4700 return SQLITE_OK;
4701}
4702
4703/*
4704** Takes an already filled in unix file and alters it so all file locking
4705** will be performed on the local proxy lock file. The following fields
4706** are preserved in the locking context so that they can be restored and
4707** the unix structure properly cleaned up at close time:
4708** ->lockingContext
4709** ->pMethod
4710*/
4711static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4712 proxyLockingContext *pCtx;
4713 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4714 char *lockPath=NULL;
4715 int rc = SQLITE_OK;
4716
4717 if( pFile->locktype!=NO_LOCK ){
4718 return SQLITE_BUSY;
4719 }
4720 proxyGetDbPathForUnixFile(pFile, dbPath);
4721 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4722 lockPath=NULL;
4723 }else{
4724 lockPath=(char *)path;
4725 }
4726
4727 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4728 (lockPath ? lockPath : ":auto:"), getpid());
4729
4730 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4731 if( pCtx==0 ){
4732 return SQLITE_NOMEM;
4733 }
4734 memset(pCtx, 0, sizeof(*pCtx));
4735
4736 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4737 if( rc==SQLITE_OK ){
4738 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4739 }
4740 if( rc==SQLITE_OK && lockPath ){
4741 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4742 }
4743
4744 if( rc==SQLITE_OK ){
4745 /* all memory is allocated, proxys are created and assigned,
4746 ** switch the locking context and pMethod then return.
4747 */
4748 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4749 pCtx->oldLockingContext = pFile->lockingContext;
4750 pFile->lockingContext = pCtx;
4751 pCtx->pOldMethod = pFile->pMethod;
4752 pFile->pMethod = &proxyIoMethods;
4753 }else{
4754 if( pCtx->conchFile ){
4755 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4756 if( rc ) return rc;
4757 sqlite3_free(pCtx->conchFile);
4758 }
4759 sqlite3_free(pCtx->conchFilePath);
4760 sqlite3_free(pCtx);
4761 }
4762 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4763 (rc==SQLITE_OK ? "ok" : "failed"));
4764 return rc;
4765}
4766
4767
4768/*
4769** This routine handles sqlite3_file_control() calls that are specific
4770** to proxy locking.
4771*/
4772static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4773 switch( op ){
4774 case SQLITE_GET_LOCKPROXYFILE: {
4775 unixFile *pFile = (unixFile*)id;
4776 if( pFile->pMethod == &proxyIoMethods ){
4777 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4778 proxyTakeConch(pFile);
4779 if( pCtx->lockProxyPath ){
4780 *(const char **)pArg = pCtx->lockProxyPath;
4781 }else{
4782 *(const char **)pArg = ":auto: (not held)";
4783 }
4784 } else {
4785 *(const char **)pArg = NULL;
4786 }
4787 return SQLITE_OK;
4788 }
4789 case SQLITE_SET_LOCKPROXYFILE: {
4790 unixFile *pFile = (unixFile*)id;
4791 int rc = SQLITE_OK;
4792 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4793 if( pArg==NULL || (const char *)pArg==0 ){
4794 if( isProxyStyle ){
4795 /* turn off proxy locking - not supported */
4796 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4797 }else{
4798 /* turn off proxy locking - already off - NOOP */
4799 rc = SQLITE_OK;
4800 }
4801 }else{
4802 const char *proxyPath = (const char *)pArg;
4803 if( isProxyStyle ){
4804 proxyLockingContext *pCtx =
4805 (proxyLockingContext*)pFile->lockingContext;
4806 if( !strcmp(pArg, ":auto:")
4807 || (pCtx->lockProxyPath &&
4808 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4809 ){
4810 rc = SQLITE_OK;
4811 }else{
4812 rc = switchLockProxyPath(pFile, proxyPath);
4813 }
4814 }else{
4815 /* turn on proxy file locking */
4816 rc = proxyTransformUnixFile(pFile, proxyPath);
4817 }
4818 }
4819 return rc;
4820 }
4821 default: {
4822 assert( 0 ); /* The call assures that only valid opcodes are sent */
4823 }
4824 }
4825 /*NOTREACHED*/
4826 return SQLITE_ERROR;
4827}
4828
4829/*
4830** Within this division (the proxying locking implementation) the procedures
4831** above this point are all utilities. The lock-related methods of the
4832** proxy-locking sqlite3_io_method object follow.
4833*/
4834
4835
4836/*
4837** This routine checks if there is a RESERVED lock held on the specified
4838** file by this or any other process. If such a lock is held, set *pResOut
4839** to a non-zero value otherwise *pResOut is set to zero. The return value
4840** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4841*/
4842static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4843 unixFile *pFile = (unixFile*)id;
4844 int rc = proxyTakeConch(pFile);
4845 if( rc==SQLITE_OK ){
4846 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4847 unixFile *proxy = pCtx->lockProxy;
4848 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4849 }
4850 return rc;
4851}
4852
4853/*
4854** Lock the file with the lock specified by parameter locktype - one
4855** of the following:
4856**
4857** (1) SHARED_LOCK
4858** (2) RESERVED_LOCK
4859** (3) PENDING_LOCK
4860** (4) EXCLUSIVE_LOCK
4861**
4862** Sometimes when requesting one lock state, additional lock states
4863** are inserted in between. The locking might fail on one of the later
4864** transitions leaving the lock state different from what it started but
4865** still short of its goal. The following chart shows the allowed
4866** transitions and the inserted intermediate states:
4867**
4868** UNLOCKED -> SHARED
4869** SHARED -> RESERVED
4870** SHARED -> (PENDING) -> EXCLUSIVE
4871** RESERVED -> (PENDING) -> EXCLUSIVE
4872** PENDING -> EXCLUSIVE
4873**
4874** This routine will only increase a lock. Use the sqlite3OsUnlock()
4875** routine to lower a locking level.
4876*/
4877static int proxyLock(sqlite3_file *id, int locktype) {
4878 unixFile *pFile = (unixFile*)id;
4879 int rc = proxyTakeConch(pFile);
4880 if( rc==SQLITE_OK ){
4881 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4882 unixFile *proxy = pCtx->lockProxy;
4883 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4884 pFile->locktype = proxy->locktype;
4885 }
4886 return rc;
4887}
4888
4889
4890/*
4891** Lower the locking level on file descriptor pFile to locktype. locktype
4892** must be either NO_LOCK or SHARED_LOCK.
4893**
4894** If the locking level of the file descriptor is already at or below
4895** the requested locking level, this routine is a no-op.
4896*/
4897static int proxyUnlock(sqlite3_file *id, int locktype) {
4898 unixFile *pFile = (unixFile*)id;
4899 int rc = proxyTakeConch(pFile);
4900 if( rc==SQLITE_OK ){
4901 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4902 unixFile *proxy = pCtx->lockProxy;
4903 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
4904 pFile->locktype = proxy->locktype;
4905 }
4906 return rc;
4907}
4908
4909/*
4910** Close a file that uses proxy locks.
4911*/
4912static int proxyClose(sqlite3_file *id) {
4913 if( id ){
4914 unixFile *pFile = (unixFile*)id;
4915 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4916 unixFile *lockProxy = pCtx->lockProxy;
4917 unixFile *conchFile = pCtx->conchFile;
4918 int rc = SQLITE_OK;
4919
4920 if( lockProxy ){
4921 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
4922 if( rc ) return rc;
4923 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
4924 if( rc ) return rc;
4925 sqlite3_free(lockProxy);
4926 pCtx->lockProxy = 0;
4927 }
4928 if( conchFile ){
4929 if( pCtx->conchHeld ){
4930 rc = proxyReleaseConch(pFile);
4931 if( rc ) return rc;
4932 }
4933 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
4934 if( rc ) return rc;
4935 sqlite3_free(conchFile);
4936 }
4937 sqlite3_free(pCtx->lockProxyPath);
4938 sqlite3_free(pCtx->conchFilePath);
4939 sqlite3_free(pCtx->dbPath);
4940 /* restore the original locking context and pMethod then close it */
4941 pFile->lockingContext = pCtx->oldLockingContext;
4942 pFile->pMethod = pCtx->pOldMethod;
4943 sqlite3_free(pCtx);
4944 return pFile->pMethod->xClose(id);
4945 }
4946 return SQLITE_OK;
4947}
4948
4949
4950
drhd2cb50b2009-01-09 21:41:17 +00004951#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00004952/*
4953** The proxy locking style is intended for use with AFP filesystems.
4954** And since AFP is only supported on MacOSX, the proxy locking is also
4955** restricted to MacOSX.
4956**
4957**
4958******************* End of the proxy lock implementation **********************
4959******************************************************************************/
4960
drh734c9862008-11-28 15:37:20 +00004961/*
danielk1977e339d652008-06-28 11:23:00 +00004962** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00004963**
4964** This routine registers all VFS implementations for unix-like operating
4965** systems. This routine, and the sqlite3_os_end() routine that follows,
4966** should be the only routines in this file that are visible from other
4967** files.
drh6b9d6dd2008-12-03 19:34:47 +00004968**
4969** This routine is called once during SQLite initialization and by a
4970** single thread. The memory allocation and mutex subsystems have not
4971** necessarily been initialized when this routine is called, and so they
4972** should not be used.
drh153c62c2007-08-24 03:51:33 +00004973*/
danielk1977c0fa4c52008-06-25 17:19:00 +00004974int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00004975 /*
4976 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00004977 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
4978 ** to the "finder" function. (pAppData is a pointer to a pointer because
4979 ** silly C90 rules prohibit a void* from being cast to a function pointer
4980 ** and so we have to go through the intermediate pointer to avoid problems
4981 ** when compiling with -pedantic-errors on GCC.)
4982 **
4983 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00004984 ** finder-function. The finder-function returns a pointer to the
4985 ** sqlite_io_methods object that implements the desired locking
4986 ** behaviors. See the division above that contains the IOMETHODS
4987 ** macro for addition information on finder-functions.
4988 **
4989 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
4990 ** object. But the "autolockIoFinder" available on MacOSX does a little
4991 ** more than that; it looks at the filesystem type that hosts the
4992 ** database file and tries to choose an locking method appropriate for
4993 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00004994 */
drh7708e972008-11-29 00:56:52 +00004995 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00004996 1, /* iVersion */ \
4997 sizeof(unixFile), /* szOsFile */ \
4998 MAX_PATHNAME, /* mxPathname */ \
4999 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005000 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005001 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005002 unixOpen, /* xOpen */ \
5003 unixDelete, /* xDelete */ \
5004 unixAccess, /* xAccess */ \
5005 unixFullPathname, /* xFullPathname */ \
5006 unixDlOpen, /* xDlOpen */ \
5007 unixDlError, /* xDlError */ \
5008 unixDlSym, /* xDlSym */ \
5009 unixDlClose, /* xDlClose */ \
5010 unixRandomness, /* xRandomness */ \
5011 unixSleep, /* xSleep */ \
5012 unixCurrentTime, /* xCurrentTime */ \
5013 unixGetLastError /* xGetLastError */ \
5014 }
5015
drh6b9d6dd2008-12-03 19:34:47 +00005016 /*
5017 ** All default VFSes for unix are contained in the following array.
5018 **
5019 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5020 ** by the SQLite core when the VFS is registered. So the following
5021 ** array cannot be const.
5022 */
danielk1977e339d652008-06-28 11:23:00 +00005023 static sqlite3_vfs aVfs[] = {
drhd2cb50b2009-01-09 21:41:17 +00005024#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005025 UNIXVFS("unix", autolockIoFinder ),
5026#else
5027 UNIXVFS("unix", posixIoFinder ),
5028#endif
5029 UNIXVFS("unix-none", nolockIoFinder ),
5030 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005031#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005032 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005033#endif
5034#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005035 UNIXVFS("unix-posix", posixIoFinder ),
5036 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005037#endif
drhd2cb50b2009-01-09 21:41:17 +00005038#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005039 UNIXVFS("unix-afp", afpIoFinder ),
5040 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005041#endif
drh153c62c2007-08-24 03:51:33 +00005042 };
drh6b9d6dd2008-12-03 19:34:47 +00005043 unsigned int i; /* Loop counter */
5044
5045 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005046 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005047 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005048 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005049 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005050}
danielk1977e339d652008-06-28 11:23:00 +00005051
5052/*
drh6b9d6dd2008-12-03 19:34:47 +00005053** Shutdown the operating system interface.
5054**
5055** Some operating systems might need to do some cleanup in this routine,
5056** to release dynamically allocated objects. But not on unix.
5057** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005058*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005059int sqlite3_os_end(void){
5060 return SQLITE_OK;
5061}
drhdce8bdb2007-08-16 13:01:44 +00005062
danielk197729bafea2008-06-26 10:41:19 +00005063#endif /* SQLITE_OS_UNIX */