blob: fd64cb06e3c3c41429af21f9cd6bacbe62bb54c1 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000122
drh40bbb0a2008-09-23 10:23:26 +0000123#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000124# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000125# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <semaphore.h>
127# include <limits.h>
128# else
drh9b35ea62008-11-29 02:20:26 +0000129# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <sys/param.h>
131# include <sys/mount.h>
132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
135/*
drh7ed97b92010-01-20 13:07:21 +0000136** Allowed values of unixFile.fsFlags
137*/
138#define SQLITE_FSFLAGS_IS_MSDOS 0x1
139
140/*
drhf1a221e2006-01-15 17:27:17 +0000141** If we are to be thread-safe, include the pthreads header and define
142** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000143*/
drhd677b3d2007-08-20 22:48:41 +0000144#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000145# include <pthread.h>
146# define SQLITE_UNIX_THREADS 1
147#endif
148
149/*
150** Default permissions when creating a new file
151*/
152#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
153# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
154#endif
155
danielk1977b4b47412007-08-17 15:53:36 +0000156/*
aswiftaebf4132008-11-21 00:10:35 +0000157 ** Default permissions when creating auto proxy dir
158 */
159#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
160# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
161#endif
162
163/*
danielk1977b4b47412007-08-17 15:53:36 +0000164** Maximum supported path-length.
165*/
166#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000167
drh734c9862008-11-28 15:37:20 +0000168/*
drh734c9862008-11-28 15:37:20 +0000169** Only set the lastErrno if the error code is a real error and not
170** a normal expected return code of SQLITE_BUSY or SQLITE_OK
171*/
172#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
173
drh9cbe6352005-11-29 03:13:21 +0000174
175/*
dane946c392009-08-22 11:39:46 +0000176** Sometimes, after a file handle is closed by SQLite, the file descriptor
177** cannot be closed immediately. In these cases, instances of the following
178** structure are used to store the file descriptor while waiting for an
179** opportunity to either close or reuse it.
180*/
181typedef struct UnixUnusedFd UnixUnusedFd;
182struct UnixUnusedFd {
183 int fd; /* File descriptor to close */
184 int flags; /* Flags this file descriptor was opened with */
185 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
186};
187
188/*
drh9b35ea62008-11-29 02:20:26 +0000189** The unixFile structure is subclass of sqlite3_file specific to the unix
190** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000191*/
drh054889e2005-11-30 03:20:31 +0000192typedef struct unixFile unixFile;
193struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000194 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000195 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
196 struct unixLockInfo *pLock; /* Info about locks on this inode */
197 int h; /* The file descriptor */
198 int dirfd; /* File descriptor for the directory */
199 unsigned char locktype; /* The type of lock held on this fd */
200 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000201 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000202 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000203 int fileFlags; /* Miscellanous flags */
drh08c6d442009-02-09 17:34:07 +0000204#if SQLITE_ENABLE_LOCKING_STYLE
205 int openFlags; /* The flags specified at open() */
206#endif
drh7ed97b92010-01-20 13:07:21 +0000207#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
208 unsigned fsFlags; /* cached details from statfs() */
209#endif
drh734c9862008-11-28 15:37:20 +0000210#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000211 pthread_t tid; /* The thread that "owns" this unixFile */
212#endif
213#if OS_VXWORKS
214 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000215 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000216#endif
drh8f941bc2009-01-14 23:03:40 +0000217#ifndef NDEBUG
218 /* The next group of variables are used to track whether or not the
219 ** transaction counter in bytes 24-27 of database files are updated
220 ** whenever any part of the database changes. An assertion fault will
221 ** occur if a file is updated without also updating the transaction
222 ** counter. This test is made to avoid new problems similar to the
223 ** one described by ticket #3584.
224 */
225 unsigned char transCntrChng; /* True if the transaction counter changed */
226 unsigned char dbUpdate; /* True if any part of database file changed */
227 unsigned char inNormalWrite; /* True if in a normal write operation */
228#endif
danielk1977967a4a12007-08-20 14:23:44 +0000229#ifdef SQLITE_TEST
230 /* In test mode, increase the size of this structure a bit so that
231 ** it is larger than the struct CrashFile defined in test6.c.
232 */
233 char aPadding[32];
234#endif
drh9cbe6352005-11-29 03:13:21 +0000235};
236
drh0ccebe72005-06-07 22:22:50 +0000237/*
drh0c2694b2009-09-03 16:23:44 +0000238** The following macros define bits in unixFile.fileFlags
239*/
240#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
241
242/*
drh198bf392006-01-06 21:52:49 +0000243** Include code that is common to all os_*.c files
244*/
245#include "os_common.h"
246
247/*
drh0ccebe72005-06-07 22:22:50 +0000248** Define various macros that are missing from some systems.
249*/
drhbbd42a62004-05-22 17:41:58 +0000250#ifndef O_LARGEFILE
251# define O_LARGEFILE 0
252#endif
253#ifdef SQLITE_DISABLE_LFS
254# undef O_LARGEFILE
255# define O_LARGEFILE 0
256#endif
257#ifndef O_NOFOLLOW
258# define O_NOFOLLOW 0
259#endif
260#ifndef O_BINARY
261# define O_BINARY 0
262#endif
263
264/*
265** The DJGPP compiler environment looks mostly like Unix, but it
266** lacks the fcntl() system call. So redefine fcntl() to be something
267** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000268** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000269*/
270#ifdef __DJGPP__
271# define fcntl(A,B,C) 0
272#endif
273
274/*
drh2b4b5962005-06-15 17:47:55 +0000275** The threadid macro resolves to the thread-id or to 0. Used for
276** testing and debugging only.
277*/
drhd677b3d2007-08-20 22:48:41 +0000278#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000279#define threadid pthread_self()
280#else
281#define threadid 0
282#endif
283
danielk197713adf8a2004-06-03 16:08:41 +0000284
drh107886a2008-11-21 22:21:50 +0000285/*
dan9359c7b2009-08-21 08:29:10 +0000286** Helper functions to obtain and relinquish the global mutex. The
287** global mutex is used to protect the unixOpenCnt, unixLockInfo and
288** vxworksFileId objects used by this file, all of which may be
289** shared by multiple threads.
290**
291** Function unixMutexHeld() is used to assert() that the global mutex
292** is held when required. This function is only used as part of assert()
293** statements. e.g.
294**
295** unixEnterMutex()
296** assert( unixMutexHeld() );
297** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000298*/
299static void unixEnterMutex(void){
300 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
301}
302static void unixLeaveMutex(void){
303 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
304}
dan9359c7b2009-08-21 08:29:10 +0000305#ifdef SQLITE_DEBUG
306static int unixMutexHeld(void) {
307 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
308}
309#endif
drh107886a2008-11-21 22:21:50 +0000310
drh734c9862008-11-28 15:37:20 +0000311
312#ifdef SQLITE_DEBUG
313/*
314** Helper function for printing out trace information from debugging
315** binaries. This returns the string represetation of the supplied
316** integer lock-type.
317*/
318static const char *locktypeName(int locktype){
319 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000320 case NO_LOCK: return "NONE";
321 case SHARED_LOCK: return "SHARED";
322 case RESERVED_LOCK: return "RESERVED";
323 case PENDING_LOCK: return "PENDING";
324 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000325 }
326 return "ERROR";
327}
328#endif
329
330#ifdef SQLITE_LOCK_TRACE
331/*
332** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000333**
drh734c9862008-11-28 15:37:20 +0000334** This routine is used for troubleshooting locks on multithreaded
335** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
336** command-line option on the compiler. This code is normally
337** turned off.
338*/
339static int lockTrace(int fd, int op, struct flock *p){
340 char *zOpName, *zType;
341 int s;
342 int savedErrno;
343 if( op==F_GETLK ){
344 zOpName = "GETLK";
345 }else if( op==F_SETLK ){
346 zOpName = "SETLK";
347 }else{
348 s = fcntl(fd, op, p);
349 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
350 return s;
351 }
352 if( p->l_type==F_RDLCK ){
353 zType = "RDLCK";
354 }else if( p->l_type==F_WRLCK ){
355 zType = "WRLCK";
356 }else if( p->l_type==F_UNLCK ){
357 zType = "UNLCK";
358 }else{
359 assert( 0 );
360 }
361 assert( p->l_whence==SEEK_SET );
362 s = fcntl(fd, op, p);
363 savedErrno = errno;
364 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
365 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
366 (int)p->l_pid, s);
367 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
368 struct flock l2;
369 l2 = *p;
370 fcntl(fd, F_GETLK, &l2);
371 if( l2.l_type==F_RDLCK ){
372 zType = "RDLCK";
373 }else if( l2.l_type==F_WRLCK ){
374 zType = "WRLCK";
375 }else if( l2.l_type==F_UNLCK ){
376 zType = "UNLCK";
377 }else{
378 assert( 0 );
379 }
380 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
381 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
382 }
383 errno = savedErrno;
384 return s;
385}
386#define fcntl lockTrace
387#endif /* SQLITE_LOCK_TRACE */
388
389
390
391/*
392** This routine translates a standard POSIX errno code into something
393** useful to the clients of the sqlite3 functions. Specifically, it is
394** intended to translate a variety of "try again" errors into SQLITE_BUSY
395** and a variety of "please close the file descriptor NOW" errors into
396** SQLITE_IOERR
397**
398** Errors during initialization of locks, or file system support for locks,
399** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
400*/
401static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
402 switch (posixError) {
403 case 0:
404 return SQLITE_OK;
405
406 case EAGAIN:
407 case ETIMEDOUT:
408 case EBUSY:
409 case EINTR:
410 case ENOLCK:
411 /* random NFS retry error, unless during file system support
412 * introspection, in which it actually means what it says */
413 return SQLITE_BUSY;
414
415 case EACCES:
416 /* EACCES is like EAGAIN during locking operations, but not any other time*/
417 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
418 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
419 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
420 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
421 return SQLITE_BUSY;
422 }
423 /* else fall through */
424 case EPERM:
425 return SQLITE_PERM;
426
427 case EDEADLK:
428 return SQLITE_IOERR_BLOCKED;
429
430#if EOPNOTSUPP!=ENOTSUP
431 case EOPNOTSUPP:
432 /* something went terribly awry, unless during file system support
433 * introspection, in which it actually means what it says */
434#endif
435#ifdef ENOTSUP
436 case ENOTSUP:
437 /* invalid fd, unless during file system support introspection, in which
438 * it actually means what it says */
439#endif
440 case EIO:
441 case EBADF:
442 case EINVAL:
443 case ENOTCONN:
444 case ENODEV:
445 case ENXIO:
446 case ENOENT:
447 case ESTALE:
448 case ENOSYS:
449 /* these should force the client to close the file and reconnect */
450
451 default:
452 return sqliteIOErr;
453 }
454}
455
456
457
458/******************************************************************************
459****************** Begin Unique File ID Utility Used By VxWorks ***************
460**
461** On most versions of unix, we can get a unique ID for a file by concatenating
462** the device number and the inode number. But this does not work on VxWorks.
463** On VxWorks, a unique file id must be based on the canonical filename.
464**
465** A pointer to an instance of the following structure can be used as a
466** unique file ID in VxWorks. Each instance of this structure contains
467** a copy of the canonical filename. There is also a reference count.
468** The structure is reclaimed when the number of pointers to it drops to
469** zero.
470**
471** There are never very many files open at one time and lookups are not
472** a performance-critical path, so it is sufficient to put these
473** structures on a linked list.
474*/
475struct vxworksFileId {
476 struct vxworksFileId *pNext; /* Next in a list of them all */
477 int nRef; /* Number of references to this one */
478 int nName; /* Length of the zCanonicalName[] string */
479 char *zCanonicalName; /* Canonical filename */
480};
481
482#if OS_VXWORKS
483/*
drh9b35ea62008-11-29 02:20:26 +0000484** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000485** variable:
486*/
487static struct vxworksFileId *vxworksFileList = 0;
488
489/*
490** Simplify a filename into its canonical form
491** by making the following changes:
492**
493** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000494** * convert /./ into just /
495** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000496**
497** Changes are made in-place. Return the new name length.
498**
499** The original filename is in z[0..n-1]. Return the number of
500** characters in the simplified name.
501*/
502static int vxworksSimplifyName(char *z, int n){
503 int i, j;
504 while( n>1 && z[n-1]=='/' ){ n--; }
505 for(i=j=0; i<n; i++){
506 if( z[i]=='/' ){
507 if( z[i+1]=='/' ) continue;
508 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
509 i += 1;
510 continue;
511 }
512 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
513 while( j>0 && z[j-1]!='/' ){ j--; }
514 if( j>0 ){ j--; }
515 i += 2;
516 continue;
517 }
518 }
519 z[j++] = z[i];
520 }
521 z[j] = 0;
522 return j;
523}
524
525/*
526** Find a unique file ID for the given absolute pathname. Return
527** a pointer to the vxworksFileId object. This pointer is the unique
528** file ID.
529**
530** The nRef field of the vxworksFileId object is incremented before
531** the object is returned. A new vxworksFileId object is created
532** and added to the global list if necessary.
533**
534** If a memory allocation error occurs, return NULL.
535*/
536static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
537 struct vxworksFileId *pNew; /* search key and new file ID */
538 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
539 int n; /* Length of zAbsoluteName string */
540
541 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000542 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000543 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
544 if( pNew==0 ) return 0;
545 pNew->zCanonicalName = (char*)&pNew[1];
546 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
547 n = vxworksSimplifyName(pNew->zCanonicalName, n);
548
549 /* Search for an existing entry that matching the canonical name.
550 ** If found, increment the reference count and return a pointer to
551 ** the existing file ID.
552 */
553 unixEnterMutex();
554 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
555 if( pCandidate->nName==n
556 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
557 ){
558 sqlite3_free(pNew);
559 pCandidate->nRef++;
560 unixLeaveMutex();
561 return pCandidate;
562 }
563 }
564
565 /* No match was found. We will make a new file ID */
566 pNew->nRef = 1;
567 pNew->nName = n;
568 pNew->pNext = vxworksFileList;
569 vxworksFileList = pNew;
570 unixLeaveMutex();
571 return pNew;
572}
573
574/*
575** Decrement the reference count on a vxworksFileId object. Free
576** the object when the reference count reaches zero.
577*/
578static void vxworksReleaseFileId(struct vxworksFileId *pId){
579 unixEnterMutex();
580 assert( pId->nRef>0 );
581 pId->nRef--;
582 if( pId->nRef==0 ){
583 struct vxworksFileId **pp;
584 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
585 assert( *pp==pId );
586 *pp = pId->pNext;
587 sqlite3_free(pId);
588 }
589 unixLeaveMutex();
590}
591#endif /* OS_VXWORKS */
592/*************** End of Unique File ID Utility Used By VxWorks ****************
593******************************************************************************/
594
595
596/******************************************************************************
597*************************** Posix Advisory Locking ****************************
598**
drh9b35ea62008-11-29 02:20:26 +0000599** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000600** section 6.5.2.2 lines 483 through 490 specify that when a process
601** sets or clears a lock, that operation overrides any prior locks set
602** by the same process. It does not explicitly say so, but this implies
603** that it overrides locks set by the same process using a different
604** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000605**
606** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000607** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
608**
609** Suppose ./file1 and ./file2 are really the same file (because
610** one is a hard or symbolic link to the other) then if you set
611** an exclusive lock on fd1, then try to get an exclusive lock
612** on fd2, it works. I would have expected the second lock to
613** fail since there was already a lock on the file due to fd1.
614** But not so. Since both locks came from the same process, the
615** second overrides the first, even though they were on different
616** file descriptors opened on different file names.
617**
drh734c9862008-11-28 15:37:20 +0000618** This means that we cannot use POSIX locks to synchronize file access
619** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000620** to synchronize access for threads in separate processes, but not
621** threads within the same process.
622**
623** To work around the problem, SQLite has to manage file locks internally
624** on its own. Whenever a new database is opened, we have to find the
625** specific inode of the database file (the inode is determined by the
626** st_dev and st_ino fields of the stat structure that fstat() fills in)
627** and check for locks already existing on that inode. When locks are
628** created or removed, we have to look at our own internal record of the
629** locks to see if another thread has previously set a lock on that same
630** inode.
631**
drh9b35ea62008-11-29 02:20:26 +0000632** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
633** For VxWorks, we have to use the alternative unique ID system based on
634** canonical filename and implemented in the previous division.)
635**
danielk1977ad94b582007-08-20 06:44:22 +0000636** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000637** descriptor. It is now a structure that holds the integer file
638** descriptor and a pointer to a structure that describes the internal
639** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000640** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000641** point to the same locking structure. The locking structure keeps
642** a reference count (so we will know when to delete it) and a "cnt"
643** field that tells us its internal lock status. cnt==0 means the
644** file is unlocked. cnt==-1 means the file has an exclusive lock.
645** cnt>0 means there are cnt shared locks on the file.
646**
647** Any attempt to lock or unlock a file first checks the locking
648** structure. The fcntl() system call is only invoked to set a
649** POSIX lock if the internal lock structure transitions between
650** a locked and an unlocked state.
651**
drh734c9862008-11-28 15:37:20 +0000652** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000653**
654** If you close a file descriptor that points to a file that has locks,
655** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000656** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000657** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000658** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000659** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000660** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000661** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000662** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000663** be closed and that list is walked (and cleared) when the last lock
664** clears.
665**
drh9b35ea62008-11-29 02:20:26 +0000666** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000667**
drh9b35ea62008-11-29 02:20:26 +0000668** Many older versions of linux use the LinuxThreads library which is
669** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000670** A cannot be modified or overridden by a different thread B.
671** Only thread A can modify the lock. Locking behavior is correct
672** if the appliation uses the newer Native Posix Thread Library (NPTL)
673** on linux - with NPTL a lock created by thread A can override locks
674** in thread B. But there is no way to know at compile-time which
675** threading library is being used. So there is no way to know at
676** compile-time whether or not thread A can override locks on thread B.
677** We have to do a run-time check to discover the behavior of the
678** current process.
drh5fdae772004-06-29 03:29:00 +0000679**
drh734c9862008-11-28 15:37:20 +0000680** On systems where thread A is unable to modify locks created by
681** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000682** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000683** structure to record this information. And on those systems it
684** is illegal to begin a transaction in one thread and finish it
685** in another. For this latter restriction, there is no work-around.
686** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000687*/
688
689/*
drh6c7d5c52008-11-21 20:32:33 +0000690** Set or check the unixFile.tid field. This field is set when an unixFile
691** is first opened. All subsequent uses of the unixFile verify that the
692** same thread is operating on the unixFile. Some operating systems do
693** not allow locks to be overridden by other threads and that restriction
694** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000695** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000696**
697** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
698** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000699** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000700** or if no locks are held. But the unixFile.pLock field needs to be
701** recomputed because its key includes the thread-id. See the
702** transferOwnership() function below for additional information
703*/
drh734c9862008-11-28 15:37:20 +0000704#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000705# define SET_THREADID(X) (X)->tid = pthread_self()
706# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
707 !pthread_equal((X)->tid, pthread_self()))
708#else
709# define SET_THREADID(X)
710# define CHECK_THREADID(X) 0
711#endif
712
713/*
drhbbd42a62004-05-22 17:41:58 +0000714** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000715** to locate a particular unixOpenCnt structure given its inode. This
716** is the same as the unixLockKey except that the thread ID is omitted.
717*/
718struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000719 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000720#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000721 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000722#else
drh107886a2008-11-21 22:21:50 +0000723 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000724#endif
725};
726
727/*
728** An instance of the following structure serves as the key used
729** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000730**
drh734c9862008-11-28 15:37:20 +0000731** If threads cannot override each others locks (LinuxThreads), then we
732** set the unixLockKey.tid field to the thread ID. If threads can override
733** each others locks (Posix and NPTL) then tid is always set to zero.
734** tid is omitted if we compile without threading support or on an OS
735** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000736*/
drh6c7d5c52008-11-21 20:32:33 +0000737struct unixLockKey {
738 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000739#if SQLITE_THREADSAFE && defined(__linux__)
740 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000741#endif
drhbbd42a62004-05-22 17:41:58 +0000742};
743
744/*
745** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000746** inode. Or, on LinuxThreads, there is one of these structures for
747** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000748**
danielk1977ad94b582007-08-20 06:44:22 +0000749** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000750** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000751** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000752*/
drh6c7d5c52008-11-21 20:32:33 +0000753struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000754 struct unixLockKey lockKey; /* The lookup key */
755 int cnt; /* Number of SHARED locks held */
756 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
757 int nRef; /* Number of pointers to this structure */
drh7ed97b92010-01-20 13:07:21 +0000758#if defined(SQLITE_ENABLE_LOCKING_STYLE)
759 unsigned long long sharedByte; /* for AFP simulated shared lock */
760#endif
drh734c9862008-11-28 15:37:20 +0000761 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
762 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000763};
764
765/*
766** An instance of the following structure is allocated for each open
767** inode. This structure keeps track of the number of locks on that
768** inode. If a close is attempted against an inode that is holding
769** locks, the close is deferred until all locks clear by adding the
770** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000771**
772** TODO: Consider changing this so that there is only a single file
773** descriptor for each open file, even when it is opened multiple times.
774** The close() system call would only occur when the last database
775** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000776*/
drh6c7d5c52008-11-21 20:32:33 +0000777struct unixOpenCnt {
778 struct unixFileId fileId; /* The lookup key */
779 int nRef; /* Number of pointers to this structure */
780 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000781 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000782#if OS_VXWORKS
783 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000784 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000785#endif
drh6c7d5c52008-11-21 20:32:33 +0000786 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000787};
788
drhda0e7682008-07-30 15:27:54 +0000789/*
drh9b35ea62008-11-29 02:20:26 +0000790** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
791** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000792** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000793** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000794*/
drh6c7d5c52008-11-21 20:32:33 +0000795static struct unixLockInfo *lockList = 0;
796static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000797
drh5fdae772004-06-29 03:29:00 +0000798/*
drh9b35ea62008-11-29 02:20:26 +0000799** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000800** locks.
801**
drh9b35ea62008-11-29 02:20:26 +0000802** 0: No. Threads cannot override each others locks. (LinuxThreads)
803** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000804** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000805**
drh5062d3a2006-01-31 23:03:35 +0000806** On some systems, we know at compile-time if threads can override each
807** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
808** will be set appropriately. On other systems, we have to check at
809** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
810** undefined.
811**
drhf1a221e2006-01-15 17:27:17 +0000812** This variable normally has file scope only. But during testing, we make
813** it a global so that the test code can change its value in order to verify
814** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000815*/
drh715ff302008-12-03 22:32:44 +0000816#if SQLITE_THREADSAFE && defined(__linux__)
817# ifndef SQLITE_THREAD_OVERRIDE_LOCK
818# define SQLITE_THREAD_OVERRIDE_LOCK -1
819# endif
820# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000821int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000822# else
drh5062d3a2006-01-31 23:03:35 +0000823static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000824# endif
drh029b44b2006-01-15 00:13:15 +0000825#endif
drh5fdae772004-06-29 03:29:00 +0000826
827/*
828** This structure holds information passed into individual test
829** threads by the testThreadLockingBehavior() routine.
830*/
831struct threadTestData {
832 int fd; /* File to be locked */
833 struct flock lock; /* The locking operation */
834 int result; /* Result of the locking operation */
835};
836
drh6c7d5c52008-11-21 20:32:33 +0000837#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000838/*
danielk197741a6a612008-11-11 18:34:35 +0000839** This function is used as the main routine for a thread launched by
840** testThreadLockingBehavior(). It tests whether the shared-lock obtained
841** by the main thread in testThreadLockingBehavior() conflicts with a
842** hypothetical write-lock obtained by this thread on the same file.
843**
844** The write-lock is not actually acquired, as this is not possible if
845** the file is open in read-only mode (see ticket #3472).
846*/
drh5fdae772004-06-29 03:29:00 +0000847static void *threadLockingTest(void *pArg){
848 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000849 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000850 return pArg;
851}
drh6c7d5c52008-11-21 20:32:33 +0000852#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000853
drh6c7d5c52008-11-21 20:32:33 +0000854
855#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000856/*
857** This procedure attempts to determine whether or not threads
858** can override each others locks then sets the
859** threadsOverrideEachOthersLocks variable appropriately.
860*/
danielk19774d5238f2006-01-27 06:32:00 +0000861static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000862 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000863 int rc;
864 struct threadTestData d;
865 struct flock l;
866 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000867
868 fd = dup(fd_orig);
869 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000870 memset(&l, 0, sizeof(l));
871 l.l_type = F_RDLCK;
872 l.l_len = 1;
873 l.l_start = 0;
874 l.l_whence = SEEK_SET;
875 rc = fcntl(fd_orig, F_SETLK, &l);
876 if( rc!=0 ) return;
877 memset(&d, 0, sizeof(d));
878 d.fd = fd;
879 d.lock = l;
880 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000881 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
882 pthread_join(t, 0);
883 }
drh5fdae772004-06-29 03:29:00 +0000884 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000885 if( d.result!=0 ) return;
886 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000887}
drh06150f92009-07-03 12:57:58 +0000888#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000889
drhbbd42a62004-05-22 17:41:58 +0000890/*
drh6c7d5c52008-11-21 20:32:33 +0000891** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000892**
893** The mutex entered using the unixEnterMutex() function must be held
894** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000895*/
896static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000897 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000898 if( pLock ){
899 pLock->nRef--;
900 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000901 if( pLock->pPrev ){
902 assert( pLock->pPrev->pNext==pLock );
903 pLock->pPrev->pNext = pLock->pNext;
904 }else{
905 assert( lockList==pLock );
906 lockList = pLock->pNext;
907 }
908 if( pLock->pNext ){
909 assert( pLock->pNext->pPrev==pLock );
910 pLock->pNext->pPrev = pLock->pPrev;
911 }
danielk1977e339d652008-06-28 11:23:00 +0000912 sqlite3_free(pLock);
913 }
drhbbd42a62004-05-22 17:41:58 +0000914 }
915}
916
917/*
drh6c7d5c52008-11-21 20:32:33 +0000918** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000919**
920** The mutex entered using the unixEnterMutex() function must be held
921** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000922*/
drh6c7d5c52008-11-21 20:32:33 +0000923static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000924 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000925 if( pOpen ){
926 pOpen->nRef--;
927 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000928 if( pOpen->pPrev ){
929 assert( pOpen->pPrev->pNext==pOpen );
930 pOpen->pPrev->pNext = pOpen->pNext;
931 }else{
932 assert( openList==pOpen );
933 openList = pOpen->pNext;
934 }
935 if( pOpen->pNext ){
936 assert( pOpen->pNext->pPrev==pOpen );
937 pOpen->pNext->pPrev = pOpen->pPrev;
938 }
drh08da4bb2009-09-10 19:20:03 +0000939#if SQLITE_THREADSAFE && defined(__linux__)
dan11b38792009-09-09 18:46:52 +0000940 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
drh08da4bb2009-09-10 19:20:03 +0000941#endif
dan11b38792009-09-09 18:46:52 +0000942
943 /* If pOpen->pUnused is not null, then memory and file-descriptors
944 ** are leaked.
945 **
946 ** This will only happen if, under Linuxthreads, the user has opened
947 ** a transaction in one thread, then attempts to close the database
948 ** handle from another thread (without first unlocking the db file).
949 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000950 sqlite3_free(pOpen);
951 }
drhbbd42a62004-05-22 17:41:58 +0000952 }
953}
954
drh6c7d5c52008-11-21 20:32:33 +0000955/*
956** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
957** describes that file descriptor. Create new ones if necessary. The
958** return values might be uninitialized if an error occurs.
959**
dan9359c7b2009-08-21 08:29:10 +0000960** The mutex entered using the unixEnterMutex() function must be held
961** when this function is called.
962**
drh6c7d5c52008-11-21 20:32:33 +0000963** Return an appropriate error code.
964*/
965static int findLockInfo(
966 unixFile *pFile, /* Unix file with file desc used in the key */
967 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
968 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
969){
970 int rc; /* System call return code */
971 int fd; /* The file descriptor for pFile */
972 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
973 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
974 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000975 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000976 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
977
dan9359c7b2009-08-21 08:29:10 +0000978 assert( unixMutexHeld() );
979
drh6c7d5c52008-11-21 20:32:33 +0000980 /* Get low-level information about the file that we can used to
981 ** create a unique name for the file.
982 */
983 fd = pFile->h;
984 rc = fstat(fd, &statbuf);
985 if( rc!=0 ){
986 pFile->lastErrno = errno;
987#ifdef EOVERFLOW
988 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
989#endif
990 return SQLITE_IOERR;
991 }
992
drheb0d74f2009-02-03 15:27:02 +0000993#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000994 /* On OS X on an msdos filesystem, the inode number is reported
995 ** incorrectly for zero-size files. See ticket #3260. To work
996 ** around this problem (we consider it a bug in OS X, not SQLite)
997 ** we always increase the file size to 1 by writing a single byte
998 ** prior to accessing the inode number. The one byte written is
999 ** an ASCII 'S' character which also happens to be the first byte
1000 ** in the header of every SQLite database. In this way, if there
1001 ** is a race condition such that another thread has already populated
1002 ** the first page of the database, no damage is done.
1003 */
drh7ed97b92010-01-20 13:07:21 +00001004 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +00001005 rc = write(fd, "S", 1);
1006 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001007 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001008 return SQLITE_IOERR;
1009 }
drh6c7d5c52008-11-21 20:32:33 +00001010 rc = fstat(fd, &statbuf);
1011 if( rc!=0 ){
1012 pFile->lastErrno = errno;
1013 return SQLITE_IOERR;
1014 }
1015 }
drheb0d74f2009-02-03 15:27:02 +00001016#endif
drh6c7d5c52008-11-21 20:32:33 +00001017
1018 memset(&lockKey, 0, sizeof(lockKey));
1019 lockKey.fid.dev = statbuf.st_dev;
1020#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001021 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001022#else
1023 lockKey.fid.ino = statbuf.st_ino;
1024#endif
drh734c9862008-11-28 15:37:20 +00001025#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001026 if( threadsOverrideEachOthersLocks<0 ){
1027 testThreadLockingBehavior(fd);
1028 }
1029 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1030#endif
1031 fileId = lockKey.fid;
1032 if( ppLock!=0 ){
1033 pLock = lockList;
1034 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1035 pLock = pLock->pNext;
1036 }
1037 if( pLock==0 ){
1038 pLock = sqlite3_malloc( sizeof(*pLock) );
1039 if( pLock==0 ){
1040 rc = SQLITE_NOMEM;
1041 goto exit_findlockinfo;
1042 }
drh9b5db1d2009-10-07 23:42:25 +00001043 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
drh6c7d5c52008-11-21 20:32:33 +00001044 pLock->nRef = 1;
1045 pLock->cnt = 0;
1046 pLock->locktype = 0;
drh7ed97b92010-01-20 13:07:21 +00001047#if defined(SQLITE_ENABLE_LOCKING_STYLE)
1048 pLock->sharedByte = 0;
1049#endif
drh6c7d5c52008-11-21 20:32:33 +00001050 pLock->pNext = lockList;
1051 pLock->pPrev = 0;
1052 if( lockList ) lockList->pPrev = pLock;
1053 lockList = pLock;
1054 }else{
1055 pLock->nRef++;
1056 }
1057 *ppLock = pLock;
1058 }
1059 if( ppOpen!=0 ){
1060 pOpen = openList;
1061 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1062 pOpen = pOpen->pNext;
1063 }
1064 if( pOpen==0 ){
1065 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1066 if( pOpen==0 ){
1067 releaseLockInfo(pLock);
1068 rc = SQLITE_NOMEM;
1069 goto exit_findlockinfo;
1070 }
dane946c392009-08-22 11:39:46 +00001071 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001072 pOpen->fileId = fileId;
1073 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001074 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001075 if( openList ) openList->pPrev = pOpen;
1076 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001077 }else{
1078 pOpen->nRef++;
1079 }
1080 *ppOpen = pOpen;
1081 }
1082
1083exit_findlockinfo:
1084 return rc;
1085}
drh6c7d5c52008-11-21 20:32:33 +00001086
drh7708e972008-11-29 00:56:52 +00001087/*
1088** If we are currently in a different thread than the thread that the
1089** unixFile argument belongs to, then transfer ownership of the unixFile
1090** over to the current thread.
1091**
1092** A unixFile is only owned by a thread on systems that use LinuxThreads.
1093**
1094** Ownership transfer is only allowed if the unixFile is currently unlocked.
1095** If the unixFile is locked and an ownership is wrong, then return
1096** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1097*/
1098#if SQLITE_THREADSAFE && defined(__linux__)
1099static int transferOwnership(unixFile *pFile){
1100 int rc;
1101 pthread_t hSelf;
1102 if( threadsOverrideEachOthersLocks ){
1103 /* Ownership transfers not needed on this system */
1104 return SQLITE_OK;
1105 }
1106 hSelf = pthread_self();
1107 if( pthread_equal(pFile->tid, hSelf) ){
1108 /* We are still in the same thread */
1109 OSTRACE1("No-transfer, same thread\n");
1110 return SQLITE_OK;
1111 }
1112 if( pFile->locktype!=NO_LOCK ){
1113 /* We cannot change ownership while we are holding a lock! */
1114 return SQLITE_MISUSE;
1115 }
1116 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1117 pFile->h, pFile->tid, hSelf);
1118 pFile->tid = hSelf;
1119 if (pFile->pLock != NULL) {
1120 releaseLockInfo(pFile->pLock);
1121 rc = findLockInfo(pFile, &pFile->pLock, 0);
1122 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1123 locktypeName(pFile->locktype),
1124 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1125 return rc;
1126 } else {
1127 return SQLITE_OK;
1128 }
1129}
1130#else /* if not SQLITE_THREADSAFE */
1131 /* On single-threaded builds, ownership transfer is a no-op */
1132# define transferOwnership(X) SQLITE_OK
1133#endif /* SQLITE_THREADSAFE */
1134
aswift5b1a2562008-08-22 00:22:35 +00001135
1136/*
danielk197713adf8a2004-06-03 16:08:41 +00001137** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001138** file by this or any other process. If such a lock is held, set *pResOut
1139** to a non-zero value otherwise *pResOut is set to zero. The return value
1140** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001141*/
danielk1977861f7452008-06-05 11:39:11 +00001142static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001143 int rc = SQLITE_OK;
1144 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001145 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001146
danielk1977861f7452008-06-05 11:39:11 +00001147 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1148
drh054889e2005-11-30 03:20:31 +00001149 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001150 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001151
1152 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001153 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001154 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001155 }
1156
drh2ac3ee92004-06-07 16:27:46 +00001157 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001158 */
danielk197709480a92009-02-09 05:32:32 +00001159#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001160 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001161 struct flock lock;
1162 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001163 lock.l_start = RESERVED_BYTE;
1164 lock.l_len = 1;
1165 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001166 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1167 int tErrno = errno;
1168 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1169 pFile->lastErrno = tErrno;
1170 } else if( lock.l_type!=F_UNLCK ){
1171 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001172 }
1173 }
danielk197709480a92009-02-09 05:32:32 +00001174#endif
danielk197713adf8a2004-06-03 16:08:41 +00001175
drh6c7d5c52008-11-21 20:32:33 +00001176 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001177 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001178
aswift5b1a2562008-08-22 00:22:35 +00001179 *pResOut = reserved;
1180 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001181}
1182
1183/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001184** Lock the file with the lock specified by parameter locktype - one
1185** of the following:
1186**
drh2ac3ee92004-06-07 16:27:46 +00001187** (1) SHARED_LOCK
1188** (2) RESERVED_LOCK
1189** (3) PENDING_LOCK
1190** (4) EXCLUSIVE_LOCK
1191**
drhb3e04342004-06-08 00:47:47 +00001192** Sometimes when requesting one lock state, additional lock states
1193** are inserted in between. The locking might fail on one of the later
1194** transitions leaving the lock state different from what it started but
1195** still short of its goal. The following chart shows the allowed
1196** transitions and the inserted intermediate states:
1197**
1198** UNLOCKED -> SHARED
1199** SHARED -> RESERVED
1200** SHARED -> (PENDING) -> EXCLUSIVE
1201** RESERVED -> (PENDING) -> EXCLUSIVE
1202** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001203**
drha6abd042004-06-09 17:37:22 +00001204** This routine will only increase a lock. Use the sqlite3OsUnlock()
1205** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001206*/
danielk197762079062007-08-15 17:08:46 +00001207static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001208 /* The following describes the implementation of the various locks and
1209 ** lock transitions in terms of the POSIX advisory shared and exclusive
1210 ** lock primitives (called read-locks and write-locks below, to avoid
1211 ** confusion with SQLite lock names). The algorithms are complicated
1212 ** slightly in order to be compatible with windows systems simultaneously
1213 ** accessing the same database file, in case that is ever required.
1214 **
1215 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1216 ** byte', each single bytes at well known offsets, and the 'shared byte
1217 ** range', a range of 510 bytes at a well known offset.
1218 **
1219 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1220 ** byte'. If this is successful, a random byte from the 'shared byte
1221 ** range' is read-locked and the lock on the 'pending byte' released.
1222 **
danielk197790ba3bd2004-06-25 08:32:25 +00001223 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1224 ** A RESERVED lock is implemented by grabbing a write-lock on the
1225 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001226 **
1227 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001228 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1229 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1230 ** obtained, but existing SHARED locks are allowed to persist. A process
1231 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1232 ** This property is used by the algorithm for rolling back a journal file
1233 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001234 **
danielk197790ba3bd2004-06-25 08:32:25 +00001235 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1236 ** implemented by obtaining a write-lock on the entire 'shared byte
1237 ** range'. Since all other locks require a read-lock on one of the bytes
1238 ** within this range, this ensures that no other locks are held on the
1239 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001240 **
1241 ** The reason a single byte cannot be used instead of the 'shared byte
1242 ** range' is that some versions of windows do not support read-locks. By
1243 ** locking a random byte from a range, concurrent SHARED locks may exist
1244 ** even if the locking primitive used is always a write-lock.
1245 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001246 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001247 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001248 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001249 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001250 int s = 0;
drh0c2694b2009-09-03 16:23:44 +00001251 int tErrno;
danielk19779a1d0ab2004-06-01 14:09:28 +00001252
drh054889e2005-11-30 03:20:31 +00001253 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001254 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001255 locktypeName(locktype), locktypeName(pFile->locktype),
1256 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001257
1258 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001259 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001260 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001261 */
drh054889e2005-11-30 03:20:31 +00001262 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00001263 OSTRACE3("LOCK %d %s ok (already held) (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001264 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001265 return SQLITE_OK;
1266 }
1267
drh0c2694b2009-09-03 16:23:44 +00001268 /* Make sure the locking sequence is correct.
1269 ** (1) We never move from unlocked to anything higher than shared lock.
1270 ** (2) SQLite never explicitly requests a pendig lock.
1271 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001272 */
drh054889e2005-11-30 03:20:31 +00001273 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001274 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001275 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001276
drh054889e2005-11-30 03:20:31 +00001277 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001278 */
drh6c7d5c52008-11-21 20:32:33 +00001279 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001280
drh029b44b2006-01-15 00:13:15 +00001281 /* Make sure the current thread owns the pFile.
1282 */
1283 rc = transferOwnership(pFile);
1284 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001285 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001286 return rc;
1287 }
drh64b1bea2006-01-15 02:30:57 +00001288 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001289
danielk1977ad94b582007-08-20 06:44:22 +00001290 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001291 ** handle that precludes the requested lock, return BUSY.
1292 */
drh054889e2005-11-30 03:20:31 +00001293 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001294 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 ){
1296 rc = SQLITE_BUSY;
1297 goto end_lock;
1298 }
1299
1300 /* If a SHARED lock is requested, and some thread using this PID already
1301 ** has a SHARED or RESERVED lock, then increment reference counts and
1302 ** return SQLITE_OK.
1303 */
1304 if( locktype==SHARED_LOCK &&
1305 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1306 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001307 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001308 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001309 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001310 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001311 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001312 goto end_lock;
1313 }
1314
danielk19779a1d0ab2004-06-01 14:09:28 +00001315
drh3cde3bb2004-06-12 02:17:14 +00001316 /* A PENDING lock is needed before acquiring a SHARED lock and before
1317 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1318 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001319 */
drh0c2694b2009-09-03 16:23:44 +00001320 lock.l_len = 1L;
1321 lock.l_whence = SEEK_SET;
drh3cde3bb2004-06-12 02:17:14 +00001322 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001323 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001324 ){
danielk1977489468c2004-06-28 08:25:47 +00001325 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001326 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001327 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001328 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001329 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001330 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1331 if( IS_LOCK_ERROR(rc) ){
1332 pFile->lastErrno = tErrno;
1333 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001334 goto end_lock;
1335 }
drh3cde3bb2004-06-12 02:17:14 +00001336 }
1337
1338
1339 /* If control gets to this point, then actually go ahead and make
1340 ** operating system calls for the specified lock.
1341 */
1342 if( locktype==SHARED_LOCK ){
1343 assert( pLock->cnt==0 );
1344 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001345
drh2ac3ee92004-06-07 16:27:46 +00001346 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001347 lock.l_start = SHARED_FIRST;
1348 lock.l_len = SHARED_SIZE;
1349 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1350 tErrno = errno;
1351 }
drh2ac3ee92004-06-07 16:27:46 +00001352 /* Drop the temporary PENDING lock */
1353 lock.l_start = PENDING_BYTE;
1354 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001355 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001356 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001357 if( s != -1 ){
1358 /* This could happen with a network mount */
1359 tErrno = errno;
1360 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1361 if( IS_LOCK_ERROR(rc) ){
1362 pFile->lastErrno = tErrno;
1363 }
1364 goto end_lock;
1365 }
drh2b4b5962005-06-15 17:47:55 +00001366 }
drhe2396a12007-03-29 20:19:58 +00001367 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001368 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1369 if( IS_LOCK_ERROR(rc) ){
1370 pFile->lastErrno = tErrno;
1371 }
drhbbd42a62004-05-22 17:41:58 +00001372 }else{
drh054889e2005-11-30 03:20:31 +00001373 pFile->locktype = SHARED_LOCK;
1374 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001375 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001376 }
drh3cde3bb2004-06-12 02:17:14 +00001377 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1378 /* We are trying for an exclusive lock but another thread in this
1379 ** same process is still holding a shared lock. */
1380 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001381 }else{
drh3cde3bb2004-06-12 02:17:14 +00001382 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001383 ** assumed that there is a SHARED or greater lock on the file
1384 ** already.
1385 */
drh054889e2005-11-30 03:20:31 +00001386 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001387 lock.l_type = F_WRLCK;
1388 switch( locktype ){
1389 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001390 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001392 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001393 lock.l_start = SHARED_FIRST;
1394 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001395 break;
1396 default:
1397 assert(0);
1398 }
drh7ed97b92010-01-20 13:07:21 +00001399 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001400 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001401 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001402 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1403 if( IS_LOCK_ERROR(rc) ){
1404 pFile->lastErrno = tErrno;
1405 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001406 }
drhbbd42a62004-05-22 17:41:58 +00001407 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001408
drh8f941bc2009-01-14 23:03:40 +00001409
1410#ifndef NDEBUG
1411 /* Set up the transaction-counter change checking flags when
1412 ** transitioning from a SHARED to a RESERVED lock. The change
1413 ** from SHARED to RESERVED marks the beginning of a normal
1414 ** write operation (not a hot journal rollback).
1415 */
1416 if( rc==SQLITE_OK
1417 && pFile->locktype<=SHARED_LOCK
1418 && locktype==RESERVED_LOCK
1419 ){
1420 pFile->transCntrChng = 0;
1421 pFile->dbUpdate = 0;
1422 pFile->inNormalWrite = 1;
1423 }
1424#endif
1425
1426
danielk1977ecb2a962004-06-02 06:30:16 +00001427 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001428 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001429 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001430 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001431 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001432 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001433 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001434
1435end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001436 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001437 OSTRACE4("LOCK %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001438 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001439 return rc;
1440}
1441
1442/*
dane946c392009-08-22 11:39:46 +00001443** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1444** If all such file descriptors are closed without error, the list is
1445** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001446**
1447** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001448** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001449** not deleted and SQLITE_IOERR_CLOSE returned.
1450*/
1451static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001452 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001453 struct unixOpenCnt *pOpen = pFile->pOpen;
1454 UnixUnusedFd *pError = 0;
1455 UnixUnusedFd *p;
1456 UnixUnusedFd *pNext;
1457 for(p=pOpen->pUnused; p; p=pNext){
1458 pNext = p->pNext;
1459 if( close(p->fd) ){
1460 pFile->lastErrno = errno;
1461 rc = SQLITE_IOERR_CLOSE;
1462 p->pNext = pError;
1463 pError = p;
dane946c392009-08-22 11:39:46 +00001464 }else{
1465 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001466 }
1467 }
dane946c392009-08-22 11:39:46 +00001468 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001469 return rc;
1470}
1471
1472/*
1473** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001474** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001475*/
1476static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001477 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001478 UnixUnusedFd *p = pFile->pUnused;
1479 p->pNext = pOpen->pUnused;
1480 pOpen->pUnused = p;
1481 pFile->h = -1;
1482 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001483}
1484
1485/*
drh054889e2005-11-30 03:20:31 +00001486** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001487** must be either NO_LOCK or SHARED_LOCK.
1488**
1489** If the locking level of the file descriptor is already at or below
1490** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001491**
1492** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1493** the byte range is divided into 2 parts and the first part is unlocked then
1494** set to a read lock, then the other part is simply unlocked. This works
1495** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1496** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001497*/
drh7ed97b92010-01-20 13:07:21 +00001498static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
1499 unixFile *pFile = (unixFile*)id;
1500 struct unixLockInfo *pLock;
1501 struct flock lock;
1502 int rc = SQLITE_OK;
1503 int h;
drh0c2694b2009-09-03 16:23:44 +00001504 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001505
drh054889e2005-11-30 03:20:31 +00001506 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001507 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001508 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001509
1510 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001511 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001512 return SQLITE_OK;
1513 }
drhf1a221e2006-01-15 17:27:17 +00001514 if( CHECK_THREADID(pFile) ){
1515 return SQLITE_MISUSE;
1516 }
drh6c7d5c52008-11-21 20:32:33 +00001517 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001518 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001519 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001520 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001521 if( pFile->locktype>SHARED_LOCK ){
1522 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001523 SimulateIOErrorBenign(1);
1524 SimulateIOError( h=(-1) )
1525 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001526
1527#ifndef NDEBUG
1528 /* When reducing a lock such that other processes can start
1529 ** reading the database file again, make sure that the
1530 ** transaction counter was updated if any part of the database
1531 ** file changed. If the transaction counter is not updated,
1532 ** other connections to the same file might not realize that
1533 ** the file has changed and hence might not know to flush their
1534 ** cache. The use of a stale cache can lead to database corruption.
1535 */
1536 assert( pFile->inNormalWrite==0
1537 || pFile->dbUpdate==0
1538 || pFile->transCntrChng==1 );
1539 pFile->inNormalWrite = 0;
1540#endif
1541
drh7ed97b92010-01-20 13:07:21 +00001542 /* downgrading to a shared lock on NFS involves clearing the write lock
1543 ** before establishing the readlock - to avoid a race condition we downgrade
1544 ** the lock in 2 blocks, so that part of the range will be covered by a
1545 ** write lock until the rest is covered by a read lock:
1546 ** 1: [WWWWW]
1547 ** 2: [....W]
1548 ** 3: [RRRRW]
1549 ** 4: [RRRR.]
1550 */
drh9c105bb2004-10-02 20:38:28 +00001551 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001552 if( handleNFSUnlock ){
1553 off_t divSize = SHARED_SIZE - 1;
1554
1555 lock.l_type = F_UNLCK;
1556 lock.l_whence = SEEK_SET;
1557 lock.l_start = SHARED_FIRST;
1558 lock.l_len = divSize;
1559 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1560 int tErrno = errno;
1561 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1562 if( IS_LOCK_ERROR(rc) ){
1563 pFile->lastErrno = tErrno;
1564 }
1565 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001566 }
drh7ed97b92010-01-20 13:07:21 +00001567 lock.l_type = F_RDLCK;
1568 lock.l_whence = SEEK_SET;
1569 lock.l_start = SHARED_FIRST;
1570 lock.l_len = divSize;
1571 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1572 int tErrno = errno;
1573 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1574 if( IS_LOCK_ERROR(rc) ){
1575 pFile->lastErrno = tErrno;
1576 }
1577 goto end_unlock;
1578 }
1579 lock.l_type = F_UNLCK;
1580 lock.l_whence = SEEK_SET;
1581 lock.l_start = SHARED_FIRST+divSize;
1582 lock.l_len = SHARED_SIZE-divSize;
1583 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1584 int tErrno = errno;
1585 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1586 if( IS_LOCK_ERROR(rc) ){
1587 pFile->lastErrno = tErrno;
1588 }
1589 goto end_unlock;
1590 }
1591 }else{
1592 lock.l_type = F_RDLCK;
1593 lock.l_whence = SEEK_SET;
1594 lock.l_start = SHARED_FIRST;
1595 lock.l_len = SHARED_SIZE;
1596 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1597 int tErrno = errno;
1598 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1599 if( IS_LOCK_ERROR(rc) ){
1600 pFile->lastErrno = tErrno;
1601 }
1602 goto end_unlock;
1603 }
drh9c105bb2004-10-02 20:38:28 +00001604 }
1605 }
drhbbd42a62004-05-22 17:41:58 +00001606 lock.l_type = F_UNLCK;
1607 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001608 lock.l_start = PENDING_BYTE;
1609 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001610 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001611 pLock->locktype = SHARED_LOCK;
1612 }else{
drh0c2694b2009-09-03 16:23:44 +00001613 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001614 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1615 if( IS_LOCK_ERROR(rc) ){
1616 pFile->lastErrno = tErrno;
1617 }
drhcd731cf2009-03-28 23:23:02 +00001618 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001619 }
drhbbd42a62004-05-22 17:41:58 +00001620 }
drha6abd042004-06-09 17:37:22 +00001621 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001622 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001623
drha6abd042004-06-09 17:37:22 +00001624 /* Decrement the shared lock counter. Release the lock using an
1625 ** OS call only when all threads in this same process have released
1626 ** the lock.
1627 */
1628 pLock->cnt--;
1629 if( pLock->cnt==0 ){
1630 lock.l_type = F_UNLCK;
1631 lock.l_whence = SEEK_SET;
1632 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001633 SimulateIOErrorBenign(1);
1634 SimulateIOError( h=(-1) )
1635 SimulateIOErrorBenign(0);
1636 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001637 pLock->locktype = NO_LOCK;
1638 }else{
drh0c2694b2009-09-03 16:23:44 +00001639 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001640 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001641 if( IS_LOCK_ERROR(rc) ){
1642 pFile->lastErrno = tErrno;
1643 }
drhf48f9ca2009-03-28 23:47:10 +00001644 pLock->locktype = NO_LOCK;
1645 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001646 }
drha6abd042004-06-09 17:37:22 +00001647 }
1648
drhbbd42a62004-05-22 17:41:58 +00001649 /* Decrement the count of locks against this same file. When the
1650 ** count reaches zero, close any other file descriptors whose close
1651 ** was deferred because of outstanding locks.
1652 */
danielk197764a54c52009-03-30 07:39:35 +00001653 pOpen = pFile->pOpen;
1654 pOpen->nLock--;
1655 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001656 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001657 int rc2 = closePendingFds(pFile);
1658 if( rc==SQLITE_OK ){
1659 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001660 }
drhbbd42a62004-05-22 17:41:58 +00001661 }
1662 }
aswift5b1a2562008-08-22 00:22:35 +00001663
1664end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001665 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001666 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001667 return rc;
drhbbd42a62004-05-22 17:41:58 +00001668}
1669
1670/*
drh7ed97b92010-01-20 13:07:21 +00001671** Lower the locking level on file descriptor pFile to locktype. locktype
1672** must be either NO_LOCK or SHARED_LOCK.
1673**
1674** If the locking level of the file descriptor is already at or below
1675** the requested locking level, this routine is a no-op.
1676*/
1677static int unixUnlock(sqlite3_file *id, int locktype){
1678 return _posixUnlock(id, locktype, 0);
1679}
1680
1681/*
danielk1977e339d652008-06-28 11:23:00 +00001682** This function performs the parts of the "close file" operation
1683** common to all locking schemes. It closes the directory and file
1684** handles, if they are valid, and sets all fields of the unixFile
1685** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001686**
1687** It is *not* necessary to hold the mutex when this routine is called,
1688** even on VxWorks. A mutex will be acquired on VxWorks by the
1689** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001690*/
1691static int closeUnixFile(sqlite3_file *id){
1692 unixFile *pFile = (unixFile*)id;
1693 if( pFile ){
1694 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001695 int err = close(pFile->dirfd);
1696 if( err ){
1697 pFile->lastErrno = errno;
1698 return SQLITE_IOERR_DIR_CLOSE;
1699 }else{
1700 pFile->dirfd=-1;
1701 }
danielk1977e339d652008-06-28 11:23:00 +00001702 }
1703 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001704 int err = close(pFile->h);
1705 if( err ){
1706 pFile->lastErrno = errno;
1707 return SQLITE_IOERR_CLOSE;
1708 }
danielk1977e339d652008-06-28 11:23:00 +00001709 }
drh6c7d5c52008-11-21 20:32:33 +00001710#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001711 if( pFile->pId ){
1712 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001713 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001714 }
drh107886a2008-11-21 22:21:50 +00001715 vxworksReleaseFileId(pFile->pId);
1716 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001717 }
1718#endif
danielk1977e339d652008-06-28 11:23:00 +00001719 OSTRACE2("CLOSE %-3d\n", pFile->h);
1720 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001721 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001722 memset(pFile, 0, sizeof(unixFile));
1723 }
1724 return SQLITE_OK;
1725}
1726
1727/*
danielk1977e3026632004-06-22 11:29:02 +00001728** Close a file.
1729*/
danielk197762079062007-08-15 17:08:46 +00001730static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001731 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001732 if( id ){
1733 unixFile *pFile = (unixFile *)id;
1734 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001735 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001736 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001737 /* If there are outstanding locks, do not actually close the file just
1738 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001739 ** descriptor to pOpen->pUnused list. It will be automatically closed
1740 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001741 */
dan08da86a2009-08-21 17:18:03 +00001742 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001743 }
danielk1977e339d652008-06-28 11:23:00 +00001744 releaseLockInfo(pFile->pLock);
1745 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001746 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001747 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001748 }
aswiftaebf4132008-11-21 00:10:35 +00001749 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001750}
1751
drh734c9862008-11-28 15:37:20 +00001752/************** End of the posix advisory lock implementation *****************
1753******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001754
drh734c9862008-11-28 15:37:20 +00001755/******************************************************************************
1756****************************** No-op Locking **********************************
1757**
1758** Of the various locking implementations available, this is by far the
1759** simplest: locking is ignored. No attempt is made to lock the database
1760** file for reading or writing.
1761**
1762** This locking mode is appropriate for use on read-only databases
1763** (ex: databases that are burned into CD-ROM, for example.) It can
1764** also be used if the application employs some external mechanism to
1765** prevent simultaneous access of the same database by two or more
1766** database connections. But there is a serious risk of database
1767** corruption if this locking mode is used in situations where multiple
1768** database connections are accessing the same database file at the same
1769** time and one or more of those connections are writing.
1770*/
drhbfe66312006-10-03 17:40:40 +00001771
drh734c9862008-11-28 15:37:20 +00001772static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1773 UNUSED_PARAMETER(NotUsed);
1774 *pResOut = 0;
1775 return SQLITE_OK;
1776}
drh734c9862008-11-28 15:37:20 +00001777static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1778 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1779 return SQLITE_OK;
1780}
drh734c9862008-11-28 15:37:20 +00001781static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1782 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1783 return SQLITE_OK;
1784}
1785
1786/*
drh9b35ea62008-11-29 02:20:26 +00001787** Close the file.
drh734c9862008-11-28 15:37:20 +00001788*/
1789static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001790 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001791}
1792
1793/******************* End of the no-op lock implementation *********************
1794******************************************************************************/
1795
1796/******************************************************************************
1797************************* Begin dot-file Locking ******************************
1798**
drh0c2694b2009-09-03 16:23:44 +00001799** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001800** files in order to control access to the database. This works on just
1801** about every filesystem imaginable. But there are serious downsides:
1802**
1803** (1) There is zero concurrency. A single reader blocks all other
1804** connections from reading or writing the database.
1805**
1806** (2) An application crash or power loss can leave stale lock files
1807** sitting around that need to be cleared manually.
1808**
1809** Nevertheless, a dotlock is an appropriate locking mode for use if no
1810** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001811**
1812** Dotfile locking works by creating a file in the same directory as the
1813** database and with the same name but with a ".lock" extension added.
1814** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1815** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001816*/
1817
1818/*
1819** The file suffix added to the data base filename in order to create the
1820** lock file.
1821*/
1822#define DOTLOCK_SUFFIX ".lock"
1823
drh7708e972008-11-29 00:56:52 +00001824/*
1825** This routine checks if there is a RESERVED lock held on the specified
1826** file by this or any other process. If such a lock is held, set *pResOut
1827** to a non-zero value otherwise *pResOut is set to zero. The return value
1828** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1829**
1830** In dotfile locking, either a lock exists or it does not. So in this
1831** variation of CheckReservedLock(), *pResOut is set to true if any lock
1832** is held on the file and false if the file is unlocked.
1833*/
drh734c9862008-11-28 15:37:20 +00001834static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1835 int rc = SQLITE_OK;
1836 int reserved = 0;
1837 unixFile *pFile = (unixFile*)id;
1838
1839 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1840
1841 assert( pFile );
1842
1843 /* Check if a thread in this process holds such a lock */
1844 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001845 /* Either this connection or some other connection in the same process
1846 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001847 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001848 }else{
1849 /* The lock is held if and only if the lockfile exists */
1850 const char *zLockFile = (const char*)pFile->lockingContext;
1851 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001852 }
drh476bda72009-12-04 14:25:18 +00001853 OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001854 *pResOut = reserved;
1855 return rc;
1856}
1857
drh7708e972008-11-29 00:56:52 +00001858/*
1859** Lock the file with the lock specified by parameter locktype - one
1860** of the following:
1861**
1862** (1) SHARED_LOCK
1863** (2) RESERVED_LOCK
1864** (3) PENDING_LOCK
1865** (4) EXCLUSIVE_LOCK
1866**
1867** Sometimes when requesting one lock state, additional lock states
1868** are inserted in between. The locking might fail on one of the later
1869** transitions leaving the lock state different from what it started but
1870** still short of its goal. The following chart shows the allowed
1871** transitions and the inserted intermediate states:
1872**
1873** UNLOCKED -> SHARED
1874** SHARED -> RESERVED
1875** SHARED -> (PENDING) -> EXCLUSIVE
1876** RESERVED -> (PENDING) -> EXCLUSIVE
1877** PENDING -> EXCLUSIVE
1878**
1879** This routine will only increase a lock. Use the sqlite3OsUnlock()
1880** routine to lower a locking level.
1881**
1882** With dotfile locking, we really only support state (4): EXCLUSIVE.
1883** But we track the other locking levels internally.
1884*/
drh734c9862008-11-28 15:37:20 +00001885static int dotlockLock(sqlite3_file *id, int locktype) {
1886 unixFile *pFile = (unixFile*)id;
1887 int fd;
1888 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001889 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001890
drh7708e972008-11-29 00:56:52 +00001891
1892 /* If we have any lock, then the lock file already exists. All we have
1893 ** to do is adjust our internal record of the lock level.
1894 */
1895 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001896 pFile->locktype = locktype;
1897#if !OS_VXWORKS
1898 /* Always update the timestamp on the old file */
1899 utimes(zLockFile, NULL);
1900#endif
drh7708e972008-11-29 00:56:52 +00001901 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001902 }
1903
1904 /* grab an exclusive lock */
1905 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1906 if( fd<0 ){
1907 /* failed to open/create the file, someone else may have stolen the lock */
1908 int tErrno = errno;
1909 if( EEXIST == tErrno ){
1910 rc = SQLITE_BUSY;
1911 } else {
1912 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1913 if( IS_LOCK_ERROR(rc) ){
1914 pFile->lastErrno = tErrno;
1915 }
1916 }
drh7708e972008-11-29 00:56:52 +00001917 return rc;
drh734c9862008-11-28 15:37:20 +00001918 }
1919 if( close(fd) ){
1920 pFile->lastErrno = errno;
1921 rc = SQLITE_IOERR_CLOSE;
1922 }
1923
1924 /* got it, set the type and return ok */
1925 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001926 return rc;
1927}
1928
drh7708e972008-11-29 00:56:52 +00001929/*
1930** Lower the locking level on file descriptor pFile to locktype. locktype
1931** must be either NO_LOCK or SHARED_LOCK.
1932**
1933** If the locking level of the file descriptor is already at or below
1934** the requested locking level, this routine is a no-op.
1935**
1936** When the locking level reaches NO_LOCK, delete the lock file.
1937*/
drh734c9862008-11-28 15:37:20 +00001938static int dotlockUnlock(sqlite3_file *id, int locktype) {
1939 unixFile *pFile = (unixFile*)id;
1940 char *zLockFile = (char *)pFile->lockingContext;
1941
1942 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001943 OSTRACE5("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00001944 pFile->locktype, getpid());
1945 assert( locktype<=SHARED_LOCK );
1946
1947 /* no-op if possible */
1948 if( pFile->locktype==locktype ){
1949 return SQLITE_OK;
1950 }
drh7708e972008-11-29 00:56:52 +00001951
1952 /* To downgrade to shared, simply update our internal notion of the
1953 ** lock state. No need to mess with the file on disk.
1954 */
1955 if( locktype==SHARED_LOCK ){
1956 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001957 return SQLITE_OK;
1958 }
1959
drh7708e972008-11-29 00:56:52 +00001960 /* To fully unlock the database, delete the lock file */
1961 assert( locktype==NO_LOCK );
1962 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001963 int rc = 0;
1964 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001965 if( ENOENT != tErrno ){
1966 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1967 }
1968 if( IS_LOCK_ERROR(rc) ){
1969 pFile->lastErrno = tErrno;
1970 }
1971 return rc;
1972 }
1973 pFile->locktype = NO_LOCK;
1974 return SQLITE_OK;
1975}
1976
1977/*
drh9b35ea62008-11-29 02:20:26 +00001978** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001979*/
1980static int dotlockClose(sqlite3_file *id) {
1981 int rc;
1982 if( id ){
1983 unixFile *pFile = (unixFile*)id;
1984 dotlockUnlock(id, NO_LOCK);
1985 sqlite3_free(pFile->lockingContext);
1986 }
drh734c9862008-11-28 15:37:20 +00001987 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001988 return rc;
1989}
1990/****************** End of the dot-file lock implementation *******************
1991******************************************************************************/
1992
1993/******************************************************************************
1994************************** Begin flock Locking ********************************
1995**
1996** Use the flock() system call to do file locking.
1997**
drh6b9d6dd2008-12-03 19:34:47 +00001998** flock() locking is like dot-file locking in that the various
1999** fine-grain locking levels supported by SQLite are collapsed into
2000** a single exclusive lock. In other words, SHARED, RESERVED, and
2001** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2002** still works when you do this, but concurrency is reduced since
2003** only a single process can be reading the database at a time.
2004**
drh734c9862008-11-28 15:37:20 +00002005** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2006** compiling for VXWORKS.
2007*/
2008#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002009
drh6b9d6dd2008-12-03 19:34:47 +00002010/*
2011** This routine checks if there is a RESERVED lock held on the specified
2012** file by this or any other process. If such a lock is held, set *pResOut
2013** to a non-zero value otherwise *pResOut is set to zero. The return value
2014** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2015*/
drh734c9862008-11-28 15:37:20 +00002016static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2017 int rc = SQLITE_OK;
2018 int reserved = 0;
2019 unixFile *pFile = (unixFile*)id;
2020
2021 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2022
2023 assert( pFile );
2024
2025 /* Check if a thread in this process holds such a lock */
2026 if( pFile->locktype>SHARED_LOCK ){
2027 reserved = 1;
2028 }
2029
2030 /* Otherwise see if some other process holds it. */
2031 if( !reserved ){
2032 /* attempt to get the lock */
2033 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2034 if( !lrc ){
2035 /* got the lock, unlock it */
2036 lrc = flock(pFile->h, LOCK_UN);
2037 if ( lrc ) {
2038 int tErrno = errno;
2039 /* unlock failed with an error */
2040 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2041 if( IS_LOCK_ERROR(lrc) ){
2042 pFile->lastErrno = tErrno;
2043 rc = lrc;
2044 }
2045 }
2046 } else {
2047 int tErrno = errno;
2048 reserved = 1;
2049 /* someone else might have it reserved */
2050 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2051 if( IS_LOCK_ERROR(lrc) ){
2052 pFile->lastErrno = tErrno;
2053 rc = lrc;
2054 }
2055 }
2056 }
drh476bda72009-12-04 14:25:18 +00002057 OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002058
2059#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2060 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2061 rc = SQLITE_OK;
2062 reserved=1;
2063 }
2064#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2065 *pResOut = reserved;
2066 return rc;
2067}
2068
drh6b9d6dd2008-12-03 19:34:47 +00002069/*
2070** Lock the file with the lock specified by parameter locktype - one
2071** of the following:
2072**
2073** (1) SHARED_LOCK
2074** (2) RESERVED_LOCK
2075** (3) PENDING_LOCK
2076** (4) EXCLUSIVE_LOCK
2077**
2078** Sometimes when requesting one lock state, additional lock states
2079** are inserted in between. The locking might fail on one of the later
2080** transitions leaving the lock state different from what it started but
2081** still short of its goal. The following chart shows the allowed
2082** transitions and the inserted intermediate states:
2083**
2084** UNLOCKED -> SHARED
2085** SHARED -> RESERVED
2086** SHARED -> (PENDING) -> EXCLUSIVE
2087** RESERVED -> (PENDING) -> EXCLUSIVE
2088** PENDING -> EXCLUSIVE
2089**
2090** flock() only really support EXCLUSIVE locks. We track intermediate
2091** lock states in the sqlite3_file structure, but all locks SHARED or
2092** above are really EXCLUSIVE locks and exclude all other processes from
2093** access the file.
2094**
2095** This routine will only increase a lock. Use the sqlite3OsUnlock()
2096** routine to lower a locking level.
2097*/
drh734c9862008-11-28 15:37:20 +00002098static int flockLock(sqlite3_file *id, int locktype) {
2099 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002100 unixFile *pFile = (unixFile*)id;
2101
2102 assert( pFile );
2103
2104 /* if we already have a lock, it is exclusive.
2105 ** Just adjust level and punt on outta here. */
2106 if (pFile->locktype > NO_LOCK) {
2107 pFile->locktype = locktype;
2108 return SQLITE_OK;
2109 }
2110
2111 /* grab an exclusive lock */
2112
2113 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2114 int tErrno = errno;
2115 /* didn't get, must be busy */
2116 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2117 if( IS_LOCK_ERROR(rc) ){
2118 pFile->lastErrno = tErrno;
2119 }
2120 } else {
2121 /* got it, set the type and return ok */
2122 pFile->locktype = locktype;
2123 }
drh476bda72009-12-04 14:25:18 +00002124 OSTRACE4("LOCK %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
drh734c9862008-11-28 15:37:20 +00002125 rc==SQLITE_OK ? "ok" : "failed");
2126#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2127 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2128 rc = SQLITE_BUSY;
2129 }
2130#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2131 return rc;
2132}
2133
drh6b9d6dd2008-12-03 19:34:47 +00002134
2135/*
2136** Lower the locking level on file descriptor pFile to locktype. locktype
2137** must be either NO_LOCK or SHARED_LOCK.
2138**
2139** If the locking level of the file descriptor is already at or below
2140** the requested locking level, this routine is a no-op.
2141*/
drh734c9862008-11-28 15:37:20 +00002142static int flockUnlock(sqlite3_file *id, int locktype) {
2143 unixFile *pFile = (unixFile*)id;
2144
2145 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002146 OSTRACE5("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002147 pFile->locktype, getpid());
2148 assert( locktype<=SHARED_LOCK );
2149
2150 /* no-op if possible */
2151 if( pFile->locktype==locktype ){
2152 return SQLITE_OK;
2153 }
2154
2155 /* shared can just be set because we always have an exclusive */
2156 if (locktype==SHARED_LOCK) {
2157 pFile->locktype = locktype;
2158 return SQLITE_OK;
2159 }
2160
2161 /* no, really, unlock. */
2162 int rc = flock(pFile->h, LOCK_UN);
2163 if (rc) {
2164 int r, tErrno = errno;
2165 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2166 if( IS_LOCK_ERROR(r) ){
2167 pFile->lastErrno = tErrno;
2168 }
2169#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2170 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2171 r = SQLITE_BUSY;
2172 }
2173#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2174
2175 return r;
2176 } else {
2177 pFile->locktype = NO_LOCK;
2178 return SQLITE_OK;
2179 }
2180}
2181
2182/*
2183** Close a file.
2184*/
2185static int flockClose(sqlite3_file *id) {
2186 if( id ){
2187 flockUnlock(id, NO_LOCK);
2188 }
2189 return closeUnixFile(id);
2190}
2191
2192#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2193
2194/******************* End of the flock lock implementation *********************
2195******************************************************************************/
2196
2197/******************************************************************************
2198************************ Begin Named Semaphore Locking ************************
2199**
2200** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002201**
2202** Semaphore locking is like dot-lock and flock in that it really only
2203** supports EXCLUSIVE locking. Only a single process can read or write
2204** the database file at a time. This reduces potential concurrency, but
2205** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002206*/
2207#if OS_VXWORKS
2208
drh6b9d6dd2008-12-03 19:34:47 +00002209/*
2210** This routine checks if there is a RESERVED lock held on the specified
2211** file by this or any other process. If such a lock is held, set *pResOut
2212** to a non-zero value otherwise *pResOut is set to zero. The return value
2213** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2214*/
drh734c9862008-11-28 15:37:20 +00002215static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2216 int rc = SQLITE_OK;
2217 int reserved = 0;
2218 unixFile *pFile = (unixFile*)id;
2219
2220 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2221
2222 assert( pFile );
2223
2224 /* Check if a thread in this process holds such a lock */
2225 if( pFile->locktype>SHARED_LOCK ){
2226 reserved = 1;
2227 }
2228
2229 /* Otherwise see if some other process holds it. */
2230 if( !reserved ){
2231 sem_t *pSem = pFile->pOpen->pSem;
2232 struct stat statBuf;
2233
2234 if( sem_trywait(pSem)==-1 ){
2235 int tErrno = errno;
2236 if( EAGAIN != tErrno ){
2237 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2238 pFile->lastErrno = tErrno;
2239 } else {
2240 /* someone else has the lock when we are in NO_LOCK */
2241 reserved = (pFile->locktype < SHARED_LOCK);
2242 }
2243 }else{
2244 /* we could have it if we want it */
2245 sem_post(pSem);
2246 }
2247 }
drh476bda72009-12-04 14:25:18 +00002248 OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002249
2250 *pResOut = reserved;
2251 return rc;
2252}
2253
drh6b9d6dd2008-12-03 19:34:47 +00002254/*
2255** Lock the file with the lock specified by parameter locktype - one
2256** of the following:
2257**
2258** (1) SHARED_LOCK
2259** (2) RESERVED_LOCK
2260** (3) PENDING_LOCK
2261** (4) EXCLUSIVE_LOCK
2262**
2263** Sometimes when requesting one lock state, additional lock states
2264** are inserted in between. The locking might fail on one of the later
2265** transitions leaving the lock state different from what it started but
2266** still short of its goal. The following chart shows the allowed
2267** transitions and the inserted intermediate states:
2268**
2269** UNLOCKED -> SHARED
2270** SHARED -> RESERVED
2271** SHARED -> (PENDING) -> EXCLUSIVE
2272** RESERVED -> (PENDING) -> EXCLUSIVE
2273** PENDING -> EXCLUSIVE
2274**
2275** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2276** lock states in the sqlite3_file structure, but all locks SHARED or
2277** above are really EXCLUSIVE locks and exclude all other processes from
2278** access the file.
2279**
2280** This routine will only increase a lock. Use the sqlite3OsUnlock()
2281** routine to lower a locking level.
2282*/
drh734c9862008-11-28 15:37:20 +00002283static int semLock(sqlite3_file *id, int locktype) {
2284 unixFile *pFile = (unixFile*)id;
2285 int fd;
2286 sem_t *pSem = pFile->pOpen->pSem;
2287 int rc = SQLITE_OK;
2288
2289 /* if we already have a lock, it is exclusive.
2290 ** Just adjust level and punt on outta here. */
2291 if (pFile->locktype > NO_LOCK) {
2292 pFile->locktype = locktype;
2293 rc = SQLITE_OK;
2294 goto sem_end_lock;
2295 }
2296
2297 /* lock semaphore now but bail out when already locked. */
2298 if( sem_trywait(pSem)==-1 ){
2299 rc = SQLITE_BUSY;
2300 goto sem_end_lock;
2301 }
2302
2303 /* got it, set the type and return ok */
2304 pFile->locktype = locktype;
2305
2306 sem_end_lock:
2307 return rc;
2308}
2309
drh6b9d6dd2008-12-03 19:34:47 +00002310/*
2311** Lower the locking level on file descriptor pFile to locktype. locktype
2312** must be either NO_LOCK or SHARED_LOCK.
2313**
2314** If the locking level of the file descriptor is already at or below
2315** the requested locking level, this routine is a no-op.
2316*/
drh734c9862008-11-28 15:37:20 +00002317static int semUnlock(sqlite3_file *id, int locktype) {
2318 unixFile *pFile = (unixFile*)id;
2319 sem_t *pSem = pFile->pOpen->pSem;
2320
2321 assert( pFile );
2322 assert( pSem );
drh476bda72009-12-04 14:25:18 +00002323 OSTRACE5("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002324 pFile->locktype, getpid());
2325 assert( locktype<=SHARED_LOCK );
2326
2327 /* no-op if possible */
2328 if( pFile->locktype==locktype ){
2329 return SQLITE_OK;
2330 }
2331
2332 /* shared can just be set because we always have an exclusive */
2333 if (locktype==SHARED_LOCK) {
2334 pFile->locktype = locktype;
2335 return SQLITE_OK;
2336 }
2337
2338 /* no, really unlock. */
2339 if ( sem_post(pSem)==-1 ) {
2340 int rc, tErrno = errno;
2341 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2342 if( IS_LOCK_ERROR(rc) ){
2343 pFile->lastErrno = tErrno;
2344 }
2345 return rc;
2346 }
2347 pFile->locktype = NO_LOCK;
2348 return SQLITE_OK;
2349}
2350
2351/*
2352 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002353 */
drh734c9862008-11-28 15:37:20 +00002354static int semClose(sqlite3_file *id) {
2355 if( id ){
2356 unixFile *pFile = (unixFile*)id;
2357 semUnlock(id, NO_LOCK);
2358 assert( pFile );
2359 unixEnterMutex();
2360 releaseLockInfo(pFile->pLock);
2361 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002362 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002363 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002364 }
2365 return SQLITE_OK;
2366}
2367
2368#endif /* OS_VXWORKS */
2369/*
2370** Named semaphore locking is only available on VxWorks.
2371**
2372*************** End of the named semaphore lock implementation ****************
2373******************************************************************************/
2374
2375
2376/******************************************************************************
2377*************************** Begin AFP Locking *********************************
2378**
2379** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2380** on Apple Macintosh computers - both OS9 and OSX.
2381**
2382** Third-party implementations of AFP are available. But this code here
2383** only works on OSX.
2384*/
2385
drhd2cb50b2009-01-09 21:41:17 +00002386#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002387/*
2388** The afpLockingContext structure contains all afp lock specific state
2389*/
drhbfe66312006-10-03 17:40:40 +00002390typedef struct afpLockingContext afpLockingContext;
2391struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002392 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002393 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002394};
2395
2396struct ByteRangeLockPB2
2397{
2398 unsigned long long offset; /* offset to first byte to lock */
2399 unsigned long long length; /* nbr of bytes to lock */
2400 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2401 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2402 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2403 int fd; /* file desc to assoc this lock with */
2404};
2405
drhfd131da2007-08-07 17:13:03 +00002406#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002407
drh6b9d6dd2008-12-03 19:34:47 +00002408/*
2409** This is a utility for setting or clearing a bit-range lock on an
2410** AFP filesystem.
2411**
2412** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2413*/
2414static int afpSetLock(
2415 const char *path, /* Name of the file to be locked or unlocked */
2416 unixFile *pFile, /* Open file descriptor on path */
2417 unsigned long long offset, /* First byte to be locked */
2418 unsigned long long length, /* Number of bytes to lock */
2419 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002420){
drh6b9d6dd2008-12-03 19:34:47 +00002421 struct ByteRangeLockPB2 pb;
2422 int err;
drhbfe66312006-10-03 17:40:40 +00002423
2424 pb.unLockFlag = setLockFlag ? 0 : 1;
2425 pb.startEndFlag = 0;
2426 pb.offset = offset;
2427 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002428 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002429
2430 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002431 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2432 offset, length);
drhbfe66312006-10-03 17:40:40 +00002433 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2434 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002435 int rc;
2436 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002437 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2438 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002439#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2440 rc = SQLITE_BUSY;
2441#else
drh734c9862008-11-28 15:37:20 +00002442 rc = sqliteErrorFromPosixError(tErrno,
2443 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002444#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002445 if( IS_LOCK_ERROR(rc) ){
2446 pFile->lastErrno = tErrno;
2447 }
2448 return rc;
drhbfe66312006-10-03 17:40:40 +00002449 } else {
aswift5b1a2562008-08-22 00:22:35 +00002450 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002451 }
2452}
2453
drh6b9d6dd2008-12-03 19:34:47 +00002454/*
2455** This routine checks if there is a RESERVED lock held on the specified
2456** file by this or any other process. If such a lock is held, set *pResOut
2457** to a non-zero value otherwise *pResOut is set to zero. The return value
2458** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2459*/
danielk1977e339d652008-06-28 11:23:00 +00002460static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002461 int rc = SQLITE_OK;
2462 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002463 unixFile *pFile = (unixFile*)id;
2464
aswift5b1a2562008-08-22 00:22:35 +00002465 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2466
2467 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002468 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002469 if( context->reserved ){
2470 *pResOut = 1;
2471 return SQLITE_OK;
2472 }
2473 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002474
2475 /* Check if a thread in this process holds such a lock */
drh7ed97b92010-01-20 13:07:21 +00002476 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002477 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002478 }
2479
2480 /* Otherwise see if some other process holds it.
2481 */
aswift5b1a2562008-08-22 00:22:35 +00002482 if( !reserved ){
2483 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002484 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002485 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002486 /* if we succeeded in taking the reserved lock, unlock it to restore
2487 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002488 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002489 } else {
2490 /* if we failed to get the lock then someone else must have it */
2491 reserved = 1;
2492 }
2493 if( IS_LOCK_ERROR(lrc) ){
2494 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002495 }
2496 }
drhbfe66312006-10-03 17:40:40 +00002497
drh7ed97b92010-01-20 13:07:21 +00002498 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002499 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
aswift5b1a2562008-08-22 00:22:35 +00002500
2501 *pResOut = reserved;
2502 return rc;
drhbfe66312006-10-03 17:40:40 +00002503}
2504
drh6b9d6dd2008-12-03 19:34:47 +00002505/*
2506** Lock the file with the lock specified by parameter locktype - one
2507** of the following:
2508**
2509** (1) SHARED_LOCK
2510** (2) RESERVED_LOCK
2511** (3) PENDING_LOCK
2512** (4) EXCLUSIVE_LOCK
2513**
2514** Sometimes when requesting one lock state, additional lock states
2515** are inserted in between. The locking might fail on one of the later
2516** transitions leaving the lock state different from what it started but
2517** still short of its goal. The following chart shows the allowed
2518** transitions and the inserted intermediate states:
2519**
2520** UNLOCKED -> SHARED
2521** SHARED -> RESERVED
2522** SHARED -> (PENDING) -> EXCLUSIVE
2523** RESERVED -> (PENDING) -> EXCLUSIVE
2524** PENDING -> EXCLUSIVE
2525**
2526** This routine will only increase a lock. Use the sqlite3OsUnlock()
2527** routine to lower a locking level.
2528*/
danielk1977e339d652008-06-28 11:23:00 +00002529static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002530 int rc = SQLITE_OK;
2531 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002532 struct unixLockInfo *pLock = pFile->pLock;
drhbfe66312006-10-03 17:40:40 +00002533 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002534
2535 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002536 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2537 locktypeName(locktype), locktypeName(pFile->locktype),
2538 locktypeName(pLock->locktype), pLock->cnt , getpid());
drh339eb0b2008-03-07 15:34:11 +00002539
drhbfe66312006-10-03 17:40:40 +00002540 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002541 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002542 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002543 */
drhbfe66312006-10-03 17:40:40 +00002544 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00002545 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002546 locktypeName(locktype));
2547 return SQLITE_OK;
2548 }
2549
2550 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002551 ** (1) We never move from unlocked to anything higher than shared lock.
2552 ** (2) SQLite never explicitly requests a pendig lock.
2553 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002554 */
drhbfe66312006-10-03 17:40:40 +00002555 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2556 assert( locktype!=PENDING_LOCK );
2557 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2558
2559 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002560 */
drh6c7d5c52008-11-21 20:32:33 +00002561 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002562
2563 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002564 */
drhbfe66312006-10-03 17:40:40 +00002565 rc = transferOwnership(pFile);
2566 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002567 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002568 return rc;
2569 }
drh7ed97b92010-01-20 13:07:21 +00002570 pLock = pFile->pLock;
2571
2572 /* If some thread using this PID has a lock via a different unixFile*
2573 ** handle that precludes the requested lock, return BUSY.
2574 */
2575 if( (pFile->locktype!=pLock->locktype &&
2576 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
2577 ){
2578 rc = SQLITE_BUSY;
2579 goto afp_end_lock;
2580 }
2581
2582 /* If a SHARED lock is requested, and some thread using this PID already
2583 ** has a SHARED or RESERVED lock, then increment reference counts and
2584 ** return SQLITE_OK.
2585 */
2586 if( locktype==SHARED_LOCK &&
2587 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
2588 assert( locktype==SHARED_LOCK );
2589 assert( pFile->locktype==0 );
2590 assert( pLock->cnt>0 );
2591 pFile->locktype = SHARED_LOCK;
2592 pLock->cnt++;
2593 pFile->pOpen->nLock++;
2594 goto afp_end_lock;
2595 }
drhbfe66312006-10-03 17:40:40 +00002596
2597 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002598 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2599 ** be released.
2600 */
drhbfe66312006-10-03 17:40:40 +00002601 if( locktype==SHARED_LOCK
2602 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002603 ){
2604 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002605 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002606 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002607 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002608 goto afp_end_lock;
2609 }
2610 }
2611
2612 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002613 ** operating system calls for the specified lock.
2614 */
drhbfe66312006-10-03 17:40:40 +00002615 if( locktype==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002616 int lrc1, lrc2, lrc1Errno;
2617 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002618
drh7ed97b92010-01-20 13:07:21 +00002619 assert( pLock->cnt==0 );
2620 assert( pLock->locktype==0 );
2621
2622 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002623 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002624 /* note that the quality of the randomness doesn't matter that much */
2625 lk = random();
drh7ed97b92010-01-20 13:07:21 +00002626 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002627 lrc1 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002628 SHARED_FIRST+pLock->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002629 if( IS_LOCK_ERROR(lrc1) ){
2630 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002631 }
aswift5b1a2562008-08-22 00:22:35 +00002632 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002633 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002634
aswift5b1a2562008-08-22 00:22:35 +00002635 if( IS_LOCK_ERROR(lrc1) ) {
2636 pFile->lastErrno = lrc1Errno;
2637 rc = lrc1;
2638 goto afp_end_lock;
2639 } else if( IS_LOCK_ERROR(lrc2) ){
2640 rc = lrc2;
2641 goto afp_end_lock;
2642 } else if( lrc1 != SQLITE_OK ) {
2643 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002644 } else {
2645 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002646 pFile->pOpen->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002647 pLock->cnt = 1;
drhbfe66312006-10-03 17:40:40 +00002648 }
drh7ed97b92010-01-20 13:07:21 +00002649 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
2650 /* We are trying for an exclusive lock but another thread in this
2651 ** same process is still holding a shared lock. */
2652 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002653 }else{
2654 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2655 ** assumed that there is a SHARED or greater lock on the file
2656 ** already.
2657 */
2658 int failed = 0;
2659 assert( 0!=pFile->locktype );
2660 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2661 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002662 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002663 if( !failed ){
2664 context->reserved = 1;
2665 }
drhbfe66312006-10-03 17:40:40 +00002666 }
2667 if (!failed && locktype == EXCLUSIVE_LOCK) {
2668 /* Acquire an EXCLUSIVE lock */
2669
2670 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002671 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002672 */
drh6b9d6dd2008-12-03 19:34:47 +00002673 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh7ed97b92010-01-20 13:07:21 +00002674 pLock->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002675 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002676 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002677 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002678 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002679 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh7ed97b92010-01-20 13:07:21 +00002680 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002681 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2682 ** a critical I/O error
2683 */
2684 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2685 SQLITE_IOERR_LOCK;
2686 goto afp_end_lock;
2687 }
2688 }else{
aswift5b1a2562008-08-22 00:22:35 +00002689 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002690 }
2691 }
aswift5b1a2562008-08-22 00:22:35 +00002692 if( failed ){
2693 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002694 }
2695 }
2696
2697 if( rc==SQLITE_OK ){
2698 pFile->locktype = locktype;
drh7ed97b92010-01-20 13:07:21 +00002699 pLock->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002700 }else if( locktype==EXCLUSIVE_LOCK ){
2701 pFile->locktype = PENDING_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002702 pLock->locktype = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002703 }
2704
2705afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002706 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002707 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002708 rc==SQLITE_OK ? "ok" : "failed");
2709 return rc;
2710}
2711
2712/*
drh339eb0b2008-03-07 15:34:11 +00002713** Lower the locking level on file descriptor pFile to locktype. locktype
2714** must be either NO_LOCK or SHARED_LOCK.
2715**
2716** If the locking level of the file descriptor is already at or below
2717** the requested locking level, this routine is a no-op.
2718*/
danielk1977e339d652008-06-28 11:23:00 +00002719static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002720 int rc = SQLITE_OK;
2721 unixFile *pFile = (unixFile*)id;
drh7ed97b92010-01-20 13:07:21 +00002722 struct unixLockInfo *pLock;
2723 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2724 int skipShared = 0;
2725#ifdef SQLITE_TEST
2726 int h = pFile->h;
2727#endif
drhbfe66312006-10-03 17:40:40 +00002728
2729 assert( pFile );
drh7ed97b92010-01-20 13:07:21 +00002730 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
2731 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002732
drhbfe66312006-10-03 17:40:40 +00002733 assert( locktype<=SHARED_LOCK );
2734 if( pFile->locktype<=locktype ){
2735 return SQLITE_OK;
2736 }
2737 if( CHECK_THREADID(pFile) ){
2738 return SQLITE_MISUSE;
2739 }
drh6c7d5c52008-11-21 20:32:33 +00002740 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00002741 pLock = pFile->pLock;
2742 assert( pLock->cnt!=0 );
drhbfe66312006-10-03 17:40:40 +00002743 if( pFile->locktype>SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002744 assert( pLock->locktype==pFile->locktype );
2745 SimulateIOErrorBenign(1);
2746 SimulateIOError( h=(-1) )
2747 SimulateIOErrorBenign(0);
2748
2749#ifndef NDEBUG
2750 /* When reducing a lock such that other processes can start
2751 ** reading the database file again, make sure that the
2752 ** transaction counter was updated if any part of the database
2753 ** file changed. If the transaction counter is not updated,
2754 ** other connections to the same file might not realize that
2755 ** the file has changed and hence might not know to flush their
2756 ** cache. The use of a stale cache can lead to database corruption.
2757 */
2758 assert( pFile->inNormalWrite==0
2759 || pFile->dbUpdate==0
2760 || pFile->transCntrChng==1 );
2761 pFile->inNormalWrite = 0;
2762#endif
aswiftaebf4132008-11-21 00:10:35 +00002763
2764 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002765 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2766 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002767 /* only re-establish the shared lock if necessary */
drh7ed97b92010-01-20 13:07:21 +00002768 int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2769 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2770 } else {
2771 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002772 }
2773 }
2774 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002775 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002776 }
drh7ed97b92010-01-20 13:07:21 +00002777 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
2778 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2779 if( !rc ){
2780 context->reserved = 0;
2781 }
aswiftaebf4132008-11-21 00:10:35 +00002782 }
drh7ed97b92010-01-20 13:07:21 +00002783 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
2784 pLock->locktype = SHARED_LOCK;
2785 }
aswiftaebf4132008-11-21 00:10:35 +00002786 }
drh7ed97b92010-01-20 13:07:21 +00002787 if( rc==SQLITE_OK && locktype==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002788
drh7ed97b92010-01-20 13:07:21 +00002789 /* Decrement the shared lock counter. Release the lock using an
2790 ** OS call only when all threads in this same process have released
2791 ** the lock.
2792 */
2793 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
2794 pLock->cnt--;
2795 if( pLock->cnt==0 ){
2796 SimulateIOErrorBenign(1);
2797 SimulateIOError( h=(-1) )
2798 SimulateIOErrorBenign(0);
2799 if( !skipShared ){
2800 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2801 }
2802 if( !rc ){
2803 pLock->locktype = NO_LOCK;
2804 pFile->locktype = NO_LOCK;
2805 }
2806 }
2807 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002808 struct unixOpenCnt *pOpen = pFile->pOpen;
drh7ed97b92010-01-20 13:07:21 +00002809
aswiftaebf4132008-11-21 00:10:35 +00002810 pOpen->nLock--;
2811 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002812 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002813 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002814 }
2815 }
drhbfe66312006-10-03 17:40:40 +00002816 }
drh7ed97b92010-01-20 13:07:21 +00002817
drh6c7d5c52008-11-21 20:32:33 +00002818 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00002819 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002820 return rc;
2821}
2822
2823/*
drh339eb0b2008-03-07 15:34:11 +00002824** Close a file & cleanup AFP specific locking context
2825*/
danielk1977e339d652008-06-28 11:23:00 +00002826static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002827 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002828 if( id ){
2829 unixFile *pFile = (unixFile*)id;
2830 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002831 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002832 if( pFile->pOpen && pFile->pOpen->nLock ){
2833 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002834 ** yet because that would clear those locks. Instead, add the file
2835 ** descriptor to pOpen->aPending. It will be automatically closed when
2836 ** the last lock is cleared.
2837 */
dan08da86a2009-08-21 17:18:03 +00002838 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002839 }
drh7ed97b92010-01-20 13:07:21 +00002840 releaseLockInfo(pFile->pLock);
aswiftaebf4132008-11-21 00:10:35 +00002841 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002842 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002843 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002844 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002845 }
drh7ed97b92010-01-20 13:07:21 +00002846 return rc;
drhbfe66312006-10-03 17:40:40 +00002847}
2848
drhd2cb50b2009-01-09 21:41:17 +00002849#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002850/*
2851** The code above is the AFP lock implementation. The code is specific
2852** to MacOSX and does not work on other unix platforms. No alternative
2853** is available. If you don't compile for a mac, then the "unix-afp"
2854** VFS is not available.
2855**
2856********************* End of the AFP lock implementation **********************
2857******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002858
drh7ed97b92010-01-20 13:07:21 +00002859/******************************************************************************
2860*************************** Begin NFS Locking ********************************/
2861
2862#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2863/*
2864 ** Lower the locking level on file descriptor pFile to locktype. locktype
2865 ** must be either NO_LOCK or SHARED_LOCK.
2866 **
2867 ** If the locking level of the file descriptor is already at or below
2868 ** the requested locking level, this routine is a no-op.
2869 */
2870static int nfsUnlock(sqlite3_file *id, int locktype){
2871 return _posixUnlock(id, locktype, 1);
2872}
2873
2874#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2875/*
2876** The code above is the NFS lock implementation. The code is specific
2877** to MacOSX and does not work on other unix platforms. No alternative
2878** is available.
2879**
2880********************* End of the NFS lock implementation **********************
2881******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002882
2883/******************************************************************************
2884**************** Non-locking sqlite3_file methods *****************************
2885**
2886** The next division contains implementations for all methods of the
2887** sqlite3_file object other than the locking methods. The locking
2888** methods were defined in divisions above (one locking method per
2889** division). Those methods that are common to all locking modes
2890** are gather together into this division.
2891*/
drhbfe66312006-10-03 17:40:40 +00002892
2893/*
drh734c9862008-11-28 15:37:20 +00002894** Seek to the offset passed as the second argument, then read cnt
2895** bytes into pBuf. Return the number of bytes actually read.
2896**
2897** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2898** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2899** one system to another. Since SQLite does not define USE_PREAD
2900** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2901** See tickets #2741 and #2681.
2902**
2903** To avoid stomping the errno value on a failed read the lastErrno value
2904** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002905*/
drh734c9862008-11-28 15:37:20 +00002906static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2907 int got;
drh7ed97b92010-01-20 13:07:21 +00002908#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002909 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002910#endif
drh734c9862008-11-28 15:37:20 +00002911 TIMER_START;
2912#if defined(USE_PREAD)
2913 got = pread(id->h, pBuf, cnt, offset);
2914 SimulateIOError( got = -1 );
2915#elif defined(USE_PREAD64)
2916 got = pread64(id->h, pBuf, cnt, offset);
2917 SimulateIOError( got = -1 );
2918#else
2919 newOffset = lseek(id->h, offset, SEEK_SET);
2920 SimulateIOError( newOffset-- );
2921 if( newOffset!=offset ){
2922 if( newOffset == -1 ){
2923 ((unixFile*)id)->lastErrno = errno;
2924 }else{
2925 ((unixFile*)id)->lastErrno = 0;
2926 }
2927 return -1;
2928 }
2929 got = read(id->h, pBuf, cnt);
2930#endif
2931 TIMER_END;
2932 if( got<0 ){
2933 ((unixFile*)id)->lastErrno = errno;
2934 }
2935 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2936 return got;
drhbfe66312006-10-03 17:40:40 +00002937}
2938
2939/*
drh734c9862008-11-28 15:37:20 +00002940** Read data from a file into a buffer. Return SQLITE_OK if all
2941** bytes were read successfully and SQLITE_IOERR if anything goes
2942** wrong.
drh339eb0b2008-03-07 15:34:11 +00002943*/
drh734c9862008-11-28 15:37:20 +00002944static int unixRead(
2945 sqlite3_file *id,
2946 void *pBuf,
2947 int amt,
2948 sqlite3_int64 offset
2949){
dan08da86a2009-08-21 17:18:03 +00002950 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002951 int got;
2952 assert( id );
drh08c6d442009-02-09 17:34:07 +00002953
dan08da86a2009-08-21 17:18:03 +00002954 /* If this is a database file (not a journal, master-journal or temp
2955 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002956 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002957 || offset>=PENDING_BYTE+512
2958 || offset+amt<=PENDING_BYTE
2959 );
drh08c6d442009-02-09 17:34:07 +00002960
dan08da86a2009-08-21 17:18:03 +00002961 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002962 if( got==amt ){
2963 return SQLITE_OK;
2964 }else if( got<0 ){
2965 /* lastErrno set by seekAndRead */
2966 return SQLITE_IOERR_READ;
2967 }else{
dan08da86a2009-08-21 17:18:03 +00002968 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002969 /* Unread parts of the buffer must be zero-filled */
2970 memset(&((char*)pBuf)[got], 0, amt-got);
2971 return SQLITE_IOERR_SHORT_READ;
2972 }
2973}
2974
2975/*
2976** Seek to the offset in id->offset then read cnt bytes into pBuf.
2977** Return the number of bytes actually read. Update the offset.
2978**
2979** To avoid stomping the errno value on a failed write the lastErrno value
2980** is set before returning.
2981*/
2982static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2983 int got;
drh7ed97b92010-01-20 13:07:21 +00002984#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002985 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002986#endif
drh734c9862008-11-28 15:37:20 +00002987 TIMER_START;
2988#if defined(USE_PREAD)
2989 got = pwrite(id->h, pBuf, cnt, offset);
2990#elif defined(USE_PREAD64)
2991 got = pwrite64(id->h, pBuf, cnt, offset);
2992#else
2993 newOffset = lseek(id->h, offset, SEEK_SET);
2994 if( newOffset!=offset ){
2995 if( newOffset == -1 ){
2996 ((unixFile*)id)->lastErrno = errno;
2997 }else{
2998 ((unixFile*)id)->lastErrno = 0;
2999 }
3000 return -1;
3001 }
3002 got = write(id->h, pBuf, cnt);
3003#endif
3004 TIMER_END;
3005 if( got<0 ){
3006 ((unixFile*)id)->lastErrno = errno;
3007 }
3008
3009 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3010 return got;
3011}
3012
3013
3014/*
3015** Write data from a buffer into a file. Return SQLITE_OK on success
3016** or some other error code on failure.
3017*/
3018static int unixWrite(
3019 sqlite3_file *id,
3020 const void *pBuf,
3021 int amt,
3022 sqlite3_int64 offset
3023){
dan08da86a2009-08-21 17:18:03 +00003024 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003025 int wrote = 0;
3026 assert( id );
3027 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003028
dan08da86a2009-08-21 17:18:03 +00003029 /* If this is a database file (not a journal, master-journal or temp
3030 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00003031 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003032 || offset>=PENDING_BYTE+512
3033 || offset+amt<=PENDING_BYTE
3034 );
drh08c6d442009-02-09 17:34:07 +00003035
drh8f941bc2009-01-14 23:03:40 +00003036#ifndef NDEBUG
3037 /* If we are doing a normal write to a database file (as opposed to
3038 ** doing a hot-journal rollback or a write to some file other than a
3039 ** normal database file) then record the fact that the database
3040 ** has changed. If the transaction counter is modified, record that
3041 ** fact too.
3042 */
dan08da86a2009-08-21 17:18:03 +00003043 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003044 pFile->dbUpdate = 1; /* The database has been modified */
3045 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003046 int rc;
drh8f941bc2009-01-14 23:03:40 +00003047 char oldCntr[4];
3048 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003049 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003050 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003051 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003052 pFile->transCntrChng = 1; /* The transaction counter has changed */
3053 }
3054 }
3055 }
3056#endif
3057
dan08da86a2009-08-21 17:18:03 +00003058 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003059 amt -= wrote;
3060 offset += wrote;
3061 pBuf = &((char*)pBuf)[wrote];
3062 }
3063 SimulateIOError(( wrote=(-1), amt=1 ));
3064 SimulateDiskfullError(( wrote=0, amt=1 ));
3065 if( amt>0 ){
3066 if( wrote<0 ){
3067 /* lastErrno set by seekAndWrite */
3068 return SQLITE_IOERR_WRITE;
3069 }else{
dan08da86a2009-08-21 17:18:03 +00003070 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003071 return SQLITE_FULL;
3072 }
3073 }
3074 return SQLITE_OK;
3075}
3076
3077#ifdef SQLITE_TEST
3078/*
3079** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003080** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003081*/
3082int sqlite3_sync_count = 0;
3083int sqlite3_fullsync_count = 0;
3084#endif
3085
3086/*
drh89240432009-03-25 01:06:01 +00003087** We do not trust systems to provide a working fdatasync(). Some do.
3088** Others do no. To be safe, we will stick with the (slower) fsync().
3089** If you know that your system does support fdatasync() correctly,
3090** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003091*/
drh89240432009-03-25 01:06:01 +00003092#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003093# define fdatasync fsync
3094#endif
3095
3096/*
3097** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3098** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3099** only available on Mac OS X. But that could change.
3100*/
3101#ifdef F_FULLFSYNC
3102# define HAVE_FULLFSYNC 1
3103#else
3104# define HAVE_FULLFSYNC 0
3105#endif
3106
3107
3108/*
3109** The fsync() system call does not work as advertised on many
3110** unix systems. The following procedure is an attempt to make
3111** it work better.
3112**
3113** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3114** for testing when we want to run through the test suite quickly.
3115** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3116** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3117** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003118**
3119** SQLite sets the dataOnly flag if the size of the file is unchanged.
3120** The idea behind dataOnly is that it should only write the file content
3121** to disk, not the inode. We only set dataOnly if the file size is
3122** unchanged since the file size is part of the inode. However,
3123** Ted Ts'o tells us that fdatasync() will also write the inode if the
3124** file size has changed. The only real difference between fdatasync()
3125** and fsync(), Ted tells us, is that fdatasync() will not flush the
3126** inode if the mtime or owner or other inode attributes have changed.
3127** We only care about the file size, not the other file attributes, so
3128** as far as SQLite is concerned, an fdatasync() is always adequate.
3129** So, we always use fdatasync() if it is available, regardless of
3130** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003131*/
3132static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003133 int rc;
drh734c9862008-11-28 15:37:20 +00003134
3135 /* The following "ifdef/elif/else/" block has the same structure as
3136 ** the one below. It is replicated here solely to avoid cluttering
3137 ** up the real code with the UNUSED_PARAMETER() macros.
3138 */
3139#ifdef SQLITE_NO_SYNC
3140 UNUSED_PARAMETER(fd);
3141 UNUSED_PARAMETER(fullSync);
3142 UNUSED_PARAMETER(dataOnly);
3143#elif HAVE_FULLFSYNC
3144 UNUSED_PARAMETER(dataOnly);
3145#else
3146 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003147 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003148#endif
3149
3150 /* Record the number of times that we do a normal fsync() and
3151 ** FULLSYNC. This is used during testing to verify that this procedure
3152 ** gets called with the correct arguments.
3153 */
3154#ifdef SQLITE_TEST
3155 if( fullSync ) sqlite3_fullsync_count++;
3156 sqlite3_sync_count++;
3157#endif
3158
3159 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3160 ** no-op
3161 */
3162#ifdef SQLITE_NO_SYNC
3163 rc = SQLITE_OK;
3164#elif HAVE_FULLFSYNC
3165 if( fullSync ){
3166 rc = fcntl(fd, F_FULLFSYNC, 0);
3167 }else{
3168 rc = 1;
3169 }
3170 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003171 ** It shouldn't be possible for fullfsync to fail on the local
3172 ** file system (on OSX), so failure indicates that FULLFSYNC
3173 ** isn't supported for this file system. So, attempt an fsync
3174 ** and (for now) ignore the overhead of a superfluous fcntl call.
3175 ** It'd be better to detect fullfsync support once and avoid
3176 ** the fcntl call every time sync is called.
3177 */
drh734c9862008-11-28 15:37:20 +00003178 if( rc ) rc = fsync(fd);
3179
drh7ed97b92010-01-20 13:07:21 +00003180#elif defined(__APPLE__)
3181 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3182 ** so currently we default to the macro that redefines fdatasync to fsync
3183 */
3184 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003185#else
drh0b647ff2009-03-21 14:41:04 +00003186 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003187#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003188 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003189 rc = fsync(fd);
3190 }
drh0b647ff2009-03-21 14:41:04 +00003191#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003192#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3193
3194 if( OS_VXWORKS && rc!= -1 ){
3195 rc = 0;
3196 }
chw97185482008-11-17 08:05:31 +00003197 return rc;
drhbfe66312006-10-03 17:40:40 +00003198}
3199
drh734c9862008-11-28 15:37:20 +00003200/*
3201** Make sure all writes to a particular file are committed to disk.
3202**
3203** If dataOnly==0 then both the file itself and its metadata (file
3204** size, access time, etc) are synced. If dataOnly!=0 then only the
3205** file data is synced.
3206**
3207** Under Unix, also make sure that the directory entry for the file
3208** has been created by fsync-ing the directory that contains the file.
3209** If we do not do this and we encounter a power failure, the directory
3210** entry for the journal might not exist after we reboot. The next
3211** SQLite to access the file will not know that the journal exists (because
3212** the directory entry for the journal was never created) and the transaction
3213** will not roll back - possibly leading to database corruption.
3214*/
3215static int unixSync(sqlite3_file *id, int flags){
3216 int rc;
3217 unixFile *pFile = (unixFile*)id;
3218
3219 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3220 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3221
3222 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3223 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3224 || (flags&0x0F)==SQLITE_SYNC_FULL
3225 );
3226
3227 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3228 ** line is to test that doing so does not cause any problems.
3229 */
3230 SimulateDiskfullError( return SQLITE_FULL );
3231
3232 assert( pFile );
3233 OSTRACE2("SYNC %-3d\n", pFile->h);
3234 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3235 SimulateIOError( rc=1 );
3236 if( rc ){
3237 pFile->lastErrno = errno;
3238 return SQLITE_IOERR_FSYNC;
3239 }
3240 if( pFile->dirfd>=0 ){
3241 int err;
3242 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3243 HAVE_FULLFSYNC, isFullsync);
3244#ifndef SQLITE_DISABLE_DIRSYNC
3245 /* The directory sync is only attempted if full_fsync is
3246 ** turned off or unavailable. If a full_fsync occurred above,
3247 ** then the directory sync is superfluous.
3248 */
3249 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3250 /*
3251 ** We have received multiple reports of fsync() returning
3252 ** errors when applied to directories on certain file systems.
3253 ** A failed directory sync is not a big deal. So it seems
3254 ** better to ignore the error. Ticket #1657
3255 */
3256 /* pFile->lastErrno = errno; */
3257 /* return SQLITE_IOERR; */
3258 }
3259#endif
3260 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3261 if( err==0 ){ /* directory when we are done */
3262 pFile->dirfd = -1;
3263 }else{
3264 pFile->lastErrno = errno;
3265 rc = SQLITE_IOERR_DIR_CLOSE;
3266 }
3267 }
3268 return rc;
3269}
3270
3271/*
3272** Truncate an open file to a specified size
3273*/
3274static int unixTruncate(sqlite3_file *id, i64 nByte){
3275 int rc;
3276 assert( id );
3277 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3278 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3279 if( rc ){
3280 ((unixFile*)id)->lastErrno = errno;
3281 return SQLITE_IOERR_TRUNCATE;
3282 }else{
drh3313b142009-11-06 04:13:18 +00003283#ifndef NDEBUG
3284 /* If we are doing a normal write to a database file (as opposed to
3285 ** doing a hot-journal rollback or a write to some file other than a
3286 ** normal database file) and we truncate the file to zero length,
3287 ** that effectively updates the change counter. This might happen
3288 ** when restoring a database using the backup API from a zero-length
3289 ** source.
3290 */
3291 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3292 ((unixFile*)id)->transCntrChng = 1;
3293 }
3294#endif
3295
drh734c9862008-11-28 15:37:20 +00003296 return SQLITE_OK;
3297 }
3298}
3299
3300/*
3301** Determine the current size of a file in bytes
3302*/
3303static int unixFileSize(sqlite3_file *id, i64 *pSize){
3304 int rc;
3305 struct stat buf;
3306 assert( id );
3307 rc = fstat(((unixFile*)id)->h, &buf);
3308 SimulateIOError( rc=1 );
3309 if( rc!=0 ){
3310 ((unixFile*)id)->lastErrno = errno;
3311 return SQLITE_IOERR_FSTAT;
3312 }
3313 *pSize = buf.st_size;
3314
3315 /* When opening a zero-size database, the findLockInfo() procedure
3316 ** writes a single byte into that file in order to work around a bug
3317 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3318 ** layers, we need to report this file size as zero even though it is
3319 ** really 1. Ticket #3260.
3320 */
3321 if( *pSize==1 ) *pSize = 0;
3322
3323
3324 return SQLITE_OK;
3325}
3326
drhd2cb50b2009-01-09 21:41:17 +00003327#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003328/*
3329** Handler for proxy-locking file-control verbs. Defined below in the
3330** proxying locking division.
3331*/
3332static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003333#endif
drh715ff302008-12-03 22:32:44 +00003334
danielk1977ad94b582007-08-20 06:44:22 +00003335
danielk1977e3026632004-06-22 11:29:02 +00003336/*
drh9e33c2c2007-08-31 18:34:59 +00003337** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003338*/
drhcc6bb3e2007-08-31 16:11:35 +00003339static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003340 switch( op ){
3341 case SQLITE_FCNTL_LOCKSTATE: {
3342 *(int*)pArg = ((unixFile*)id)->locktype;
3343 return SQLITE_OK;
3344 }
drh7708e972008-11-29 00:56:52 +00003345 case SQLITE_LAST_ERRNO: {
3346 *(int*)pArg = ((unixFile*)id)->lastErrno;
3347 return SQLITE_OK;
3348 }
drh8f941bc2009-01-14 23:03:40 +00003349#ifndef NDEBUG
3350 /* The pager calls this method to signal that it has done
3351 ** a rollback and that the database is therefore unchanged and
3352 ** it hence it is OK for the transaction change counter to be
3353 ** unchanged.
3354 */
3355 case SQLITE_FCNTL_DB_UNCHANGED: {
3356 ((unixFile*)id)->dbUpdate = 0;
3357 return SQLITE_OK;
3358 }
3359#endif
drhd2cb50b2009-01-09 21:41:17 +00003360#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003361 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003362 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003363 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003364 }
drhd2cb50b2009-01-09 21:41:17 +00003365#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003366 }
drhcc6bb3e2007-08-31 16:11:35 +00003367 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003368}
3369
3370/*
danielk1977a3d4c882007-03-23 10:08:38 +00003371** Return the sector size in bytes of the underlying block device for
3372** the specified file. This is almost always 512 bytes, but may be
3373** larger for some devices.
3374**
3375** SQLite code assumes this function cannot fail. It also assumes that
3376** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003377** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003378** same for both.
3379*/
danielk1977397d65f2008-11-19 11:35:39 +00003380static int unixSectorSize(sqlite3_file *NotUsed){
3381 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003382 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003383}
3384
danielk197790949c22007-08-17 16:50:38 +00003385/*
danielk1977397d65f2008-11-19 11:35:39 +00003386** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003387*/
danielk1977397d65f2008-11-19 11:35:39 +00003388static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3389 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003390 return 0;
3391}
3392
drh734c9862008-11-28 15:37:20 +00003393/*
3394** Here ends the implementation of all sqlite3_file methods.
3395**
3396********************** End sqlite3_file Methods *******************************
3397******************************************************************************/
3398
3399/*
drh6b9d6dd2008-12-03 19:34:47 +00003400** This division contains definitions of sqlite3_io_methods objects that
3401** implement various file locking strategies. It also contains definitions
3402** of "finder" functions. A finder-function is used to locate the appropriate
3403** sqlite3_io_methods object for a particular database file. The pAppData
3404** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3405** the correct finder-function for that VFS.
3406**
3407** Most finder functions return a pointer to a fixed sqlite3_io_methods
3408** object. The only interesting finder-function is autolockIoFinder, which
3409** looks at the filesystem type and tries to guess the best locking
3410** strategy from that.
3411**
drh1875f7a2008-12-08 18:19:17 +00003412** For finder-funtion F, two objects are created:
3413**
3414** (1) The real finder-function named "FImpt()".
3415**
dane946c392009-08-22 11:39:46 +00003416** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003417**
3418**
3419** A pointer to the F pointer is used as the pAppData value for VFS
3420** objects. We have to do this instead of letting pAppData point
3421** directly at the finder-function since C90 rules prevent a void*
3422** from be cast into a function pointer.
3423**
drh6b9d6dd2008-12-03 19:34:47 +00003424**
drh7708e972008-11-29 00:56:52 +00003425** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003426**
drh7708e972008-11-29 00:56:52 +00003427** * A constant sqlite3_io_methods object call METHOD that has locking
3428** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3429**
3430** * An I/O method finder function called FINDER that returns a pointer
3431** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003432*/
drh7708e972008-11-29 00:56:52 +00003433#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3434static const sqlite3_io_methods METHOD = { \
3435 1, /* iVersion */ \
3436 CLOSE, /* xClose */ \
3437 unixRead, /* xRead */ \
3438 unixWrite, /* xWrite */ \
3439 unixTruncate, /* xTruncate */ \
3440 unixSync, /* xSync */ \
3441 unixFileSize, /* xFileSize */ \
3442 LOCK, /* xLock */ \
3443 UNLOCK, /* xUnlock */ \
3444 CKLOCK, /* xCheckReservedLock */ \
3445 unixFileControl, /* xFileControl */ \
3446 unixSectorSize, /* xSectorSize */ \
3447 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3448}; \
drh0c2694b2009-09-03 16:23:44 +00003449static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3450 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003451 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003452} \
drh0c2694b2009-09-03 16:23:44 +00003453static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003454 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003455
3456/*
3457** Here are all of the sqlite3_io_methods objects for each of the
3458** locking strategies. Functions that return pointers to these methods
3459** are also created.
3460*/
3461IOMETHODS(
3462 posixIoFinder, /* Finder function name */
3463 posixIoMethods, /* sqlite3_io_methods object name */
3464 unixClose, /* xClose method */
3465 unixLock, /* xLock method */
3466 unixUnlock, /* xUnlock method */
3467 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003468)
drh7708e972008-11-29 00:56:52 +00003469IOMETHODS(
3470 nolockIoFinder, /* Finder function name */
3471 nolockIoMethods, /* sqlite3_io_methods object name */
3472 nolockClose, /* xClose method */
3473 nolockLock, /* xLock method */
3474 nolockUnlock, /* xUnlock method */
3475 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003476)
drh7708e972008-11-29 00:56:52 +00003477IOMETHODS(
3478 dotlockIoFinder, /* Finder function name */
3479 dotlockIoMethods, /* sqlite3_io_methods object name */
3480 dotlockClose, /* xClose method */
3481 dotlockLock, /* xLock method */
3482 dotlockUnlock, /* xUnlock method */
3483 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003484)
drh7708e972008-11-29 00:56:52 +00003485
chw78a13182009-04-07 05:35:03 +00003486#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003487IOMETHODS(
3488 flockIoFinder, /* Finder function name */
3489 flockIoMethods, /* sqlite3_io_methods object name */
3490 flockClose, /* xClose method */
3491 flockLock, /* xLock method */
3492 flockUnlock, /* xUnlock method */
3493 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003494)
drh7708e972008-11-29 00:56:52 +00003495#endif
3496
drh6c7d5c52008-11-21 20:32:33 +00003497#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003498IOMETHODS(
3499 semIoFinder, /* Finder function name */
3500 semIoMethods, /* sqlite3_io_methods object name */
3501 semClose, /* xClose method */
3502 semLock, /* xLock method */
3503 semUnlock, /* xUnlock method */
3504 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003505)
aswiftaebf4132008-11-21 00:10:35 +00003506#endif
drh7708e972008-11-29 00:56:52 +00003507
drhd2cb50b2009-01-09 21:41:17 +00003508#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003509IOMETHODS(
3510 afpIoFinder, /* Finder function name */
3511 afpIoMethods, /* sqlite3_io_methods object name */
3512 afpClose, /* xClose method */
3513 afpLock, /* xLock method */
3514 afpUnlock, /* xUnlock method */
3515 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003516)
drh715ff302008-12-03 22:32:44 +00003517#endif
3518
3519/*
3520** The proxy locking method is a "super-method" in the sense that it
3521** opens secondary file descriptors for the conch and lock files and
3522** it uses proxy, dot-file, AFP, and flock() locking methods on those
3523** secondary files. For this reason, the division that implements
3524** proxy locking is located much further down in the file. But we need
3525** to go ahead and define the sqlite3_io_methods and finder function
3526** for proxy locking here. So we forward declare the I/O methods.
3527*/
drhd2cb50b2009-01-09 21:41:17 +00003528#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003529static int proxyClose(sqlite3_file*);
3530static int proxyLock(sqlite3_file*, int);
3531static int proxyUnlock(sqlite3_file*, int);
3532static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003533IOMETHODS(
3534 proxyIoFinder, /* Finder function name */
3535 proxyIoMethods, /* sqlite3_io_methods object name */
3536 proxyClose, /* xClose method */
3537 proxyLock, /* xLock method */
3538 proxyUnlock, /* xUnlock method */
3539 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003540)
aswiftaebf4132008-11-21 00:10:35 +00003541#endif
drh7708e972008-11-29 00:56:52 +00003542
drh7ed97b92010-01-20 13:07:21 +00003543/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3544#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3545IOMETHODS(
3546 nfsIoFinder, /* Finder function name */
3547 nfsIoMethods, /* sqlite3_io_methods object name */
3548 unixClose, /* xClose method */
3549 unixLock, /* xLock method */
3550 nfsUnlock, /* xUnlock method */
3551 unixCheckReservedLock /* xCheckReservedLock method */
3552)
3553#endif
drh7708e972008-11-29 00:56:52 +00003554
drhd2cb50b2009-01-09 21:41:17 +00003555#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003556/*
drh6b9d6dd2008-12-03 19:34:47 +00003557** This "finder" function attempts to determine the best locking strategy
3558** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003559** object that implements that strategy.
3560**
3561** This is for MacOSX only.
3562*/
drh1875f7a2008-12-08 18:19:17 +00003563static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003564 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003565 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003566){
3567 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003568 const char *zFilesystem; /* Filesystem type name */
3569 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003570 } aMap[] = {
3571 { "hfs", &posixIoMethods },
3572 { "ufs", &posixIoMethods },
3573 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003574 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00003575 { "webdav", &nolockIoMethods },
3576 { 0, 0 }
3577 };
3578 int i;
3579 struct statfs fsInfo;
3580 struct flock lockInfo;
3581
3582 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003583 /* If filePath==NULL that means we are dealing with a transient file
3584 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003585 return &nolockIoMethods;
3586 }
3587 if( statfs(filePath, &fsInfo) != -1 ){
3588 if( fsInfo.f_flags & MNT_RDONLY ){
3589 return &nolockIoMethods;
3590 }
3591 for(i=0; aMap[i].zFilesystem; i++){
3592 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3593 return aMap[i].pMethods;
3594 }
3595 }
3596 }
3597
3598 /* Default case. Handles, amongst others, "nfs".
3599 ** Test byte-range lock using fcntl(). If the call succeeds,
3600 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003601 */
drh7708e972008-11-29 00:56:52 +00003602 lockInfo.l_len = 1;
3603 lockInfo.l_start = 0;
3604 lockInfo.l_whence = SEEK_SET;
3605 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003606 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00003607 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3608 return &nfsIoMethods;
3609 } else {
3610 return &posixIoMethods;
3611 }
drh7708e972008-11-29 00:56:52 +00003612 }else{
3613 return &dotlockIoMethods;
3614 }
3615}
drh0c2694b2009-09-03 16:23:44 +00003616static const sqlite3_io_methods
3617 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003618
drhd2cb50b2009-01-09 21:41:17 +00003619#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003620
chw78a13182009-04-07 05:35:03 +00003621#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3622/*
3623** This "finder" function attempts to determine the best locking strategy
3624** for the database file "filePath". It then returns the sqlite3_io_methods
3625** object that implements that strategy.
3626**
3627** This is for VXWorks only.
3628*/
3629static const sqlite3_io_methods *autolockIoFinderImpl(
3630 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003631 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003632){
3633 struct flock lockInfo;
3634
3635 if( !filePath ){
3636 /* If filePath==NULL that means we are dealing with a transient file
3637 ** that does not need to be locked. */
3638 return &nolockIoMethods;
3639 }
3640
3641 /* Test if fcntl() is supported and use POSIX style locks.
3642 ** Otherwise fall back to the named semaphore method.
3643 */
3644 lockInfo.l_len = 1;
3645 lockInfo.l_start = 0;
3646 lockInfo.l_whence = SEEK_SET;
3647 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003648 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003649 return &posixIoMethods;
3650 }else{
3651 return &semIoMethods;
3652 }
3653}
drh0c2694b2009-09-03 16:23:44 +00003654static const sqlite3_io_methods
3655 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003656
3657#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3658
drh7708e972008-11-29 00:56:52 +00003659/*
3660** An abstract type for a pointer to a IO method finder function:
3661*/
drh0c2694b2009-09-03 16:23:44 +00003662typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003663
aswiftaebf4132008-11-21 00:10:35 +00003664
drh734c9862008-11-28 15:37:20 +00003665/****************************************************************************
3666**************************** sqlite3_vfs methods ****************************
3667**
3668** This division contains the implementation of methods on the
3669** sqlite3_vfs object.
3670*/
3671
danielk1977a3d4c882007-03-23 10:08:38 +00003672/*
danielk1977e339d652008-06-28 11:23:00 +00003673** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003674*/
3675static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003676 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003677 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003678 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003679 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003680 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003681 int noLock, /* Omit locking if true */
3682 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003683){
drh7708e972008-11-29 00:56:52 +00003684 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003685 unixFile *pNew = (unixFile *)pId;
3686 int rc = SQLITE_OK;
3687
danielk197717b90b52008-06-06 11:11:25 +00003688 assert( pNew->pLock==NULL );
3689 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003690
dane946c392009-08-22 11:39:46 +00003691 /* Parameter isDelete is only used on vxworks. Express this explicitly
3692 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003693 */
drh7708e972008-11-29 00:56:52 +00003694 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003695
drh218c5082008-03-07 00:27:10 +00003696 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003697 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003698 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003699 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00003700 pNew->fileFlags = 0;
drh339eb0b2008-03-07 15:34:11 +00003701
drh6c7d5c52008-11-21 20:32:33 +00003702#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003703 pNew->pId = vxworksFindFileId(zFilename);
3704 if( pNew->pId==0 ){
3705 noLock = 1;
3706 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003707 }
3708#endif
3709
drhda0e7682008-07-30 15:27:54 +00003710 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003711 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003712 }else{
drh0c2694b2009-09-03 16:23:44 +00003713 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003714#if SQLITE_ENABLE_LOCKING_STYLE
3715 /* Cache zFilename in the locking context (AFP and dotlock override) for
3716 ** proxyLock activation is possible (remote proxy is based on db name)
3717 ** zFilename remains valid until file is closed, to support */
3718 pNew->lockingContext = (void*)zFilename;
3719#endif
drhda0e7682008-07-30 15:27:54 +00003720 }
danielk1977e339d652008-06-28 11:23:00 +00003721
drh7ed97b92010-01-20 13:07:21 +00003722 if( pLockingStyle == &posixIoMethods
3723#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3724 || pLockingStyle == &nfsIoMethods
3725#endif
3726 ){
drh7708e972008-11-29 00:56:52 +00003727 unixEnterMutex();
3728 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003729 if( rc!=SQLITE_OK ){
3730 /* If an error occured in findLockInfo(), close the file descriptor
3731 ** immediately, before releasing the mutex. findLockInfo() may fail
3732 ** in two scenarios:
3733 **
3734 ** (a) A call to fstat() failed.
3735 ** (b) A malloc failed.
3736 **
3737 ** Scenario (b) may only occur if the process is holding no other
3738 ** file descriptors open on the same file. If there were other file
3739 ** descriptors on this file, then no malloc would be required by
3740 ** findLockInfo(). If this is the case, it is quite safe to close
3741 ** handle h - as it is guaranteed that no posix locks will be released
3742 ** by doing so.
3743 **
3744 ** If scenario (a) caused the error then things are not so safe. The
3745 ** implicit assumption here is that if fstat() fails, things are in
3746 ** such bad shape that dropping a lock or two doesn't matter much.
3747 */
3748 close(h);
3749 h = -1;
3750 }
drh7708e972008-11-29 00:56:52 +00003751 unixLeaveMutex();
3752 }
danielk1977e339d652008-06-28 11:23:00 +00003753
drhd2cb50b2009-01-09 21:41:17 +00003754#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003755 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003756 /* AFP locking uses the file path so it needs to be included in
3757 ** the afpLockingContext.
3758 */
3759 afpLockingContext *pCtx;
3760 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3761 if( pCtx==0 ){
3762 rc = SQLITE_NOMEM;
3763 }else{
3764 /* NB: zFilename exists and remains valid until the file is closed
3765 ** according to requirement F11141. So we do not need to make a
3766 ** copy of the filename. */
3767 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00003768 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00003769 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003770 unixEnterMutex();
drh7ed97b92010-01-20 13:07:21 +00003771 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3772 if( rc!=SQLITE_OK ){
3773 sqlite3_free(pNew->lockingContext);
3774 close(h);
3775 h = -1;
3776 }
drh7708e972008-11-29 00:56:52 +00003777 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003778 }
drh7708e972008-11-29 00:56:52 +00003779 }
3780#endif
danielk1977e339d652008-06-28 11:23:00 +00003781
drh7708e972008-11-29 00:56:52 +00003782 else if( pLockingStyle == &dotlockIoMethods ){
3783 /* Dotfile locking uses the file path so it needs to be included in
3784 ** the dotlockLockingContext
3785 */
3786 char *zLockFile;
3787 int nFilename;
drhea678832008-12-10 19:26:22 +00003788 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003789 zLockFile = (char *)sqlite3_malloc(nFilename);
3790 if( zLockFile==0 ){
3791 rc = SQLITE_NOMEM;
3792 }else{
3793 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003794 }
drh7708e972008-11-29 00:56:52 +00003795 pNew->lockingContext = zLockFile;
3796 }
danielk1977e339d652008-06-28 11:23:00 +00003797
drh6c7d5c52008-11-21 20:32:33 +00003798#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003799 else if( pLockingStyle == &semIoMethods ){
3800 /* Named semaphore locking uses the file path so it needs to be
3801 ** included in the semLockingContext
3802 */
3803 unixEnterMutex();
3804 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3805 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3806 char *zSemName = pNew->pOpen->aSemName;
3807 int n;
drh2238dcc2009-08-27 17:56:20 +00003808 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003809 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003810 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003811 if( zSemName[n]=='/' ) zSemName[n] = '_';
3812 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3813 if( pNew->pOpen->pSem == SEM_FAILED ){
3814 rc = SQLITE_NOMEM;
3815 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003816 }
chw97185482008-11-17 08:05:31 +00003817 }
drh7708e972008-11-29 00:56:52 +00003818 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003819 }
drh7708e972008-11-29 00:56:52 +00003820#endif
aswift5b1a2562008-08-22 00:22:35 +00003821
3822 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003823#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003824 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00003825 if( h>=0 ) close(h);
3826 h = -1;
chw97185482008-11-17 08:05:31 +00003827 unlink(zFilename);
3828 isDelete = 0;
3829 }
3830 pNew->isDelete = isDelete;
3831#endif
danielk1977e339d652008-06-28 11:23:00 +00003832 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003833 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003834 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003835 }else{
drh7708e972008-11-29 00:56:52 +00003836 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003837 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003838 }
danielk1977e339d652008-06-28 11:23:00 +00003839 return rc;
drh054889e2005-11-30 03:20:31 +00003840}
drh9c06c952005-11-26 00:25:00 +00003841
danielk1977ad94b582007-08-20 06:44:22 +00003842/*
3843** Open a file descriptor to the directory containing file zFilename.
3844** If successful, *pFd is set to the opened file descriptor and
3845** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3846** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3847** value.
3848**
3849** If SQLITE_OK is returned, the caller is responsible for closing
3850** the file descriptor *pFd using close().
3851*/
danielk1977fee2d252007-08-18 10:59:19 +00003852static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003853 int ii;
drh777b17a2007-09-20 10:02:54 +00003854 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003855 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003856
drh153c62c2007-08-24 03:51:33 +00003857 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003858 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003859 if( ii>0 ){
3860 zDirname[ii] = '\0';
3861 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003862 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003863#ifdef FD_CLOEXEC
3864 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3865#endif
3866 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3867 }
3868 }
danielk1977fee2d252007-08-18 10:59:19 +00003869 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003870 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003871}
3872
danielk1977b4b47412007-08-17 15:53:36 +00003873/*
danielk197717b90b52008-06-06 11:11:25 +00003874** Create a temporary file name in zBuf. zBuf must be allocated
3875** by the calling process and must be big enough to hold at least
3876** pVfs->mxPathname bytes.
3877*/
3878static int getTempname(int nBuf, char *zBuf){
3879 static const char *azDirs[] = {
3880 0,
aswiftaebf4132008-11-21 00:10:35 +00003881 0,
danielk197717b90b52008-06-06 11:11:25 +00003882 "/var/tmp",
3883 "/usr/tmp",
3884 "/tmp",
3885 ".",
3886 };
3887 static const unsigned char zChars[] =
3888 "abcdefghijklmnopqrstuvwxyz"
3889 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3890 "0123456789";
drh41022642008-11-21 00:24:42 +00003891 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003892 struct stat buf;
3893 const char *zDir = ".";
3894
3895 /* It's odd to simulate an io-error here, but really this is just
3896 ** using the io-error infrastructure to test that SQLite handles this
3897 ** function failing.
3898 */
3899 SimulateIOError( return SQLITE_IOERR );
3900
3901 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003902 if (NULL == azDirs[1]) {
3903 azDirs[1] = getenv("TMPDIR");
3904 }
3905
3906 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003907 if( azDirs[i]==0 ) continue;
3908 if( stat(azDirs[i], &buf) ) continue;
3909 if( !S_ISDIR(buf.st_mode) ) continue;
3910 if( access(azDirs[i], 07) ) continue;
3911 zDir = azDirs[i];
3912 break;
3913 }
3914
3915 /* Check that the output buffer is large enough for the temporary file
3916 ** name. If it is not, return SQLITE_ERROR.
3917 */
danielk197700e13612008-11-17 19:18:54 +00003918 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003919 return SQLITE_ERROR;
3920 }
3921
3922 do{
3923 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003924 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003925 sqlite3_randomness(15, &zBuf[j]);
3926 for(i=0; i<15; i++, j++){
3927 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3928 }
3929 zBuf[j] = 0;
3930 }while( access(zBuf,0)==0 );
3931 return SQLITE_OK;
3932}
3933
drhd2cb50b2009-01-09 21:41:17 +00003934#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003935/*
3936** Routine to transform a unixFile into a proxy-locking unixFile.
3937** Implementation in the proxy-lock division, but used by unixOpen()
3938** if SQLITE_PREFER_PROXY_LOCKING is defined.
3939*/
3940static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003941#endif
drhc66d5b62008-12-03 22:48:32 +00003942
dan08da86a2009-08-21 17:18:03 +00003943/*
3944** Search for an unused file descriptor that was opened on the database
3945** file (not a journal or master-journal file) identified by pathname
3946** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3947** argument to this function.
3948**
3949** Such a file descriptor may exist if a database connection was closed
3950** but the associated file descriptor could not be closed because some
3951** other file descriptor open on the same file is holding a file-lock.
3952** Refer to comments in the unixClose() function and the lengthy comment
3953** describing "Posix Advisory Locking" at the start of this file for
3954** further details. Also, ticket #4018.
3955**
3956** If a suitable file descriptor is found, then it is returned. If no
3957** such file descriptor is located, -1 is returned.
3958*/
dane946c392009-08-22 11:39:46 +00003959static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3960 UnixUnusedFd *pUnused = 0;
3961
3962 /* Do not search for an unused file descriptor on vxworks. Not because
3963 ** vxworks would not benefit from the change (it might, we're not sure),
3964 ** but because no way to test it is currently available. It is better
3965 ** not to risk breaking vxworks support for the sake of such an obscure
3966 ** feature. */
3967#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003968 struct stat sStat; /* Results of stat() call */
3969
3970 /* A stat() call may fail for various reasons. If this happens, it is
3971 ** almost certain that an open() call on the same path will also fail.
3972 ** For this reason, if an error occurs in the stat() call here, it is
3973 ** ignored and -1 is returned. The caller will try to open a new file
3974 ** descriptor on the same path, fail, and return an error to SQLite.
3975 **
3976 ** Even if a subsequent open() call does succeed, the consequences of
3977 ** not searching for a resusable file descriptor are not dire. */
3978 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00003979 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00003980
3981 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00003982 pOpen = openList;
3983 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
3984 || pOpen->fileId.ino!=sStat.st_ino) ){
3985 pOpen = pOpen->pNext;
3986 }
3987 if( pOpen ){
dane946c392009-08-22 11:39:46 +00003988 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00003989 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00003990 pUnused = *pp;
3991 if( pUnused ){
3992 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00003993 }
3994 }
3995 unixLeaveMutex();
3996 }
dane946c392009-08-22 11:39:46 +00003997#endif /* if !OS_VXWORKS */
3998 return pUnused;
dan08da86a2009-08-21 17:18:03 +00003999}
danielk197717b90b52008-06-06 11:11:25 +00004000
4001/*
danielk1977ad94b582007-08-20 06:44:22 +00004002** Open the file zPath.
4003**
danielk1977b4b47412007-08-17 15:53:36 +00004004** Previously, the SQLite OS layer used three functions in place of this
4005** one:
4006**
4007** sqlite3OsOpenReadWrite();
4008** sqlite3OsOpenReadOnly();
4009** sqlite3OsOpenExclusive();
4010**
4011** These calls correspond to the following combinations of flags:
4012**
4013** ReadWrite() -> (READWRITE | CREATE)
4014** ReadOnly() -> (READONLY)
4015** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4016**
4017** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4018** true, the file was configured to be automatically deleted when the
4019** file handle closed. To achieve the same effect using this new
4020** interface, add the DELETEONCLOSE flag to those specified above for
4021** OpenExclusive().
4022*/
4023static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004024 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4025 const char *zPath, /* Pathname of file to be opened */
4026 sqlite3_file *pFile, /* The file descriptor to be filled in */
4027 int flags, /* Input flags to control the opening */
4028 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004029){
dan08da86a2009-08-21 17:18:03 +00004030 unixFile *p = (unixFile *)pFile;
4031 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004032 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004033 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004034 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004035 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004036 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004037
4038 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4039 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4040 int isCreate = (flags & SQLITE_OPEN_CREATE);
4041 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4042 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004043#if SQLITE_ENABLE_LOCKING_STYLE
4044 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4045#endif
danielk1977b4b47412007-08-17 15:53:36 +00004046
danielk1977fee2d252007-08-18 10:59:19 +00004047 /* If creating a master or main-file journal, this function will open
4048 ** a file-descriptor on the directory too. The first time unixSync()
4049 ** is called the directory file descriptor will be fsync()ed and close()d.
4050 */
4051 int isOpenDirectory = (isCreate &&
4052 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4053 );
4054
danielk197717b90b52008-06-06 11:11:25 +00004055 /* If argument zPath is a NULL pointer, this function is required to open
4056 ** a temporary file. Use this buffer to store the file name in.
4057 */
4058 char zTmpname[MAX_PATHNAME+1];
4059 const char *zName = zPath;
4060
danielk1977fee2d252007-08-18 10:59:19 +00004061 /* Check the following statements are true:
4062 **
4063 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4064 ** (b) if CREATE is set, then READWRITE must also be set, and
4065 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004066 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004067 */
danielk1977b4b47412007-08-17 15:53:36 +00004068 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004069 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004070 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004071 assert(isDelete==0 || isCreate);
4072
drh33f4e022007-09-03 15:19:34 +00004073 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004074 ** deleted. Nor are they ever temporary files. */
4075 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4076 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4077 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004078
danielk1977fee2d252007-08-18 10:59:19 +00004079 /* Assert that the upper layer has set one of the "file-type" flags. */
4080 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4081 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4082 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004083 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004084 );
4085
dan08da86a2009-08-21 17:18:03 +00004086 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004087
dan08da86a2009-08-21 17:18:03 +00004088 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004089 UnixUnusedFd *pUnused;
4090 pUnused = findReusableFd(zName, flags);
4091 if( pUnused ){
4092 fd = pUnused->fd;
4093 }else{
dan6aa657f2009-08-24 18:57:58 +00004094 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004095 if( !pUnused ){
4096 return SQLITE_NOMEM;
4097 }
4098 }
4099 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004100 }else if( !zName ){
4101 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004102 assert(isDelete && !isOpenDirectory);
4103 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4104 if( rc!=SQLITE_OK ){
4105 return rc;
4106 }
4107 zName = zTmpname;
4108 }
4109
dan08da86a2009-08-21 17:18:03 +00004110 /* Determine the value of the flags parameter passed to POSIX function
4111 ** open(). These must be calculated even if open() is not called, as
4112 ** they may be stored as part of the file handle and used by the
4113 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004114 if( isReadonly ) openFlags |= O_RDONLY;
4115 if( isReadWrite ) openFlags |= O_RDWR;
4116 if( isCreate ) openFlags |= O_CREAT;
4117 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4118 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004119
danielk1977b4b47412007-08-17 15:53:36 +00004120 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004121 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4122 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004123 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
4124 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4125 /* Failed to open the file for read/write access. Try read-only. */
4126 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004127 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004128 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004129 openFlags |= O_RDONLY;
4130 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004131 }
4132 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004133 rc = SQLITE_CANTOPEN;
4134 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004135 }
danielk1977b4b47412007-08-17 15:53:36 +00004136 }
dan08da86a2009-08-21 17:18:03 +00004137 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004138 if( pOutFlags ){
4139 *pOutFlags = flags;
4140 }
4141
dane946c392009-08-22 11:39:46 +00004142 if( p->pUnused ){
4143 p->pUnused->fd = fd;
4144 p->pUnused->flags = flags;
4145 }
4146
danielk1977b4b47412007-08-17 15:53:36 +00004147 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004148#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004149 zPath = zName;
4150#else
danielk197717b90b52008-06-06 11:11:25 +00004151 unlink(zName);
chw97185482008-11-17 08:05:31 +00004152#endif
danielk1977b4b47412007-08-17 15:53:36 +00004153 }
drh41022642008-11-21 00:24:42 +00004154#if SQLITE_ENABLE_LOCKING_STYLE
4155 else{
dan08da86a2009-08-21 17:18:03 +00004156 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004157 }
4158#endif
4159
danielk1977fee2d252007-08-18 10:59:19 +00004160 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004161 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004162 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004163 /* It is safe to close fd at this point, because it is guaranteed not
4164 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004165 ** it would not be safe to close as this would release any locks held
4166 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004167 assert( eType!=SQLITE_OPEN_MAIN_DB );
4168 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004169 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004170 }
4171 }
danielk1977e339d652008-06-28 11:23:00 +00004172
4173#ifdef FD_CLOEXEC
4174 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4175#endif
4176
drhda0e7682008-07-30 15:27:54 +00004177 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004178
drh7ed97b92010-01-20 13:07:21 +00004179
4180#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4181 struct statfs fsInfo;
4182 if( fstatfs(fd, &fsInfo) == -1 ){
4183 ((unixFile*)pFile)->lastErrno = errno;
4184 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4185 close(fd); /* silently leak if fail, in error */
4186 return SQLITE_IOERR_ACCESS;
4187 }
4188 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4189 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4190 }
4191#endif
4192
4193#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004194#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004195 isAutoProxy = 1;
4196#endif
4197 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004198 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4199 int useProxy = 0;
4200
dan08da86a2009-08-21 17:18:03 +00004201 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4202 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004203 if( envforce!=NULL ){
4204 useProxy = atoi(envforce)>0;
4205 }else{
4206 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004207 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004208 /* In theory, the close(fd) call is sub-optimal. If the file opened
4209 ** with fd is a database file, and there are other connections open
4210 ** on that file that are currently holding advisory locks on it,
4211 ** then the call to close() will cancel those locks. In practice,
4212 ** we're assuming that statfs() doesn't fail very often. At least
4213 ** not while other file descriptors opened by the same process on
4214 ** the same file are working. */
4215 p->lastErrno = errno;
4216 if( dirfd>=0 ){
4217 close(dirfd); /* silently leak if fail, in error */
4218 }
aswiftaebf4132008-11-21 00:10:35 +00004219 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004220 rc = SQLITE_IOERR_ACCESS;
4221 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004222 }
4223 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4224 }
4225 if( useProxy ){
4226 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4227 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004228 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004229 if( rc!=SQLITE_OK ){
4230 /* Use unixClose to clean up the resources added in fillInUnixFile
4231 ** and clear all the structure's references. Specifically,
4232 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4233 */
4234 unixClose(pFile);
4235 return rc;
4236 }
aswiftaebf4132008-11-21 00:10:35 +00004237 }
dane946c392009-08-22 11:39:46 +00004238 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004239 }
4240 }
4241#endif
4242
dane946c392009-08-22 11:39:46 +00004243 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4244open_finished:
4245 if( rc!=SQLITE_OK ){
4246 sqlite3_free(p->pUnused);
4247 }
4248 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004249}
4250
dane946c392009-08-22 11:39:46 +00004251
danielk1977b4b47412007-08-17 15:53:36 +00004252/*
danielk1977fee2d252007-08-18 10:59:19 +00004253** Delete the file at zPath. If the dirSync argument is true, fsync()
4254** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004255*/
drh6b9d6dd2008-12-03 19:34:47 +00004256static int unixDelete(
4257 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4258 const char *zPath, /* Name of file to be deleted */
4259 int dirSync /* If true, fsync() directory after deleting file */
4260){
danielk1977fee2d252007-08-18 10:59:19 +00004261 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004262 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004263 SimulateIOError(return SQLITE_IOERR_DELETE);
4264 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004265#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004266 if( dirSync ){
4267 int fd;
4268 rc = openDirectory(zPath, &fd);
4269 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004270#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004271 if( fsync(fd)==-1 )
4272#else
4273 if( fsync(fd) )
4274#endif
4275 {
danielk1977fee2d252007-08-18 10:59:19 +00004276 rc = SQLITE_IOERR_DIR_FSYNC;
4277 }
aswiftaebf4132008-11-21 00:10:35 +00004278 if( close(fd)&&!rc ){
4279 rc = SQLITE_IOERR_DIR_CLOSE;
4280 }
danielk1977fee2d252007-08-18 10:59:19 +00004281 }
4282 }
danielk1977d138dd82008-10-15 16:02:48 +00004283#endif
danielk1977fee2d252007-08-18 10:59:19 +00004284 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004285}
4286
danielk197790949c22007-08-17 16:50:38 +00004287/*
4288** Test the existance of or access permissions of file zPath. The
4289** test performed depends on the value of flags:
4290**
4291** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4292** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4293** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4294**
4295** Otherwise return 0.
4296*/
danielk1977861f7452008-06-05 11:39:11 +00004297static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004298 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4299 const char *zPath, /* Path of the file to examine */
4300 int flags, /* What do we want to learn about the zPath file? */
4301 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004302){
rse25c0d1a2007-09-20 08:38:14 +00004303 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004304 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004305 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004306 switch( flags ){
4307 case SQLITE_ACCESS_EXISTS:
4308 amode = F_OK;
4309 break;
4310 case SQLITE_ACCESS_READWRITE:
4311 amode = W_OK|R_OK;
4312 break;
drh50d3f902007-08-27 21:10:36 +00004313 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004314 amode = R_OK;
4315 break;
4316
4317 default:
4318 assert(!"Invalid flags argument");
4319 }
danielk1977861f7452008-06-05 11:39:11 +00004320 *pResOut = (access(zPath, amode)==0);
4321 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004322}
4323
danielk1977b4b47412007-08-17 15:53:36 +00004324
4325/*
4326** Turn a relative pathname into a full pathname. The relative path
4327** is stored as a nul-terminated string in the buffer pointed to by
4328** zPath.
4329**
4330** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4331** (in this case, MAX_PATHNAME bytes). The full-path is written to
4332** this buffer before returning.
4333*/
danielk1977adfb9b02007-09-17 07:02:56 +00004334static int unixFullPathname(
4335 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4336 const char *zPath, /* Possibly relative input path */
4337 int nOut, /* Size of output buffer in bytes */
4338 char *zOut /* Output buffer */
4339){
danielk1977843e65f2007-09-01 16:16:15 +00004340
4341 /* It's odd to simulate an io-error here, but really this is just
4342 ** using the io-error infrastructure to test that SQLite handles this
4343 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004344 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004345 */
4346 SimulateIOError( return SQLITE_ERROR );
4347
drh153c62c2007-08-24 03:51:33 +00004348 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004349 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004350
drh3c7f2dc2007-12-06 13:26:20 +00004351 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004352 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004353 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004354 }else{
4355 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004356 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00004357 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00004358 }
drhea678832008-12-10 19:26:22 +00004359 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004360 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004361 }
4362 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004363}
4364
drh0ccebe72005-06-07 22:22:50 +00004365
drh761df872006-12-21 01:29:22 +00004366#ifndef SQLITE_OMIT_LOAD_EXTENSION
4367/*
4368** Interfaces for opening a shared library, finding entry points
4369** within the shared library, and closing the shared library.
4370*/
4371#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004372static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4373 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004374 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4375}
danielk197795c8a542007-09-01 06:51:27 +00004376
4377/*
4378** SQLite calls this function immediately after a call to unixDlSym() or
4379** unixDlOpen() fails (returns a null pointer). If a more detailed error
4380** message is available, it is written to zBufOut. If no error message
4381** is available, zBufOut is left unmodified and SQLite uses a default
4382** error message.
4383*/
danielk1977397d65f2008-11-19 11:35:39 +00004384static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004385 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004386 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004387 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004388 zErr = dlerror();
4389 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004390 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004391 }
drh6c7d5c52008-11-21 20:32:33 +00004392 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004393}
drh1875f7a2008-12-08 18:19:17 +00004394static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4395 /*
4396 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4397 ** cast into a pointer to a function. And yet the library dlsym() routine
4398 ** returns a void* which is really a pointer to a function. So how do we
4399 ** use dlsym() with -pedantic-errors?
4400 **
4401 ** Variable x below is defined to be a pointer to a function taking
4402 ** parameters void* and const char* and returning a pointer to a function.
4403 ** We initialize x by assigning it a pointer to the dlsym() function.
4404 ** (That assignment requires a cast.) Then we call the function that
4405 ** x points to.
4406 **
4407 ** This work-around is unlikely to work correctly on any system where
4408 ** you really cannot cast a function pointer into void*. But then, on the
4409 ** other hand, dlsym() will not work on such a system either, so we have
4410 ** not really lost anything.
4411 */
4412 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004413 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004414 x = (void(*(*)(void*,const char*))(void))dlsym;
4415 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004416}
danielk1977397d65f2008-11-19 11:35:39 +00004417static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4418 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004419 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004420}
danielk1977b4b47412007-08-17 15:53:36 +00004421#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4422 #define unixDlOpen 0
4423 #define unixDlError 0
4424 #define unixDlSym 0
4425 #define unixDlClose 0
4426#endif
4427
4428/*
danielk197790949c22007-08-17 16:50:38 +00004429** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004430*/
danielk1977397d65f2008-11-19 11:35:39 +00004431static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4432 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004433 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004434
drhbbd42a62004-05-22 17:41:58 +00004435 /* We have to initialize zBuf to prevent valgrind from reporting
4436 ** errors. The reports issued by valgrind are incorrect - we would
4437 ** prefer that the randomness be increased by making use of the
4438 ** uninitialized space in zBuf - but valgrind errors tend to worry
4439 ** some users. Rather than argue, it seems easier just to initialize
4440 ** the whole array and silence valgrind, even if that means less randomness
4441 ** in the random seed.
4442 **
4443 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004444 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004445 ** tests repeatable.
4446 */
danielk1977b4b47412007-08-17 15:53:36 +00004447 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004448#if !defined(SQLITE_TEST)
4449 {
drh842b8642005-01-21 17:53:17 +00004450 int pid, fd;
4451 fd = open("/dev/urandom", O_RDONLY);
4452 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004453 time_t t;
4454 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004455 memcpy(zBuf, &t, sizeof(t));
4456 pid = getpid();
4457 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004458 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004459 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004460 }else{
drh72cbd072008-10-14 17:58:38 +00004461 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004462 close(fd);
4463 }
drhbbd42a62004-05-22 17:41:58 +00004464 }
4465#endif
drh72cbd072008-10-14 17:58:38 +00004466 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004467}
4468
danielk1977b4b47412007-08-17 15:53:36 +00004469
drhbbd42a62004-05-22 17:41:58 +00004470/*
4471** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004472** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004473** The return value is the number of microseconds of sleep actually
4474** requested from the underlying operating system, a number which
4475** might be greater than or equal to the argument, but not less
4476** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004477*/
danielk1977397d65f2008-11-19 11:35:39 +00004478static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004479#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004480 struct timespec sp;
4481
4482 sp.tv_sec = microseconds / 1000000;
4483 sp.tv_nsec = (microseconds % 1000000) * 1000;
4484 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004485 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004486 return microseconds;
4487#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004488 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004489 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004490 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004491#else
danielk1977b4b47412007-08-17 15:53:36 +00004492 int seconds = (microseconds+999999)/1000000;
4493 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004494 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004495 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004496#endif
drh88f474a2006-01-02 20:00:12 +00004497}
4498
4499/*
drh6b9d6dd2008-12-03 19:34:47 +00004500** The following variable, if set to a non-zero value, is interpreted as
4501** the number of seconds since 1970 and is used to set the result of
4502** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004503*/
4504#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004505int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004506#endif
4507
4508/*
4509** Find the current time (in Universal Coordinated Time). Write the
4510** current time and date as a Julian Day number into *prNow and
4511** return 0. Return 1 if the time and date cannot be found.
4512*/
danielk1977397d65f2008-11-19 11:35:39 +00004513static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004514#if defined(SQLITE_OMIT_FLOATING_POINT)
4515 time_t t;
4516 time(&t);
4517 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4518#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004519 time_t t;
4520 time(&t);
4521 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004522#elif OS_VXWORKS
4523 struct timespec sNow;
4524 clock_gettime(CLOCK_REALTIME, &sNow);
4525 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004526#else
4527 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004528 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004529 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4530#endif
danielk1977397d65f2008-11-19 11:35:39 +00004531
drhbbd42a62004-05-22 17:41:58 +00004532#ifdef SQLITE_TEST
4533 if( sqlite3_current_time ){
4534 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4535 }
4536#endif
danielk1977397d65f2008-11-19 11:35:39 +00004537 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004538 return 0;
4539}
danielk1977b4b47412007-08-17 15:53:36 +00004540
drh6b9d6dd2008-12-03 19:34:47 +00004541/*
4542** We added the xGetLastError() method with the intention of providing
4543** better low-level error messages when operating-system problems come up
4544** during SQLite operation. But so far, none of that has been implemented
4545** in the core. So this routine is never called. For now, it is merely
4546** a place-holder.
4547*/
danielk1977397d65f2008-11-19 11:35:39 +00004548static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4549 UNUSED_PARAMETER(NotUsed);
4550 UNUSED_PARAMETER(NotUsed2);
4551 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004552 return 0;
4553}
4554
drh153c62c2007-08-24 03:51:33 +00004555/*
drh734c9862008-11-28 15:37:20 +00004556************************ End of sqlite3_vfs methods ***************************
4557******************************************************************************/
4558
drh715ff302008-12-03 22:32:44 +00004559/******************************************************************************
4560************************** Begin Proxy Locking ********************************
4561**
4562** Proxy locking is a "uber-locking-method" in this sense: It uses the
4563** other locking methods on secondary lock files. Proxy locking is a
4564** meta-layer over top of the primitive locking implemented above. For
4565** this reason, the division that implements of proxy locking is deferred
4566** until late in the file (here) after all of the other I/O methods have
4567** been defined - so that the primitive locking methods are available
4568** as services to help with the implementation of proxy locking.
4569**
4570****
4571**
4572** The default locking schemes in SQLite use byte-range locks on the
4573** database file to coordinate safe, concurrent access by multiple readers
4574** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4575** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4576** as POSIX read & write locks over fixed set of locations (via fsctl),
4577** on AFP and SMB only exclusive byte-range locks are available via fsctl
4578** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4579** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4580** address in the shared range is taken for a SHARED lock, the entire
4581** shared range is taken for an EXCLUSIVE lock):
4582**
4583** PENDING_BYTE 0x40000000
4584** RESERVED_BYTE 0x40000001
4585** SHARED_RANGE 0x40000002 -> 0x40000200
4586**
4587** This works well on the local file system, but shows a nearly 100x
4588** slowdown in read performance on AFP because the AFP client disables
4589** the read cache when byte-range locks are present. Enabling the read
4590** cache exposes a cache coherency problem that is present on all OS X
4591** supported network file systems. NFS and AFP both observe the
4592** close-to-open semantics for ensuring cache coherency
4593** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4594** address the requirements for concurrent database access by multiple
4595** readers and writers
4596** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4597**
4598** To address the performance and cache coherency issues, proxy file locking
4599** changes the way database access is controlled by limiting access to a
4600** single host at a time and moving file locks off of the database file
4601** and onto a proxy file on the local file system.
4602**
4603**
4604** Using proxy locks
4605** -----------------
4606**
4607** C APIs
4608**
4609** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4610** <proxy_path> | ":auto:");
4611** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4612**
4613**
4614** SQL pragmas
4615**
4616** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4617** PRAGMA [database.]lock_proxy_file
4618**
4619** Specifying ":auto:" means that if there is a conch file with a matching
4620** host ID in it, the proxy path in the conch file will be used, otherwise
4621** a proxy path based on the user's temp dir
4622** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4623** actual proxy file name is generated from the name and path of the
4624** database file. For example:
4625**
4626** For database path "/Users/me/foo.db"
4627** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4628**
4629** Once a lock proxy is configured for a database connection, it can not
4630** be removed, however it may be switched to a different proxy path via
4631** the above APIs (assuming the conch file is not being held by another
4632** connection or process).
4633**
4634**
4635** How proxy locking works
4636** -----------------------
4637**
4638** Proxy file locking relies primarily on two new supporting files:
4639**
4640** * conch file to limit access to the database file to a single host
4641** at a time
4642**
4643** * proxy file to act as a proxy for the advisory locks normally
4644** taken on the database
4645**
4646** The conch file - to use a proxy file, sqlite must first "hold the conch"
4647** by taking an sqlite-style shared lock on the conch file, reading the
4648** contents and comparing the host's unique host ID (see below) and lock
4649** proxy path against the values stored in the conch. The conch file is
4650** stored in the same directory as the database file and the file name
4651** is patterned after the database file name as ".<databasename>-conch".
4652** If the conch file does not exist, or it's contents do not match the
4653** host ID and/or proxy path, then the lock is escalated to an exclusive
4654** lock and the conch file contents is updated with the host ID and proxy
4655** path and the lock is downgraded to a shared lock again. If the conch
4656** is held by another process (with a shared lock), the exclusive lock
4657** will fail and SQLITE_BUSY is returned.
4658**
4659** The proxy file - a single-byte file used for all advisory file locks
4660** normally taken on the database file. This allows for safe sharing
4661** of the database file for multiple readers and writers on the same
4662** host (the conch ensures that they all use the same local lock file).
4663**
drh715ff302008-12-03 22:32:44 +00004664** Requesting the lock proxy does not immediately take the conch, it is
4665** only taken when the first request to lock database file is made.
4666** This matches the semantics of the traditional locking behavior, where
4667** opening a connection to a database file does not take a lock on it.
4668** The shared lock and an open file descriptor are maintained until
4669** the connection to the database is closed.
4670**
4671** The proxy file and the lock file are never deleted so they only need
4672** to be created the first time they are used.
4673**
4674** Configuration options
4675** ---------------------
4676**
4677** SQLITE_PREFER_PROXY_LOCKING
4678**
4679** Database files accessed on non-local file systems are
4680** automatically configured for proxy locking, lock files are
4681** named automatically using the same logic as
4682** PRAGMA lock_proxy_file=":auto:"
4683**
4684** SQLITE_PROXY_DEBUG
4685**
4686** Enables the logging of error messages during host id file
4687** retrieval and creation
4688**
drh715ff302008-12-03 22:32:44 +00004689** LOCKPROXYDIR
4690**
4691** Overrides the default directory used for lock proxy files that
4692** are named automatically via the ":auto:" setting
4693**
4694** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4695**
4696** Permissions to use when creating a directory for storing the
4697** lock proxy files, only used when LOCKPROXYDIR is not set.
4698**
4699**
4700** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4701** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4702** force proxy locking to be used for every database file opened, and 0
4703** will force automatic proxy locking to be disabled for all database
4704** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4705** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4706*/
4707
4708/*
4709** Proxy locking is only available on MacOSX
4710*/
drhd2cb50b2009-01-09 21:41:17 +00004711#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004712
drh715ff302008-12-03 22:32:44 +00004713/*
4714** The proxyLockingContext has the path and file structures for the remote
4715** and local proxy files in it
4716*/
4717typedef struct proxyLockingContext proxyLockingContext;
4718struct proxyLockingContext {
4719 unixFile *conchFile; /* Open conch file */
4720 char *conchFilePath; /* Name of the conch file */
4721 unixFile *lockProxy; /* Open proxy lock file */
4722 char *lockProxyPath; /* Name of the proxy lock file */
4723 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00004724 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00004725 void *oldLockingContext; /* Original lockingcontext to restore on close */
4726 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4727};
4728
drh7ed97b92010-01-20 13:07:21 +00004729/*
4730** The proxy lock file path for the database at dbPath is written into lPath,
4731** which must point to valid, writable memory large enough for a maxLen length
4732** file path.
drh715ff302008-12-03 22:32:44 +00004733*/
drh715ff302008-12-03 22:32:44 +00004734static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4735 int len;
4736 int dbLen;
4737 int i;
4738
4739#ifdef LOCKPROXYDIR
4740 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4741#else
4742# ifdef _CS_DARWIN_USER_TEMP_DIR
4743 {
drh7ed97b92010-01-20 13:07:21 +00004744 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
4745 OSTRACE4("GETLOCKPATH failed %s errno=%d pid=%d\n",
4746 lPath, errno, getpid());
4747 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00004748 }
drh7ed97b92010-01-20 13:07:21 +00004749 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00004750 }
4751# else
4752 len = strlcpy(lPath, "/tmp/", maxLen);
4753# endif
4754#endif
4755
4756 if( lPath[len-1]!='/' ){
4757 len = strlcat(lPath, "/", maxLen);
4758 }
4759
4760 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004761 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004762 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4763 char c = dbPath[i];
4764 lPath[i+len] = (c=='/')?'_':c;
4765 }
4766 lPath[i+len]='\0';
4767 strlcat(lPath, ":auto:", maxLen);
drh7ed97b92010-01-20 13:07:21 +00004768 OSTRACE3("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid());
drh715ff302008-12-03 22:32:44 +00004769 return SQLITE_OK;
4770}
4771
drh7ed97b92010-01-20 13:07:21 +00004772/*
4773 ** Creates the lock file and any missing directories in lockPath
4774 */
4775static int proxyCreateLockPath(const char *lockPath){
4776 int i, len;
4777 char buf[MAXPATHLEN];
4778 int start = 0;
4779
4780 assert(lockPath!=NULL);
4781 /* try to create all the intermediate directories */
4782 len = (int)strlen(lockPath);
4783 buf[0] = lockPath[0];
4784 for( i=1; i<len; i++ ){
4785 if( lockPath[i] == '/' && (i - start > 0) ){
4786 /* only mkdir if leaf dir != "." or "/" or ".." */
4787 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
4788 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
4789 buf[i]='\0';
4790 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4791 int err=errno;
4792 if( err!=EEXIST ) {
4793 OSTRACE5("CREATELOCKPATH FAILED creating %s, "
4794 "'%s' proxy lock path=%s pid=%d\n",
4795 buf, strerror(err), lockPath, getpid());
4796 return err;
4797 }
4798 }
4799 }
4800 start=i+1;
4801 }
4802 buf[i] = lockPath[i];
4803 }
4804 OSTRACE3("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid());
4805 return 0;
4806}
4807
drh715ff302008-12-03 22:32:44 +00004808/*
4809** Create a new VFS file descriptor (stored in memory obtained from
4810** sqlite3_malloc) and open the file named "path" in the file descriptor.
4811**
4812** The caller is responsible not only for closing the file descriptor
4813** but also for freeing the memory associated with the file descriptor.
4814*/
drh7ed97b92010-01-20 13:07:21 +00004815static int proxyCreateUnixFile(
4816 const char *path, /* path for the new unixFile */
4817 unixFile **ppFile, /* unixFile created and returned by ref */
4818 int islockfile /* if non zero missing dirs will be created */
4819) {
4820 int fd = -1;
4821 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00004822 unixFile *pNew;
4823 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00004824 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00004825 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00004826 int terrno = 0;
4827 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00004828
drh7ed97b92010-01-20 13:07:21 +00004829 /* 1. first try to open/create the file
4830 ** 2. if that fails, and this is a lock file (not-conch), try creating
4831 ** the parent directories and then try again.
4832 ** 3. if that fails, try to open the file read-only
4833 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
4834 */
4835 pUnused = findReusableFd(path, openFlags);
4836 if( pUnused ){
4837 fd = pUnused->fd;
4838 }else{
4839 pUnused = sqlite3_malloc(sizeof(*pUnused));
4840 if( !pUnused ){
4841 return SQLITE_NOMEM;
4842 }
4843 }
4844 if( fd<0 ){
4845 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4846 terrno = errno;
4847 if( fd<0 && errno==ENOENT && islockfile ){
4848 if( proxyCreateLockPath(path) == SQLITE_OK ){
4849 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4850 }
4851 }
4852 }
4853 if( fd<0 ){
4854 openFlags = O_RDONLY;
4855 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
4856 terrno = errno;
4857 }
4858 if( fd<0 ){
4859 if( islockfile ){
4860 return SQLITE_BUSY;
4861 }
4862 switch (terrno) {
4863 case EACCES:
4864 return SQLITE_PERM;
4865 case EIO:
4866 return SQLITE_IOERR_LOCK; /* even though it is the conch */
4867 default:
4868 return SQLITE_CANTOPEN;
4869 }
4870 }
4871
4872 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
4873 if( pNew==NULL ){
4874 rc = SQLITE_NOMEM;
4875 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00004876 }
4877 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00004878 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00004879 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00004880 pUnused->fd = fd;
4881 pUnused->flags = openFlags;
4882 pNew->pUnused = pUnused;
4883
4884 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4885 if( rc==SQLITE_OK ){
4886 *ppFile = pNew;
4887 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00004888 }
drh7ed97b92010-01-20 13:07:21 +00004889end_create_proxy:
4890 close(fd); /* silently leak fd if error, we're already in error */
4891 sqlite3_free(pNew);
4892 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00004893 return rc;
4894}
4895
drh7ed97b92010-01-20 13:07:21 +00004896#ifdef SQLITE_TEST
4897/* simulate multiple hosts by creating unique hostid file paths */
4898int sqlite3_hostid_num = 0;
4899#endif
4900
4901#define PROXY_HOSTIDLEN 16 /* conch file host id length */
4902
4903/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
4904** bytes of writable memory.
4905*/
4906static int proxyGetHostID(unsigned char *pHostID, int *pError){
4907 struct timespec timeout = {1, 0}; /* 1 sec timeout */
4908
4909 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
4910 memset(pHostID, 0, PROXY_HOSTIDLEN);
4911 if( gethostuuid(pHostID, &timeout) ){
4912 int err = errno;
4913 if( pError ){
4914 *pError = err;
4915 }
4916 return SQLITE_IOERR;
4917 }
4918#ifdef SQLITE_TEST
4919 /* simulate multiple hosts by creating unique hostid file paths */
4920 if( sqlite3_hostid_num != 0){
4921 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
4922 }
4923#endif
4924
4925 return SQLITE_OK;
4926}
4927
4928/* The conch file contains the header, host id and lock file path
4929 */
4930#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
4931#define PROXY_HEADERLEN 1 /* conch file header length */
4932#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
4933#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
4934
4935/*
4936** Takes an open conch file, copies the contents to a new path and then moves
4937** it back. The newly created file's file descriptor is assigned to the
4938** conch file structure and finally the original conch file descriptor is
4939** closed. Returns zero if successful.
4940*/
4941static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
4942 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4943 unixFile *conchFile = pCtx->conchFile;
4944 char tPath[MAXPATHLEN];
4945 char buf[PROXY_MAXCONCHLEN];
4946 char *cPath = pCtx->conchFilePath;
4947 size_t readLen = 0;
4948 size_t pathLen = 0;
4949 char errmsg[64] = "";
4950 int fd = -1;
4951 int rc = -1;
4952
4953 /* create a new path by replace the trailing '-conch' with '-break' */
4954 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
4955 if( pathLen>MAXPATHLEN || pathLen<6 ||
4956 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
4957 sprintf(errmsg, "path error (len %d)", (int)pathLen);
4958 goto end_breaklock;
4959 }
4960 /* read the conch content */
4961 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
4962 if( readLen<PROXY_PATHINDEX ){
4963 sprintf(errmsg, "read error (len %d)", (int)readLen);
4964 goto end_breaklock;
4965 }
4966 /* write it out to the temporary break file */
4967 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
4968 if( fd<0 ){
4969 sprintf(errmsg, "create failed (%d)", errno);
4970 goto end_breaklock;
4971 }
4972 if( pwrite(fd, buf, readLen, 0) != readLen ){
4973 sprintf(errmsg, "write failed (%d)", errno);
4974 goto end_breaklock;
4975 }
4976 if( rename(tPath, cPath) ){
4977 sprintf(errmsg, "rename failed (%d)", errno);
4978 goto end_breaklock;
4979 }
4980 rc = 0;
4981 fprintf(stderr, "broke stale lock on %s\n", cPath);
4982 close(conchFile->h);
4983 conchFile->h = fd;
4984 conchFile->openFlags = O_RDWR | O_CREAT;
4985
4986end_breaklock:
4987 if( rc ){
4988 if( fd>=0 ){
4989 unlink(tPath);
4990 close(fd);
4991 }
4992 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
4993 }
4994 return rc;
4995}
4996
4997/* Take the requested lock on the conch file and break a stale lock if the
4998** host id matches.
4999*/
5000static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5001 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5002 unixFile *conchFile = pCtx->conchFile;
5003 int rc = SQLITE_OK;
5004 int nTries = 0;
5005 struct timespec conchModTime;
5006
5007 do {
5008 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5009 nTries ++;
5010 if( rc==SQLITE_BUSY ){
5011 /* If the lock failed (busy):
5012 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5013 * 2nd try: fail if the mod time changed or host id is different, wait
5014 * 10 sec and try again
5015 * 3rd try: break the lock unless the mod time has changed.
5016 */
5017 struct stat buf;
5018 if( fstat(conchFile->h, &buf) ){
5019 pFile->lastErrno = errno;
5020 return SQLITE_IOERR_LOCK;
5021 }
5022
5023 if( nTries==1 ){
5024 conchModTime = buf.st_mtimespec;
5025 usleep(500000); /* wait 0.5 sec and try the lock again*/
5026 continue;
5027 }
5028
5029 assert( nTries>1 );
5030 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5031 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5032 return SQLITE_BUSY;
5033 }
5034
5035 if( nTries==2 ){
5036 char tBuf[PROXY_MAXCONCHLEN];
5037 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5038 if( len<0 ){
5039 pFile->lastErrno = errno;
5040 return SQLITE_IOERR_LOCK;
5041 }
5042 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5043 /* don't break the lock if the host id doesn't match */
5044 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5045 return SQLITE_BUSY;
5046 }
5047 }else{
5048 /* don't break the lock on short read or a version mismatch */
5049 return SQLITE_BUSY;
5050 }
5051 usleep(10000000); /* wait 10 sec and try the lock again */
5052 continue;
5053 }
5054
5055 assert( nTries==3 );
5056 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5057 rc = SQLITE_OK;
5058 if( lockType==EXCLUSIVE_LOCK ){
5059 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5060 }
5061 if( !rc ){
5062 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5063 }
5064 }
5065 }
5066 } while( rc==SQLITE_BUSY && nTries<3 );
5067
5068 return rc;
5069}
5070
5071/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005072** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5073** lockPath means that the lockPath in the conch file will be used if the
5074** host IDs match, or a new lock path will be generated automatically
5075** and written to the conch file.
5076*/
5077static int proxyTakeConch(unixFile *pFile){
5078 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5079
drh7ed97b92010-01-20 13:07:21 +00005080 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005081 return SQLITE_OK;
5082 }else{
5083 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005084 uuid_t myHostID;
5085 int pError = 0;
5086 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005087 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005088 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005089 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005090 int createConch = 0;
5091 int hostIdMatch = 0;
5092 int readLen = 0;
5093 int tryOldLockPath = 0;
5094 int forceNewLockPath = 0;
5095
drh715ff302008-12-03 22:32:44 +00005096 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5097 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
5098
drh7ed97b92010-01-20 13:07:21 +00005099 rc = proxyGetHostID(myHostID, &pError);
5100 if( (rc&0xff)==SQLITE_IOERR ){
5101 pFile->lastErrno = pError;
5102 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005103 }
drh7ed97b92010-01-20 13:07:21 +00005104 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005105 if( rc!=SQLITE_OK ){
5106 goto end_takeconch;
5107 }
drh7ed97b92010-01-20 13:07:21 +00005108 /* read the existing conch file */
5109 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5110 if( readLen<0 ){
5111 /* I/O error: lastErrno set by seekAndRead */
5112 pFile->lastErrno = conchFile->lastErrno;
5113 rc = SQLITE_IOERR_READ;
5114 goto end_takeconch;
5115 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5116 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5117 /* a short read or version format mismatch means we need to create a new
5118 ** conch file.
5119 */
5120 createConch = 1;
5121 }
5122 /* if the host id matches and the lock path already exists in the conch
5123 ** we'll try to use the path there, if we can't open that path, we'll
5124 ** retry with a new auto-generated path
5125 */
5126 do { /* in case we need to try again for an :auto: named lock file */
5127
5128 if( !createConch && !forceNewLockPath ){
5129 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5130 PROXY_HOSTIDLEN);
5131 /* if the conch has data compare the contents */
5132 if( !pCtx->lockProxyPath ){
5133 /* for auto-named local lock file, just check the host ID and we'll
5134 ** use the local lock file path that's already in there
5135 */
5136 if( hostIdMatch ){
5137 size_t pathLen = (readLen - PROXY_PATHINDEX);
5138
5139 if( pathLen>=MAXPATHLEN ){
5140 pathLen=MAXPATHLEN-1;
5141 }
5142 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5143 lockPath[pathLen] = 0;
5144 tempLockPath = lockPath;
5145 tryOldLockPath = 1;
5146 /* create a copy of the lock path if the conch is taken */
5147 goto end_takeconch;
5148 }
5149 }else if( hostIdMatch
5150 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5151 readLen-PROXY_PATHINDEX)
5152 ){
5153 /* conch host and lock path match */
5154 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005155 }
drh7ed97b92010-01-20 13:07:21 +00005156 }
5157
5158 /* if the conch isn't writable and doesn't match, we can't take it */
5159 if( (conchFile->openFlags&O_RDWR) == 0 ){
5160 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005161 goto end_takeconch;
5162 }
drh7ed97b92010-01-20 13:07:21 +00005163
5164 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005165 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005166 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5167 tempLockPath = lockPath;
5168 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005169 }
drh7ed97b92010-01-20 13:07:21 +00005170
5171 /* update conch with host and path (this will fail if other process
5172 ** has a shared lock already), if the host id matches, use the big
5173 ** stick.
drh715ff302008-12-03 22:32:44 +00005174 */
drh7ed97b92010-01-20 13:07:21 +00005175 futimes(conchFile->h, NULL);
5176 if( hostIdMatch && !createConch ){
5177 if( conchFile->pLock && conchFile->pLock->cnt>1 ){
5178 /* We are trying for an exclusive lock but another thread in this
5179 ** same process is still holding a shared lock. */
5180 rc = SQLITE_BUSY;
5181 } else {
5182 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005183 }
drh715ff302008-12-03 22:32:44 +00005184 }else{
drh7ed97b92010-01-20 13:07:21 +00005185 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005186 }
drh7ed97b92010-01-20 13:07:21 +00005187 if( rc==SQLITE_OK ){
5188 char writeBuffer[PROXY_MAXCONCHLEN];
5189 int writeSize = 0;
5190
5191 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5192 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5193 if( pCtx->lockProxyPath!=NULL ){
5194 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5195 }else{
5196 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5197 }
5198 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5199 ftruncate(conchFile->h, writeSize);
5200 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5201 fsync(conchFile->h);
5202 /* If we created a new conch file (not just updated the contents of a
5203 ** valid conch file), try to match the permissions of the database
5204 */
5205 if( rc==SQLITE_OK && createConch ){
5206 struct stat buf;
5207 int err = fstat(pFile->h, &buf);
5208 if( err==0 ){
5209 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5210 S_IROTH|S_IWOTH);
5211 /* try to match the database file R/W permissions, ignore failure */
5212#ifndef SQLITE_PROXY_DEBUG
5213 fchmod(conchFile->h, cmode);
5214#else
5215 if( fchmod(conchFile->h, cmode)!=0 ){
5216 int code = errno;
5217 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5218 cmode, code, strerror(code));
5219 } else {
5220 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5221 }
5222 }else{
5223 int code = errno;
5224 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5225 err, code, strerror(code));
5226#endif
5227 }
drh715ff302008-12-03 22:32:44 +00005228 }
5229 }
drh7ed97b92010-01-20 13:07:21 +00005230 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5231
5232 end_takeconch:
5233 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
5234 if( rc==SQLITE_OK && pFile->openFlags ){
5235 if( pFile->h>=0 ){
5236#ifdef STRICT_CLOSE_ERROR
5237 if( close(pFile->h) ){
5238 pFile->lastErrno = errno;
5239 return SQLITE_IOERR_CLOSE;
5240 }
5241#else
5242 close(pFile->h); /* silently leak fd if fail */
5243#endif
5244 }
5245 pFile->h = -1;
5246 int fd = open(pCtx->dbPath, pFile->openFlags,
5247 SQLITE_DEFAULT_FILE_PERMISSIONS);
5248 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
5249 if( fd>=0 ){
5250 pFile->h = fd;
5251 }else{
5252 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
5253 during locking */
5254 }
5255 }
5256 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5257 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5258 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5259 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5260 /* we couldn't create the proxy lock file with the old lock file path
5261 ** so try again via auto-naming
5262 */
5263 forceNewLockPath = 1;
5264 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005265 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005266 }
5267 }
5268 if( rc==SQLITE_OK ){
5269 /* Need to make a copy of path if we extracted the value
5270 ** from the conch file or the path was allocated on the stack
5271 */
5272 if( tempLockPath ){
5273 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5274 if( !pCtx->lockProxyPath ){
5275 rc = SQLITE_NOMEM;
5276 }
5277 }
5278 }
5279 if( rc==SQLITE_OK ){
5280 pCtx->conchHeld = 1;
5281
5282 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5283 afpLockingContext *afpCtx;
5284 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5285 afpCtx->dbPath = pCtx->lockProxyPath;
5286 }
5287 } else {
5288 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5289 }
5290 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
5291 return rc;
5292 } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005293 }
5294}
5295
5296/*
5297** If pFile holds a lock on a conch file, then release that lock.
5298*/
5299static int proxyReleaseConch(unixFile *pFile){
5300 int rc; /* Subroutine return code */
5301 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5302 unixFile *conchFile; /* Name of the conch file */
5303
5304 pCtx = (proxyLockingContext *)pFile->lockingContext;
5305 conchFile = pCtx->conchFile;
5306 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
5307 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
5308 getpid());
drh7ed97b92010-01-20 13:07:21 +00005309 if( pCtx->conchHeld>0 ){
5310 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5311 }
drh715ff302008-12-03 22:32:44 +00005312 pCtx->conchHeld = 0;
drh715ff302008-12-03 22:32:44 +00005313 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
5314 (rc==SQLITE_OK ? "ok" : "failed"));
5315 return rc;
5316}
5317
5318/*
5319** Given the name of a database file, compute the name of its conch file.
5320** Store the conch filename in memory obtained from sqlite3_malloc().
5321** Make *pConchPath point to the new name. Return SQLITE_OK on success
5322** or SQLITE_NOMEM if unable to obtain memory.
5323**
5324** The caller is responsible for ensuring that the allocated memory
5325** space is eventually freed.
5326**
5327** *pConchPath is set to NULL if a memory allocation error occurs.
5328*/
5329static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5330 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005331 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005332 char *conchPath; /* buffer in which to construct conch name */
5333
5334 /* Allocate space for the conch filename and initialize the name to
5335 ** the name of the original database file. */
5336 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5337 if( conchPath==0 ){
5338 return SQLITE_NOMEM;
5339 }
5340 memcpy(conchPath, dbPath, len+1);
5341
5342 /* now insert a "." before the last / character */
5343 for( i=(len-1); i>=0; i-- ){
5344 if( conchPath[i]=='/' ){
5345 i++;
5346 break;
5347 }
5348 }
5349 conchPath[i]='.';
5350 while ( i<len ){
5351 conchPath[i+1]=dbPath[i];
5352 i++;
5353 }
5354
5355 /* append the "-conch" suffix to the file */
5356 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005357 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005358
5359 return SQLITE_OK;
5360}
5361
5362
5363/* Takes a fully configured proxy locking-style unix file and switches
5364** the local lock file path
5365*/
5366static int switchLockProxyPath(unixFile *pFile, const char *path) {
5367 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5368 char *oldPath = pCtx->lockProxyPath;
5369 int rc = SQLITE_OK;
5370
5371 if( pFile->locktype!=NO_LOCK ){
5372 return SQLITE_BUSY;
5373 }
5374
5375 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5376 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5377 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5378 return SQLITE_OK;
5379 }else{
5380 unixFile *lockProxy = pCtx->lockProxy;
5381 pCtx->lockProxy=NULL;
5382 pCtx->conchHeld = 0;
5383 if( lockProxy!=NULL ){
5384 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5385 if( rc ) return rc;
5386 sqlite3_free(lockProxy);
5387 }
5388 sqlite3_free(oldPath);
5389 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5390 }
5391
5392 return rc;
5393}
5394
5395/*
5396** pFile is a file that has been opened by a prior xOpen call. dbPath
5397** is a string buffer at least MAXPATHLEN+1 characters in size.
5398**
5399** This routine find the filename associated with pFile and writes it
5400** int dbPath.
5401*/
5402static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005403#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005404 if( pFile->pMethod == &afpIoMethods ){
5405 /* afp style keeps a reference to the db path in the filePath field
5406 ** of the struct */
drhea678832008-12-10 19:26:22 +00005407 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005408 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5409 } else
drh715ff302008-12-03 22:32:44 +00005410#endif
5411 if( pFile->pMethod == &dotlockIoMethods ){
5412 /* dot lock style uses the locking context to store the dot lock
5413 ** file path */
5414 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5415 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5416 }else{
5417 /* all other styles use the locking context to store the db file path */
5418 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005419 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005420 }
5421 return SQLITE_OK;
5422}
5423
5424/*
5425** Takes an already filled in unix file and alters it so all file locking
5426** will be performed on the local proxy lock file. The following fields
5427** are preserved in the locking context so that they can be restored and
5428** the unix structure properly cleaned up at close time:
5429** ->lockingContext
5430** ->pMethod
5431*/
5432static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5433 proxyLockingContext *pCtx;
5434 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5435 char *lockPath=NULL;
5436 int rc = SQLITE_OK;
5437
5438 if( pFile->locktype!=NO_LOCK ){
5439 return SQLITE_BUSY;
5440 }
5441 proxyGetDbPathForUnixFile(pFile, dbPath);
5442 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5443 lockPath=NULL;
5444 }else{
5445 lockPath=(char *)path;
5446 }
5447
5448 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5449 (lockPath ? lockPath : ":auto:"), getpid());
5450
5451 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5452 if( pCtx==0 ){
5453 return SQLITE_NOMEM;
5454 }
5455 memset(pCtx, 0, sizeof(*pCtx));
5456
5457 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5458 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005459 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5460 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5461 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5462 ** (c) the file system is read-only, then enable no-locking access.
5463 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5464 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5465 */
5466 struct statfs fsInfo;
5467 struct stat conchInfo;
5468 int goLockless = 0;
5469
5470 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5471 int err = errno;
5472 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5473 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5474 }
5475 }
5476 if( goLockless ){
5477 pCtx->conchHeld = -1; /* read only FS/ lockless */
5478 rc = SQLITE_OK;
5479 }
5480 }
drh715ff302008-12-03 22:32:44 +00005481 }
5482 if( rc==SQLITE_OK && lockPath ){
5483 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5484 }
5485
5486 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005487 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5488 if( pCtx->dbPath==NULL ){
5489 rc = SQLITE_NOMEM;
5490 }
5491 }
5492 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005493 /* all memory is allocated, proxys are created and assigned,
5494 ** switch the locking context and pMethod then return.
5495 */
drh715ff302008-12-03 22:32:44 +00005496 pCtx->oldLockingContext = pFile->lockingContext;
5497 pFile->lockingContext = pCtx;
5498 pCtx->pOldMethod = pFile->pMethod;
5499 pFile->pMethod = &proxyIoMethods;
5500 }else{
5501 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00005502 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00005503 sqlite3_free(pCtx->conchFile);
5504 }
drh7ed97b92010-01-20 13:07:21 +00005505 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00005506 sqlite3_free(pCtx->conchFilePath);
5507 sqlite3_free(pCtx);
5508 }
5509 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
5510 (rc==SQLITE_OK ? "ok" : "failed"));
5511 return rc;
5512}
5513
5514
5515/*
5516** This routine handles sqlite3_file_control() calls that are specific
5517** to proxy locking.
5518*/
5519static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5520 switch( op ){
5521 case SQLITE_GET_LOCKPROXYFILE: {
5522 unixFile *pFile = (unixFile*)id;
5523 if( pFile->pMethod == &proxyIoMethods ){
5524 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5525 proxyTakeConch(pFile);
5526 if( pCtx->lockProxyPath ){
5527 *(const char **)pArg = pCtx->lockProxyPath;
5528 }else{
5529 *(const char **)pArg = ":auto: (not held)";
5530 }
5531 } else {
5532 *(const char **)pArg = NULL;
5533 }
5534 return SQLITE_OK;
5535 }
5536 case SQLITE_SET_LOCKPROXYFILE: {
5537 unixFile *pFile = (unixFile*)id;
5538 int rc = SQLITE_OK;
5539 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5540 if( pArg==NULL || (const char *)pArg==0 ){
5541 if( isProxyStyle ){
5542 /* turn off proxy locking - not supported */
5543 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5544 }else{
5545 /* turn off proxy locking - already off - NOOP */
5546 rc = SQLITE_OK;
5547 }
5548 }else{
5549 const char *proxyPath = (const char *)pArg;
5550 if( isProxyStyle ){
5551 proxyLockingContext *pCtx =
5552 (proxyLockingContext*)pFile->lockingContext;
5553 if( !strcmp(pArg, ":auto:")
5554 || (pCtx->lockProxyPath &&
5555 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5556 ){
5557 rc = SQLITE_OK;
5558 }else{
5559 rc = switchLockProxyPath(pFile, proxyPath);
5560 }
5561 }else{
5562 /* turn on proxy file locking */
5563 rc = proxyTransformUnixFile(pFile, proxyPath);
5564 }
5565 }
5566 return rc;
5567 }
5568 default: {
5569 assert( 0 ); /* The call assures that only valid opcodes are sent */
5570 }
5571 }
5572 /*NOTREACHED*/
5573 return SQLITE_ERROR;
5574}
5575
5576/*
5577** Within this division (the proxying locking implementation) the procedures
5578** above this point are all utilities. The lock-related methods of the
5579** proxy-locking sqlite3_io_method object follow.
5580*/
5581
5582
5583/*
5584** This routine checks if there is a RESERVED lock held on the specified
5585** file by this or any other process. If such a lock is held, set *pResOut
5586** to a non-zero value otherwise *pResOut is set to zero. The return value
5587** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5588*/
5589static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5590 unixFile *pFile = (unixFile*)id;
5591 int rc = proxyTakeConch(pFile);
5592 if( rc==SQLITE_OK ){
5593 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005594 if( pCtx->conchHeld>0 ){
5595 unixFile *proxy = pCtx->lockProxy;
5596 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5597 }else{ /* conchHeld < 0 is lockless */
5598 pResOut=0;
5599 }
drh715ff302008-12-03 22:32:44 +00005600 }
5601 return rc;
5602}
5603
5604/*
5605** Lock the file with the lock specified by parameter locktype - one
5606** of the following:
5607**
5608** (1) SHARED_LOCK
5609** (2) RESERVED_LOCK
5610** (3) PENDING_LOCK
5611** (4) EXCLUSIVE_LOCK
5612**
5613** Sometimes when requesting one lock state, additional lock states
5614** are inserted in between. The locking might fail on one of the later
5615** transitions leaving the lock state different from what it started but
5616** still short of its goal. The following chart shows the allowed
5617** transitions and the inserted intermediate states:
5618**
5619** UNLOCKED -> SHARED
5620** SHARED -> RESERVED
5621** SHARED -> (PENDING) -> EXCLUSIVE
5622** RESERVED -> (PENDING) -> EXCLUSIVE
5623** PENDING -> EXCLUSIVE
5624**
5625** This routine will only increase a lock. Use the sqlite3OsUnlock()
5626** routine to lower a locking level.
5627*/
5628static int proxyLock(sqlite3_file *id, int locktype) {
5629 unixFile *pFile = (unixFile*)id;
5630 int rc = proxyTakeConch(pFile);
5631 if( rc==SQLITE_OK ){
5632 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005633 if( pCtx->conchHeld>0 ){
5634 unixFile *proxy = pCtx->lockProxy;
5635 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
5636 pFile->locktype = proxy->locktype;
5637 }else{
5638 /* conchHeld < 0 is lockless */
5639 }
drh715ff302008-12-03 22:32:44 +00005640 }
5641 return rc;
5642}
5643
5644
5645/*
5646** Lower the locking level on file descriptor pFile to locktype. locktype
5647** must be either NO_LOCK or SHARED_LOCK.
5648**
5649** If the locking level of the file descriptor is already at or below
5650** the requested locking level, this routine is a no-op.
5651*/
5652static int proxyUnlock(sqlite3_file *id, int locktype) {
5653 unixFile *pFile = (unixFile*)id;
5654 int rc = proxyTakeConch(pFile);
5655 if( rc==SQLITE_OK ){
5656 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00005657 if( pCtx->conchHeld>0 ){
5658 unixFile *proxy = pCtx->lockProxy;
5659 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5660 pFile->locktype = proxy->locktype;
5661 }else{
5662 /* conchHeld < 0 is lockless */
5663 }
drh715ff302008-12-03 22:32:44 +00005664 }
5665 return rc;
5666}
5667
5668/*
5669** Close a file that uses proxy locks.
5670*/
5671static int proxyClose(sqlite3_file *id) {
5672 if( id ){
5673 unixFile *pFile = (unixFile*)id;
5674 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5675 unixFile *lockProxy = pCtx->lockProxy;
5676 unixFile *conchFile = pCtx->conchFile;
5677 int rc = SQLITE_OK;
5678
5679 if( lockProxy ){
5680 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5681 if( rc ) return rc;
5682 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5683 if( rc ) return rc;
5684 sqlite3_free(lockProxy);
5685 pCtx->lockProxy = 0;
5686 }
5687 if( conchFile ){
5688 if( pCtx->conchHeld ){
5689 rc = proxyReleaseConch(pFile);
5690 if( rc ) return rc;
5691 }
5692 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5693 if( rc ) return rc;
5694 sqlite3_free(conchFile);
5695 }
5696 sqlite3_free(pCtx->lockProxyPath);
5697 sqlite3_free(pCtx->conchFilePath);
5698 sqlite3_free(pCtx->dbPath);
5699 /* restore the original locking context and pMethod then close it */
5700 pFile->lockingContext = pCtx->oldLockingContext;
5701 pFile->pMethod = pCtx->pOldMethod;
5702 sqlite3_free(pCtx);
5703 return pFile->pMethod->xClose(id);
5704 }
5705 return SQLITE_OK;
5706}
5707
5708
5709
drhd2cb50b2009-01-09 21:41:17 +00005710#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005711/*
5712** The proxy locking style is intended for use with AFP filesystems.
5713** And since AFP is only supported on MacOSX, the proxy locking is also
5714** restricted to MacOSX.
5715**
5716**
5717******************* End of the proxy lock implementation **********************
5718******************************************************************************/
5719
drh734c9862008-11-28 15:37:20 +00005720/*
danielk1977e339d652008-06-28 11:23:00 +00005721** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005722**
5723** This routine registers all VFS implementations for unix-like operating
5724** systems. This routine, and the sqlite3_os_end() routine that follows,
5725** should be the only routines in this file that are visible from other
5726** files.
drh6b9d6dd2008-12-03 19:34:47 +00005727**
5728** This routine is called once during SQLite initialization and by a
5729** single thread. The memory allocation and mutex subsystems have not
5730** necessarily been initialized when this routine is called, and so they
5731** should not be used.
drh153c62c2007-08-24 03:51:33 +00005732*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005733int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005734 /*
5735 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005736 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5737 ** to the "finder" function. (pAppData is a pointer to a pointer because
5738 ** silly C90 rules prohibit a void* from being cast to a function pointer
5739 ** and so we have to go through the intermediate pointer to avoid problems
5740 ** when compiling with -pedantic-errors on GCC.)
5741 **
5742 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005743 ** finder-function. The finder-function returns a pointer to the
5744 ** sqlite_io_methods object that implements the desired locking
5745 ** behaviors. See the division above that contains the IOMETHODS
5746 ** macro for addition information on finder-functions.
5747 **
5748 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5749 ** object. But the "autolockIoFinder" available on MacOSX does a little
5750 ** more than that; it looks at the filesystem type that hosts the
5751 ** database file and tries to choose an locking method appropriate for
5752 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005753 */
drh7708e972008-11-29 00:56:52 +00005754 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005755 1, /* iVersion */ \
5756 sizeof(unixFile), /* szOsFile */ \
5757 MAX_PATHNAME, /* mxPathname */ \
5758 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005759 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005760 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005761 unixOpen, /* xOpen */ \
5762 unixDelete, /* xDelete */ \
5763 unixAccess, /* xAccess */ \
5764 unixFullPathname, /* xFullPathname */ \
5765 unixDlOpen, /* xDlOpen */ \
5766 unixDlError, /* xDlError */ \
5767 unixDlSym, /* xDlSym */ \
5768 unixDlClose, /* xDlClose */ \
5769 unixRandomness, /* xRandomness */ \
5770 unixSleep, /* xSleep */ \
5771 unixCurrentTime, /* xCurrentTime */ \
5772 unixGetLastError /* xGetLastError */ \
5773 }
5774
drh6b9d6dd2008-12-03 19:34:47 +00005775 /*
5776 ** All default VFSes for unix are contained in the following array.
5777 **
5778 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5779 ** by the SQLite core when the VFS is registered. So the following
5780 ** array cannot be const.
5781 */
danielk1977e339d652008-06-28 11:23:00 +00005782 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005783#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005784 UNIXVFS("unix", autolockIoFinder ),
5785#else
5786 UNIXVFS("unix", posixIoFinder ),
5787#endif
5788 UNIXVFS("unix-none", nolockIoFinder ),
5789 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005790#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005791 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005792#endif
5793#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005794 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005795#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005796 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005797#endif
chw78a13182009-04-07 05:35:03 +00005798#endif
drhd2cb50b2009-01-09 21:41:17 +00005799#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005800 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00005801 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00005802 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005803#endif
drh153c62c2007-08-24 03:51:33 +00005804 };
drh6b9d6dd2008-12-03 19:34:47 +00005805 unsigned int i; /* Loop counter */
5806
5807 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005808 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005809 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005810 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005811 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005812}
danielk1977e339d652008-06-28 11:23:00 +00005813
5814/*
drh6b9d6dd2008-12-03 19:34:47 +00005815** Shutdown the operating system interface.
5816**
5817** Some operating systems might need to do some cleanup in this routine,
5818** to release dynamically allocated objects. But not on unix.
5819** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005820*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005821int sqlite3_os_end(void){
5822 return SQLITE_OK;
5823}
drhdce8bdb2007-08-16 13:01:44 +00005824
danielk197729bafea2008-06-26 10:41:19 +00005825#endif /* SQLITE_OS_UNIX */