blob: a7f1271ac62c33f1c8466bc4326a9046bbc493f9 [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**
13** This file contains code that is specific to Unix systems.
14*/
drhbbd42a62004-05-22 17:41:58 +000015#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000016#include "os.h"
17#if OS_UNIX /* This file is used on unix only */
drh9cbe6352005-11-29 03:13:21 +000018/*
19** These #defines should enable >2GB file support on Posix if the
20** underlying operating system supports it. If the OS lacks
21** large file support, or if the OS is windows, these should be no-ops.
22**
23** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24** on the compiler command line. This is necessary if you are compiling
25** on a recent machine (ex: RedHat 7.2) but you want your code to work
26** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
27** without this option, LFS is enable. But LFS does not exist in the kernel
28** in RedHat 6.0, so the code won't work. Hence, for maximum binary
29** portability you should omit LFS.
30**
31** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
32*/
33#ifndef SQLITE_DISABLE_LFS
34# define _LARGE_FILE 1
35# ifndef _FILE_OFFSET_BITS
36# define _FILE_OFFSET_BITS 64
37# endif
38# define _LARGEFILE_SOURCE 1
39#endif
drhbbd42a62004-05-22 17:41:58 +000040
drh9cbe6352005-11-29 03:13:21 +000041/*
42** standard include files.
43*/
44#include <sys/types.h>
45#include <sys/stat.h>
46#include <fcntl.h>
47#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000048#include <time.h>
drh19e2d372005-08-29 23:00:03 +000049#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000050#include <errno.h>
drh9cbe6352005-11-29 03:13:21 +000051
52/*
53** Macros used to determine whether or not to use threads. The
54** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
55** Posix threads and SQLITE_W32_THREADS is defined if we are
56** synchronizing using Win32 threads.
57*/
58#if defined(THREADSAFE) && THREADSAFE
59# include <pthread.h>
60# define SQLITE_UNIX_THREADS 1
61#endif
62
63/*
64** Default permissions when creating a new file
65*/
66#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
67# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
68#endif
69
70
71
72/*
drh054889e2005-11-30 03:20:31 +000073** The unixFile structure is subclass of OsFile specific for the unix
74** protability layer.
drh9cbe6352005-11-29 03:13:21 +000075*/
drh054889e2005-11-30 03:20:31 +000076typedef struct unixFile unixFile;
77struct unixFile {
78 IoMethod const *pMethod; /* Always the first entry */
drh9cbe6352005-11-29 03:13:21 +000079 struct openCnt *pOpen; /* Info about all open fd's on this inode */
80 struct lockInfo *pLock; /* Info about locks on this inode */
81 int h; /* The file descriptor */
82 unsigned char locktype; /* The type of lock held on this fd */
83 unsigned char isOpen; /* True if needs to be closed */
84 unsigned char fullSync; /* Use F_FULLSYNC if available */
85 int dirfd; /* File descriptor for the directory */
86#ifdef SQLITE_UNIX_THREADS
87 pthread_t tid; /* The thread authorized to use this OsFile */
88#endif
89};
90
drh0ccebe72005-06-07 22:22:50 +000091
92/*
93** Do not include any of the File I/O interface procedures if the
94** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
95** will be in-memory only)
96*/
97#ifndef SQLITE_OMIT_DISKIO
98
99
100/*
101** Define various macros that are missing from some systems.
102*/
drhbbd42a62004-05-22 17:41:58 +0000103#ifndef O_LARGEFILE
104# define O_LARGEFILE 0
105#endif
106#ifdef SQLITE_DISABLE_LFS
107# undef O_LARGEFILE
108# define O_LARGEFILE 0
109#endif
110#ifndef O_NOFOLLOW
111# define O_NOFOLLOW 0
112#endif
113#ifndef O_BINARY
114# define O_BINARY 0
115#endif
116
117/*
118** The DJGPP compiler environment looks mostly like Unix, but it
119** lacks the fcntl() system call. So redefine fcntl() to be something
120** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000121** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000122*/
123#ifdef __DJGPP__
124# define fcntl(A,B,C) 0
125#endif
126
127/*
drhbbd42a62004-05-22 17:41:58 +0000128** Include code that is common to all os_*.c files
129*/
130#include "os_common.h"
131
drh2b4b5962005-06-15 17:47:55 +0000132/*
133** The threadid macro resolves to the thread-id or to 0. Used for
134** testing and debugging only.
135*/
136#ifdef SQLITE_UNIX_THREADS
137#define threadid pthread_self()
138#else
139#define threadid 0
140#endif
141
142/*
143** Set or check the OsFile.tid field. This field is set when an OsFile
144** is first opened. All subsequent uses of the OsFile verify that the
145** same thread is operating on the OsFile. Some operating systems do
146** not allow locks to be overridden by other threads and that restriction
147** means that sqlite3* database handles cannot be moved from one thread
148** to another. This logic makes sure a user does not try to do that
149** by mistake.
150*/
drh91636d52005-11-24 23:14:00 +0000151#if defined(SQLITE_UNIX_THREADS) && !defined(SQLITE_ALLOW_XTHREAD_CONNECTIONS)
drh9cbe6352005-11-29 03:13:21 +0000152# define SET_THREADID(X) (X)->tid = pthread_self()
153# define CHECK_THREADID(X) (!pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000154#else
155# define SET_THREADID(X)
156# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000157#endif
158
drhbbd42a62004-05-22 17:41:58 +0000159/*
160** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
161** section 6.5.2.2 lines 483 through 490 specify that when a process
162** sets or clears a lock, that operation overrides any prior locks set
163** by the same process. It does not explicitly say so, but this implies
164** that it overrides locks set by the same process using a different
165** file descriptor. Consider this test case:
166**
167** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
168** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
169**
170** Suppose ./file1 and ./file2 are really the same file (because
171** one is a hard or symbolic link to the other) then if you set
172** an exclusive lock on fd1, then try to get an exclusive lock
173** on fd2, it works. I would have expected the second lock to
174** fail since there was already a lock on the file due to fd1.
175** But not so. Since both locks came from the same process, the
176** second overrides the first, even though they were on different
177** file descriptors opened on different file names.
178**
179** Bummer. If you ask me, this is broken. Badly broken. It means
180** that we cannot use POSIX locks to synchronize file access among
181** competing threads of the same process. POSIX locks will work fine
182** to synchronize access for threads in separate processes, but not
183** threads within the same process.
184**
185** To work around the problem, SQLite has to manage file locks internally
186** on its own. Whenever a new database is opened, we have to find the
187** specific inode of the database file (the inode is determined by the
188** st_dev and st_ino fields of the stat structure that fstat() fills in)
189** and check for locks already existing on that inode. When locks are
190** created or removed, we have to look at our own internal record of the
191** locks to see if another thread has previously set a lock on that same
192** inode.
193**
194** The OsFile structure for POSIX is no longer just an integer file
195** descriptor. It is now a structure that holds the integer file
196** descriptor and a pointer to a structure that describes the internal
197** locks on the corresponding inode. There is one locking structure
198** per inode, so if the same inode is opened twice, both OsFile structures
199** point to the same locking structure. The locking structure keeps
200** a reference count (so we will know when to delete it) and a "cnt"
201** field that tells us its internal lock status. cnt==0 means the
202** file is unlocked. cnt==-1 means the file has an exclusive lock.
203** cnt>0 means there are cnt shared locks on the file.
204**
205** Any attempt to lock or unlock a file first checks the locking
206** structure. The fcntl() system call is only invoked to set a
207** POSIX lock if the internal lock structure transitions between
208** a locked and an unlocked state.
209**
210** 2004-Jan-11:
211** More recent discoveries about POSIX advisory locks. (The more
212** I discover, the more I realize the a POSIX advisory locks are
213** an abomination.)
214**
215** If you close a file descriptor that points to a file that has locks,
216** all locks on that file that are owned by the current process are
217** released. To work around this problem, each OsFile structure contains
218** a pointer to an openCnt structure. There is one openCnt structure
219** per open inode, which means that multiple OsFiles can point to a single
220** openCnt. When an attempt is made to close an OsFile, if there are
221** other OsFiles open on the same inode that are holding locks, the call
222** to close() the file descriptor is deferred until all of the locks clear.
223** The openCnt structure keeps a list of file descriptors that need to
224** be closed and that list is walked (and cleared) when the last lock
225** clears.
226**
227** First, under Linux threads, because each thread has a separate
228** process ID, lock operations in one thread do not override locks
229** to the same file in other threads. Linux threads behave like
230** separate processes in this respect. But, if you close a file
231** descriptor in linux threads, all locks are cleared, even locks
232** on other threads and even though the other threads have different
233** process IDs. Linux threads is inconsistent in this respect.
234** (I'm beginning to think that linux threads is an abomination too.)
235** The consequence of this all is that the hash table for the lockInfo
236** structure has to include the process id as part of its key because
237** locks in different threads are treated as distinct. But the
238** openCnt structure should not include the process id in its
239** key because close() clears lock on all threads, not just the current
240** thread. Were it not for this goofiness in linux threads, we could
241** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000242**
243** 2004-Jun-28:
244** On some versions of linux, threads can override each others locks.
245** On others not. Sometimes you can change the behavior on the same
246** system by setting the LD_ASSUME_KERNEL environment variable. The
247** POSIX standard is silent as to which behavior is correct, as far
248** as I can tell, so other versions of unix might show the same
249** inconsistency. There is no little doubt in my mind that posix
250** advisory locks and linux threads are profoundly broken.
251**
252** To work around the inconsistencies, we have to test at runtime
253** whether or not threads can override each others locks. This test
254** is run once, the first time any lock is attempted. A static
255** variable is set to record the results of this test for future
256** use.
drhbbd42a62004-05-22 17:41:58 +0000257*/
258
259/*
260** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000261** to locate a particular lockInfo structure given its inode.
262**
263** If threads cannot override each others locks, then we set the
264** lockKey.tid field to the thread ID. If threads can override
265** each others locks then tid is always set to zero. tid is also
266** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000267*/
268struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000269 dev_t dev; /* Device number */
270 ino_t ino; /* Inode number */
271#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000272 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000273#endif
drhbbd42a62004-05-22 17:41:58 +0000274};
275
276/*
277** An instance of the following structure is allocated for each open
278** inode on each thread with a different process ID. (Threads have
279** different process IDs on linux, but not on most other unixes.)
280**
281** A single inode can have multiple file descriptors, so each OsFile
282** structure contains a pointer to an instance of this object and this
283** object keeps a count of the number of OsFiles pointing to it.
284*/
285struct lockInfo {
286 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000287 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000288 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000289 int nRef; /* Number of pointers to this structure */
290};
291
292/*
293** An instance of the following structure serves as the key used
294** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000295** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000296*/
297struct openKey {
298 dev_t dev; /* Device number */
299 ino_t ino; /* Inode number */
300};
301
302/*
303** An instance of the following structure is allocated for each open
304** inode. This structure keeps track of the number of locks on that
305** inode. If a close is attempted against an inode that is holding
306** locks, the close is deferred until all locks clear by adding the
307** file descriptor to be closed to the pending list.
308*/
309struct openCnt {
310 struct openKey key; /* The lookup key */
311 int nRef; /* Number of pointers to this structure */
312 int nLock; /* Number of outstanding locks */
313 int nPending; /* Number of pending close() operations */
314 int *aPending; /* Malloced space holding fd's awaiting a close() */
315};
316
317/*
318** These hash table maps inodes and process IDs into lockInfo and openCnt
319** structures. Access to these hash tables must be protected by a mutex.
320*/
321static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
322static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
323
drh5fdae772004-06-29 03:29:00 +0000324
325#ifdef SQLITE_UNIX_THREADS
326/*
327** This variable records whether or not threads can override each others
328** locks.
329**
330** 0: No. Threads cannot override each others locks.
331** 1: Yes. Threads can override each others locks.
332** -1: We don't know yet.
333*/
334static int threadsOverrideEachOthersLocks = -1;
335
336/*
337** This structure holds information passed into individual test
338** threads by the testThreadLockingBehavior() routine.
339*/
340struct threadTestData {
341 int fd; /* File to be locked */
342 struct flock lock; /* The locking operation */
343 int result; /* Result of the locking operation */
344};
345
drh2b4b5962005-06-15 17:47:55 +0000346#ifdef SQLITE_LOCK_TRACE
347/*
348** Print out information about all locking operations.
349**
350** This routine is used for troubleshooting locks on multithreaded
351** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
352** command-line option on the compiler. This code is normally
353** turnned off.
354*/
355static int lockTrace(int fd, int op, struct flock *p){
356 char *zOpName, *zType;
357 int s;
358 int savedErrno;
359 if( op==F_GETLK ){
360 zOpName = "GETLK";
361 }else if( op==F_SETLK ){
362 zOpName = "SETLK";
363 }else{
364 s = fcntl(fd, op, p);
365 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
366 return s;
367 }
368 if( p->l_type==F_RDLCK ){
369 zType = "RDLCK";
370 }else if( p->l_type==F_WRLCK ){
371 zType = "WRLCK";
372 }else if( p->l_type==F_UNLCK ){
373 zType = "UNLCK";
374 }else{
375 assert( 0 );
376 }
377 assert( p->l_whence==SEEK_SET );
378 s = fcntl(fd, op, p);
379 savedErrno = errno;
380 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
381 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
382 (int)p->l_pid, s);
383 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
384 struct flock l2;
385 l2 = *p;
386 fcntl(fd, F_GETLK, &l2);
387 if( l2.l_type==F_RDLCK ){
388 zType = "RDLCK";
389 }else if( l2.l_type==F_WRLCK ){
390 zType = "WRLCK";
391 }else if( l2.l_type==F_UNLCK ){
392 zType = "UNLCK";
393 }else{
394 assert( 0 );
395 }
396 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
397 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
398 }
399 errno = savedErrno;
400 return s;
401}
402#define fcntl lockTrace
403#endif /* SQLITE_LOCK_TRACE */
404
drh5fdae772004-06-29 03:29:00 +0000405/*
406** The testThreadLockingBehavior() routine launches two separate
407** threads on this routine. This routine attempts to lock a file
408** descriptor then returns. The success or failure of that attempt
409** allows the testThreadLockingBehavior() procedure to determine
410** whether or not threads can override each others locks.
411*/
412static void *threadLockingTest(void *pArg){
413 struct threadTestData *pData = (struct threadTestData*)pArg;
414 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
415 return pArg;
416}
417
418/*
419** This procedure attempts to determine whether or not threads
420** can override each others locks then sets the
421** threadsOverrideEachOthersLocks variable appropriately.
422*/
423static void testThreadLockingBehavior(fd_orig){
424 int fd;
425 struct threadTestData d[2];
426 pthread_t t[2];
427
428 fd = dup(fd_orig);
429 if( fd<0 ) return;
430 memset(d, 0, sizeof(d));
431 d[0].fd = fd;
432 d[0].lock.l_type = F_RDLCK;
433 d[0].lock.l_len = 1;
434 d[0].lock.l_start = 0;
435 d[0].lock.l_whence = SEEK_SET;
436 d[1] = d[0];
437 d[1].lock.l_type = F_WRLCK;
438 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
439 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
440 pthread_join(t[0], 0);
441 pthread_join(t[1], 0);
442 close(fd);
443 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
444}
445#endif /* SQLITE_UNIX_THREADS */
446
drhbbd42a62004-05-22 17:41:58 +0000447/*
448** Release a lockInfo structure previously allocated by findLockInfo().
449*/
450static void releaseLockInfo(struct lockInfo *pLock){
451 pLock->nRef--;
452 if( pLock->nRef==0 ){
453 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
454 sqliteFree(pLock);
455 }
456}
457
458/*
459** Release a openCnt structure previously allocated by findLockInfo().
460*/
461static void releaseOpenCnt(struct openCnt *pOpen){
462 pOpen->nRef--;
463 if( pOpen->nRef==0 ){
464 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
465 sqliteFree(pOpen->aPending);
466 sqliteFree(pOpen);
467 }
468}
469
470/*
471** Given a file descriptor, locate lockInfo and openCnt structures that
472** describes that file descriptor. Create a new ones if necessary. The
473** return values might be unset if an error occurs.
474**
475** Return the number of errors.
476*/
drh38f82712004-06-18 17:10:16 +0000477static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000478 int fd, /* The file descriptor used in the key */
479 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000480 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000481){
482 int rc;
483 struct lockKey key1;
484 struct openKey key2;
485 struct stat statbuf;
486 struct lockInfo *pLock;
487 struct openCnt *pOpen;
488 rc = fstat(fd, &statbuf);
489 if( rc!=0 ) return 1;
490 memset(&key1, 0, sizeof(key1));
491 key1.dev = statbuf.st_dev;
492 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000493#ifdef SQLITE_UNIX_THREADS
494 if( threadsOverrideEachOthersLocks<0 ){
495 testThreadLockingBehavior(fd);
496 }
497 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
498#endif
drhbbd42a62004-05-22 17:41:58 +0000499 memset(&key2, 0, sizeof(key2));
500 key2.dev = statbuf.st_dev;
501 key2.ino = statbuf.st_ino;
502 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
503 if( pLock==0 ){
504 struct lockInfo *pOld;
505 pLock = sqliteMallocRaw( sizeof(*pLock) );
506 if( pLock==0 ) return 1;
507 pLock->key = key1;
508 pLock->nRef = 1;
509 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000510 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000511 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
512 if( pOld!=0 ){
513 assert( pOld==pLock );
514 sqliteFree(pLock);
515 return 1;
516 }
517 }else{
518 pLock->nRef++;
519 }
520 *ppLock = pLock;
521 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
522 if( pOpen==0 ){
523 struct openCnt *pOld;
524 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
525 if( pOpen==0 ){
526 releaseLockInfo(pLock);
527 return 1;
528 }
529 pOpen->key = key2;
530 pOpen->nRef = 1;
531 pOpen->nLock = 0;
532 pOpen->nPending = 0;
533 pOpen->aPending = 0;
534 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
535 if( pOld!=0 ){
536 assert( pOld==pOpen );
537 sqliteFree(pOpen);
538 releaseLockInfo(pLock);
539 return 1;
540 }
541 }else{
542 pOpen->nRef++;
543 }
544 *ppOpen = pOpen;
545 return 0;
546}
547
548/*
549** Delete the named file
550*/
drh9c06c952005-11-26 00:25:00 +0000551static int unixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000552 unlink(zFilename);
553 return SQLITE_OK;
554}
555
556/*
557** Return TRUE if the named file exists.
558*/
drh9c06c952005-11-26 00:25:00 +0000559static int unixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000560 return access(zFilename, 0)==0;
561}
562
drh054889e2005-11-30 03:20:31 +0000563/* Forward declaration */
564static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000565
566/*
drhbbd42a62004-05-22 17:41:58 +0000567** Attempt to open a file for both reading and writing. If that
568** fails, try opening it read-only. If the file does not exist,
569** try to create it.
570**
571** On success, a handle for the open file is written to *id
572** and *pReadonly is set to 0 if the file was opened for reading and
573** writing or 1 if the file was opened read-only. The function returns
574** SQLITE_OK.
575**
576** On failure, the function returns SQLITE_CANTOPEN and leaves
577** *id and *pReadonly unchanged.
578*/
drh9c06c952005-11-26 00:25:00 +0000579static int unixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000580 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000581 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000582 int *pReadonly
583){
584 int rc;
drh054889e2005-11-30 03:20:31 +0000585 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000586
587 assert( 0==*pId );
588 f.dirfd = -1;
589 SET_THREADID(&f);
590 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000591 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000592 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000593#ifdef EISDIR
594 if( errno==EISDIR ){
595 return SQLITE_CANTOPEN;
596 }
597#endif
drh9cbe6352005-11-29 03:13:21 +0000598 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
599 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000600 return SQLITE_CANTOPEN;
601 }
602 *pReadonly = 1;
603 }else{
604 *pReadonly = 0;
605 }
drh054889e2005-11-30 03:20:31 +0000606 sqlite3Os.xEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000607 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh054889e2005-11-30 03:20:31 +0000608 sqlite3Os.xLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000609 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000610 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000611 return SQLITE_NOMEM;
612 }
drh9cbe6352005-11-29 03:13:21 +0000613 f.locktype = 0;
614 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000615 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000616}
617
618
619/*
620** Attempt to open a new file for exclusive access by this process.
621** The file will be opened for both reading and writing. To avoid
622** a potential security problem, we do not allow the file to have
623** previously existed. Nor do we allow the file to be a symbolic
624** link.
625**
626** If delFlag is true, then make arrangements to automatically delete
627** the file when it is closed.
628**
629** On success, write the file handle into *id and return SQLITE_OK.
630**
631** On failure, return SQLITE_CANTOPEN.
632*/
drh9cbe6352005-11-29 03:13:21 +0000633static int unixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000634 int rc;
drh054889e2005-11-30 03:20:31 +0000635 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000636
637 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000638 if( access(zFilename, 0)==0 ){
639 return SQLITE_CANTOPEN;
640 }
drh9cbe6352005-11-29 03:13:21 +0000641 SET_THREADID(&f);
642 f.dirfd = -1;
643 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000644 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
645 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000646 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000647 return SQLITE_CANTOPEN;
648 }
drh054889e2005-11-30 03:20:31 +0000649 sqlite3Os.xEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000650 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh054889e2005-11-30 03:20:31 +0000651 sqlite3Os.xLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000652 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000653 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000654 unlink(zFilename);
655 return SQLITE_NOMEM;
656 }
drh9cbe6352005-11-29 03:13:21 +0000657 f.locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000658 if( delFlag ){
659 unlink(zFilename);
660 }
drh9cbe6352005-11-29 03:13:21 +0000661 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000662 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000663}
664
665/*
666** Attempt to open a new file for read-only access.
667**
668** On success, write the file handle into *id and return SQLITE_OK.
669**
670** On failure, return SQLITE_CANTOPEN.
671*/
drh9cbe6352005-11-29 03:13:21 +0000672static int unixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000673 int rc;
drh054889e2005-11-30 03:20:31 +0000674 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000675
676 assert( 0==*pId );
677 SET_THREADID(&f);
678 f.dirfd = -1;
679 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
680 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000681 return SQLITE_CANTOPEN;
682 }
drh054889e2005-11-30 03:20:31 +0000683 sqlite3Os.xEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000684 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh054889e2005-11-30 03:20:31 +0000685 sqlite3Os.xLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000686 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000687 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000688 return SQLITE_NOMEM;
689 }
drh9cbe6352005-11-29 03:13:21 +0000690 f.locktype = 0;
691 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
danielk1977261919c2005-12-06 12:52:59 +0000692
drh054889e2005-11-30 03:20:31 +0000693 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000694}
695
696/*
697** Attempt to open a file descriptor for the directory that contains a
698** file. This file descriptor can be used to fsync() the directory
699** in order to make sure the creation of a new file is actually written
700** to disk.
701**
702** This routine is only meaningful for Unix. It is a no-op under
703** windows since windows does not support hard links.
704**
drh9cbe6352005-11-29 03:13:21 +0000705** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000706** updated with the new directory file descriptor and SQLITE_OK is
707** returned.
708**
709** On failure, the function returns SQLITE_CANTOPEN and leaves
710** *id unchanged.
711*/
drh9c06c952005-11-26 00:25:00 +0000712static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000713 OsFile *id,
714 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000715){
drh054889e2005-11-30 03:20:31 +0000716 unixFile *pFile = (unixFile*)id;
717 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000718 /* Do not open the directory if the corresponding file is not already
719 ** open. */
720 return SQLITE_CANTOPEN;
721 }
drh054889e2005-11-30 03:20:31 +0000722 SET_THREADID(pFile);
723 assert( pFile->dirfd<0 );
724 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
725 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000726 return SQLITE_CANTOPEN;
727 }
drh054889e2005-11-30 03:20:31 +0000728 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000729 return SQLITE_OK;
730}
731
732/*
drhab3f9fe2004-08-14 17:10:10 +0000733** If the following global variable points to a string which is the
734** name of a directory, then that directory will be used to store
735** temporary files.
736*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000737char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000738
739/*
drhbbd42a62004-05-22 17:41:58 +0000740** Create a temporary file name in zBuf. zBuf must be big enough to
741** hold at least SQLITE_TEMPNAME_SIZE characters.
742*/
drh9c06c952005-11-26 00:25:00 +0000743static int unixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000744 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000745 0,
drhbbd42a62004-05-22 17:41:58 +0000746 "/var/tmp",
747 "/usr/tmp",
748 "/tmp",
749 ".",
750 };
drh57196282004-10-06 15:41:16 +0000751 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000752 "abcdefghijklmnopqrstuvwxyz"
753 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
754 "0123456789";
755 int i, j;
756 struct stat buf;
757 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000758 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000759 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000760 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000761 if( stat(azDirs[i], &buf) ) continue;
762 if( !S_ISDIR(buf.st_mode) ) continue;
763 if( access(azDirs[i], 07) ) continue;
764 zDir = azDirs[i];
765 break;
766 }
767 do{
768 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
769 j = strlen(zBuf);
770 sqlite3Randomness(15, &zBuf[j]);
771 for(i=0; i<15; i++, j++){
772 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
773 }
774 zBuf[j] = 0;
775 }while( access(zBuf,0)==0 );
776 return SQLITE_OK;
777}
778
779/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000780** Check that a given pathname is a directory and is writable
781**
782*/
drh9c06c952005-11-26 00:25:00 +0000783static int unixIsDirWritable(char *zBuf){
784#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000785 struct stat buf;
786 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000787 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000788 if( stat(zBuf, &buf) ) return 0;
789 if( !S_ISDIR(buf.st_mode) ) return 0;
790 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000791#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000792 return 1;
793}
794
795/*
drhbbd42a62004-05-22 17:41:58 +0000796** Read data from a file into a buffer. Return SQLITE_OK if all
797** bytes were read successfully and SQLITE_IOERR if anything goes
798** wrong.
799*/
drh9c06c952005-11-26 00:25:00 +0000800static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000801 int got;
drh9cbe6352005-11-29 03:13:21 +0000802 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000803 SimulateIOError(SQLITE_IOERR);
804 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000805 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000806 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000807 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
808 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000809 SEEK(0);
810 /* if( got<0 ) got = 0; */
811 if( got==amt ){
812 return SQLITE_OK;
813 }else{
814 return SQLITE_IOERR;
815 }
816}
817
818/*
819** Write data from a buffer into a file. Return SQLITE_OK on success
820** or some other error code on failure.
821*/
drh9c06c952005-11-26 00:25:00 +0000822static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000823 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000824 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000825 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000826 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000827 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000828 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000829 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000830 amt -= wrote;
831 pBuf = &((char*)pBuf)[wrote];
832 }
833 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000834 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
835 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000836 SEEK(0);
837 if( amt>0 ){
838 return SQLITE_FULL;
839 }
840 return SQLITE_OK;
841}
842
843/*
844** Move the read/write pointer in a file.
845*/
drh9c06c952005-11-26 00:25:00 +0000846static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000847 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000848 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000849#ifdef SQLITE_TEST
850 if( offset ) SimulateDiskfullError
851#endif
drh054889e2005-11-30 03:20:31 +0000852 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000853 return SQLITE_OK;
854}
855
drhb851b2c2005-03-10 14:11:12 +0000856#ifdef SQLITE_TEST
857/*
858** Count the number of fullsyncs and normal syncs. This is used to test
859** that syncs and fullsyncs are occuring at the right times.
860*/
861int sqlite3_sync_count = 0;
862int sqlite3_fullsync_count = 0;
863#endif
864
drhf2f23912005-10-05 10:29:36 +0000865/*
866** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
867** Otherwise use fsync() in its place.
868*/
869#ifndef HAVE_FDATASYNC
870# define fdatasync fsync
871#endif
872
drhb851b2c2005-03-10 14:11:12 +0000873
drhbbd42a62004-05-22 17:41:58 +0000874/*
drhdd809b02004-07-17 21:44:57 +0000875** The fsync() system call does not work as advertised on many
876** unix systems. The following procedure is an attempt to make
877** it work better.
drh1398ad32005-01-19 23:24:50 +0000878**
879** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
880** for testing when we want to run through the test suite quickly.
881** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
882** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
883** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000884*/
drheb796a72005-09-08 12:38:41 +0000885static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000886 int rc;
drhb851b2c2005-03-10 14:11:12 +0000887
888 /* Record the number of times that we do a normal fsync() and
889 ** FULLSYNC. This is used during testing to verify that this procedure
890 ** gets called with the correct arguments.
891 */
892#ifdef SQLITE_TEST
893 if( fullSync ) sqlite3_fullsync_count++;
894 sqlite3_sync_count++;
895#endif
896
897 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
898 ** no-op
899 */
900#ifdef SQLITE_NO_SYNC
901 rc = SQLITE_OK;
902#else
903
drhdd809b02004-07-17 21:44:57 +0000904#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000905 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000906 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +0000907 }else{
908 rc = 1;
909 }
910 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +0000911 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +0000912
drhc035e6e2005-09-22 15:45:04 +0000913#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +0000914 if( dataOnly ){
915 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000916 }else{
drheb796a72005-09-08 12:38:41 +0000917 rc = fsync(fd);
918 }
drhf30cc942005-03-11 17:52:34 +0000919#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +0000920#endif /* defined(SQLITE_NO_SYNC) */
921
drhdd809b02004-07-17 21:44:57 +0000922 return rc;
923}
924
925/*
drhbbd42a62004-05-22 17:41:58 +0000926** Make sure all writes to a particular file are committed to disk.
927**
drheb796a72005-09-08 12:38:41 +0000928** If dataOnly==0 then both the file itself and its metadata (file
929** size, access time, etc) are synced. If dataOnly!=0 then only the
930** file data is synced.
931**
drhbbd42a62004-05-22 17:41:58 +0000932** Under Unix, also make sure that the directory entry for the file
933** has been created by fsync-ing the directory that contains the file.
934** If we do not do this and we encounter a power failure, the directory
935** entry for the journal might not exist after we reboot. The next
936** SQLite to access the file will not know that the journal exists (because
937** the directory entry for the journal was never created) and the transaction
938** will not roll back - possibly leading to database corruption.
939*/
drh9c06c952005-11-26 00:25:00 +0000940static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +0000941 unixFile *pFile = (unixFile*)id;
942 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +0000943 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +0000944 TRACE2("SYNC %-3d\n", pFile->h);
945 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +0000946 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000947 }
drh054889e2005-11-30 03:20:31 +0000948 if( pFile->dirfd>=0 ){
949 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +0000950#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +0000951 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
danielk19770964b232005-11-25 08:47:57 +0000952 return SQLITE_IOERR;
953 }
danielk1977d7c03f72005-11-25 10:38:22 +0000954#endif
drh054889e2005-11-30 03:20:31 +0000955 close(pFile->dirfd); /* Only need to sync once, so close the directory */
956 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +0000957 }
drha2854222004-06-17 19:04:17 +0000958 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000959}
960
961/*
danielk1977962398d2004-06-14 09:35:16 +0000962** Sync the directory zDirname. This is a no-op on operating systems other
963** than UNIX.
drhb851b2c2005-03-10 14:11:12 +0000964**
965** This is used to make sure the master journal file has truely been deleted
966** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +0000967** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +0000968*/
drh9c06c952005-11-26 00:25:00 +0000969static int unixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +0000970#ifdef SQLITE_DISABLE_DIRSYNC
971 return SQLITE_OK;
972#else
danielk1977962398d2004-06-14 09:35:16 +0000973 int fd;
974 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000975 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +0000976 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +0000977 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000978 if( fd<0 ){
979 return SQLITE_CANTOPEN;
980 }
981 r = fsync(fd);
982 close(fd);
983 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +0000984#endif
danielk1977962398d2004-06-14 09:35:16 +0000985}
986
987/*
drhbbd42a62004-05-22 17:41:58 +0000988** Truncate an open file to a specified size
989*/
drh9c06c952005-11-26 00:25:00 +0000990static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +0000991 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000992 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +0000993 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000994}
995
996/*
997** Determine the current size of a file in bytes
998*/
drh9c06c952005-11-26 00:25:00 +0000999static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001000 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001001 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001002 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001003 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001004 return SQLITE_IOERR;
1005 }
1006 *pSize = buf.st_size;
1007 return SQLITE_OK;
1008}
1009
danielk19779a1d0ab2004-06-01 14:09:28 +00001010/*
danielk197713adf8a2004-06-03 16:08:41 +00001011** This routine checks if there is a RESERVED lock held on the specified
1012** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001013** non-zero. If the file is unlocked or holds only SHARED locks, then
1014** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001015*/
drh9c06c952005-11-26 00:25:00 +00001016static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001017 int r = 0;
drh054889e2005-11-30 03:20:31 +00001018 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001019
drh054889e2005-11-30 03:20:31 +00001020 assert( pFile );
1021 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
1022 sqlite3Os.xEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001023
1024 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001025 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001026 r = 1;
1027 }
1028
drh2ac3ee92004-06-07 16:27:46 +00001029 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001030 */
1031 if( !r ){
1032 struct flock lock;
1033 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001034 lock.l_start = RESERVED_BYTE;
1035 lock.l_len = 1;
1036 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001037 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001038 if( lock.l_type!=F_UNLCK ){
1039 r = 1;
1040 }
1041 }
1042
drh054889e2005-11-30 03:20:31 +00001043 sqlite3Os.xLeaveMutex();
1044 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001045
1046 return r;
1047}
1048
danielk19772b444852004-06-29 07:45:33 +00001049#ifdef SQLITE_DEBUG
1050/*
1051** Helper function for printing out trace information from debugging
1052** binaries. This returns the string represetation of the supplied
1053** integer lock-type.
1054*/
drh054889e2005-11-30 03:20:31 +00001055static const char *locktypeName(int locktype){
danielk19772b444852004-06-29 07:45:33 +00001056 switch( locktype ){
1057 case NO_LOCK: return "NONE";
1058 case SHARED_LOCK: return "SHARED";
1059 case RESERVED_LOCK: return "RESERVED";
1060 case PENDING_LOCK: return "PENDING";
1061 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
1062 }
1063 return "ERROR";
1064}
1065#endif
1066
danielk197713adf8a2004-06-03 16:08:41 +00001067/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001068** Lock the file with the lock specified by parameter locktype - one
1069** of the following:
1070**
drh2ac3ee92004-06-07 16:27:46 +00001071** (1) SHARED_LOCK
1072** (2) RESERVED_LOCK
1073** (3) PENDING_LOCK
1074** (4) EXCLUSIVE_LOCK
1075**
drhb3e04342004-06-08 00:47:47 +00001076** Sometimes when requesting one lock state, additional lock states
1077** are inserted in between. The locking might fail on one of the later
1078** transitions leaving the lock state different from what it started but
1079** still short of its goal. The following chart shows the allowed
1080** transitions and the inserted intermediate states:
1081**
1082** UNLOCKED -> SHARED
1083** SHARED -> RESERVED
1084** SHARED -> (PENDING) -> EXCLUSIVE
1085** RESERVED -> (PENDING) -> EXCLUSIVE
1086** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001087**
drha6abd042004-06-09 17:37:22 +00001088** This routine will only increase a lock. Use the sqlite3OsUnlock()
1089** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001090*/
drh9c06c952005-11-26 00:25:00 +00001091static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001092 /* The following describes the implementation of the various locks and
1093 ** lock transitions in terms of the POSIX advisory shared and exclusive
1094 ** lock primitives (called read-locks and write-locks below, to avoid
1095 ** confusion with SQLite lock names). The algorithms are complicated
1096 ** slightly in order to be compatible with windows systems simultaneously
1097 ** accessing the same database file, in case that is ever required.
1098 **
1099 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1100 ** byte', each single bytes at well known offsets, and the 'shared byte
1101 ** range', a range of 510 bytes at a well known offset.
1102 **
1103 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1104 ** byte'. If this is successful, a random byte from the 'shared byte
1105 ** range' is read-locked and the lock on the 'pending byte' released.
1106 **
danielk197790ba3bd2004-06-25 08:32:25 +00001107 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1108 ** A RESERVED lock is implemented by grabbing a write-lock on the
1109 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001110 **
1111 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001112 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1113 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1114 ** obtained, but existing SHARED locks are allowed to persist. A process
1115 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1116 ** This property is used by the algorithm for rolling back a journal file
1117 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001118 **
danielk197790ba3bd2004-06-25 08:32:25 +00001119 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1120 ** implemented by obtaining a write-lock on the entire 'shared byte
1121 ** range'. Since all other locks require a read-lock on one of the bytes
1122 ** within this range, this ensures that no other locks are held on the
1123 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001124 **
1125 ** The reason a single byte cannot be used instead of the 'shared byte
1126 ** range' is that some versions of windows do not support read-locks. By
1127 ** locking a random byte from a range, concurrent SHARED locks may exist
1128 ** even if the locking primitive used is always a write-lock.
1129 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001130 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001131 unixFile *pFile = (unixFile*)id;
1132 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001133 struct flock lock;
1134 int s;
1135
drh054889e2005-11-30 03:20:31 +00001136 assert( pFile );
1137 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1138 locktypeName(locktype), locktypeName(pFile->locktype),
1139 locktypeName(pLock->locktype), pLock->cnt , getpid());
1140 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001141
1142 /* If there is already a lock of this type or more restrictive on the
1143 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh054889e2005-11-30 03:20:31 +00001144 ** sqlite3Os.xEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001145 */
drh054889e2005-11-30 03:20:31 +00001146 if( pFile->locktype>=locktype ){
1147 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1148 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001149 return SQLITE_OK;
1150 }
1151
drhb3e04342004-06-08 00:47:47 +00001152 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001153 */
drh054889e2005-11-30 03:20:31 +00001154 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001155 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001156 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001157
drh054889e2005-11-30 03:20:31 +00001158 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001159 */
drh054889e2005-11-30 03:20:31 +00001160 sqlite3Os.xEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001161
1162 /* If some thread using this PID has a lock via a different OsFile*
1163 ** handle that precludes the requested lock, return BUSY.
1164 */
drh054889e2005-11-30 03:20:31 +00001165 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001166 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001167 ){
1168 rc = SQLITE_BUSY;
1169 goto end_lock;
1170 }
1171
1172 /* If a SHARED lock is requested, and some thread using this PID already
1173 ** has a SHARED or RESERVED lock, then increment reference counts and
1174 ** return SQLITE_OK.
1175 */
1176 if( locktype==SHARED_LOCK &&
1177 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1178 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001179 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001180 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001181 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001182 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001183 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001184 goto end_lock;
1185 }
1186
danielk197713adf8a2004-06-03 16:08:41 +00001187 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001188
danielk19779a1d0ab2004-06-01 14:09:28 +00001189 lock.l_whence = SEEK_SET;
1190
drh3cde3bb2004-06-12 02:17:14 +00001191 /* A PENDING lock is needed before acquiring a SHARED lock and before
1192 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1193 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001194 */
drh3cde3bb2004-06-12 02:17:14 +00001195 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001196 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001197 ){
danielk1977489468c2004-06-28 08:25:47 +00001198 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001199 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001200 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001201 if( s ){
1202 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1203 goto end_lock;
1204 }
drh3cde3bb2004-06-12 02:17:14 +00001205 }
1206
1207
1208 /* If control gets to this point, then actually go ahead and make
1209 ** operating system calls for the specified lock.
1210 */
1211 if( locktype==SHARED_LOCK ){
1212 assert( pLock->cnt==0 );
1213 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001214
drh2ac3ee92004-06-07 16:27:46 +00001215 /* Now get the read-lock */
1216 lock.l_start = SHARED_FIRST;
1217 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001218 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001219
1220 /* Drop the temporary PENDING lock */
1221 lock.l_start = PENDING_BYTE;
1222 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001224 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001225 rc = SQLITE_IOERR; /* This should never happen */
1226 goto end_lock;
1227 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001229 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1230 }else{
drh054889e2005-11-30 03:20:31 +00001231 pFile->locktype = SHARED_LOCK;
1232 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001233 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001234 }
drh3cde3bb2004-06-12 02:17:14 +00001235 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1236 /* We are trying for an exclusive lock but another thread in this
1237 ** same process is still holding a shared lock. */
1238 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001239 }else{
drh3cde3bb2004-06-12 02:17:14 +00001240 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001241 ** assumed that there is a SHARED or greater lock on the file
1242 ** already.
1243 */
drh054889e2005-11-30 03:20:31 +00001244 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001245 lock.l_type = F_WRLCK;
1246 switch( locktype ){
1247 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001248 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001249 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001250 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001251 lock.l_start = SHARED_FIRST;
1252 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001253 break;
1254 default:
1255 assert(0);
1256 }
drh054889e2005-11-30 03:20:31 +00001257 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001258 if( s ){
1259 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1260 }
drhbbd42a62004-05-22 17:41:58 +00001261 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001262
danielk1977ecb2a962004-06-02 06:30:16 +00001263 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001264 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001265 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001266 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001267 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001268 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001269 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001270
1271end_lock:
drh054889e2005-11-30 03:20:31 +00001272 sqlite3Os.xLeaveMutex();
1273 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001274 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001275 return rc;
1276}
1277
1278/*
drh054889e2005-11-30 03:20:31 +00001279** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001280** must be either NO_LOCK or SHARED_LOCK.
1281**
1282** If the locking level of the file descriptor is already at or below
1283** the requested locking level, this routine is a no-op.
1284**
drh9c105bb2004-10-02 20:38:28 +00001285** It is not possible for this routine to fail if the second argument
1286** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1287** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001288*/
drh9c06c952005-11-26 00:25:00 +00001289static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001290 struct lockInfo *pLock;
1291 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001292 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001293 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001294
drh054889e2005-11-30 03:20:31 +00001295 assert( pFile );
1296 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1297 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
1298 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drha6abd042004-06-09 17:37:22 +00001299
1300 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001301 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001302 return SQLITE_OK;
1303 }
drh054889e2005-11-30 03:20:31 +00001304 sqlite3Os.xEnterMutex();
1305 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001306 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001307 if( pFile->locktype>SHARED_LOCK ){
1308 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001309 if( locktype==SHARED_LOCK ){
1310 lock.l_type = F_RDLCK;
1311 lock.l_whence = SEEK_SET;
1312 lock.l_start = SHARED_FIRST;
1313 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001314 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001315 /* This should never happen */
1316 rc = SQLITE_IOERR;
1317 }
1318 }
drhbbd42a62004-05-22 17:41:58 +00001319 lock.l_type = F_UNLCK;
1320 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001321 lock.l_start = PENDING_BYTE;
1322 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001323 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001324 pLock->locktype = SHARED_LOCK;
1325 }else{
1326 rc = SQLITE_IOERR; /* This should never happen */
1327 }
drhbbd42a62004-05-22 17:41:58 +00001328 }
drha6abd042004-06-09 17:37:22 +00001329 if( locktype==NO_LOCK ){
1330 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001331
drha6abd042004-06-09 17:37:22 +00001332 /* Decrement the shared lock counter. Release the lock using an
1333 ** OS call only when all threads in this same process have released
1334 ** the lock.
1335 */
1336 pLock->cnt--;
1337 if( pLock->cnt==0 ){
1338 lock.l_type = F_UNLCK;
1339 lock.l_whence = SEEK_SET;
1340 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001341 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001342 pLock->locktype = NO_LOCK;
1343 }else{
1344 rc = SQLITE_IOERR; /* This should never happen */
1345 }
drha6abd042004-06-09 17:37:22 +00001346 }
1347
drhbbd42a62004-05-22 17:41:58 +00001348 /* Decrement the count of locks against this same file. When the
1349 ** count reaches zero, close any other file descriptors whose close
1350 ** was deferred because of outstanding locks.
1351 */
drh054889e2005-11-30 03:20:31 +00001352 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001353 pOpen->nLock--;
1354 assert( pOpen->nLock>=0 );
1355 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1356 int i;
1357 for(i=0; i<pOpen->nPending; i++){
1358 close(pOpen->aPending[i]);
1359 }
1360 sqliteFree(pOpen->aPending);
1361 pOpen->nPending = 0;
1362 pOpen->aPending = 0;
1363 }
1364 }
drh054889e2005-11-30 03:20:31 +00001365 sqlite3Os.xLeaveMutex();
1366 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001367 return rc;
drhbbd42a62004-05-22 17:41:58 +00001368}
1369
1370/*
danielk1977e3026632004-06-22 11:29:02 +00001371** Close a file.
1372*/
drh9cbe6352005-11-29 03:13:21 +00001373static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001374 unixFile *id = (unixFile*)*pId;
drh9cbe6352005-11-29 03:13:21 +00001375 if( !id ) return SQLITE_OK;
drh2b4b5962005-06-15 17:47:55 +00001376 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
drh054889e2005-11-30 03:20:31 +00001377 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001378 if( id->dirfd>=0 ) close(id->dirfd);
1379 id->dirfd = -1;
drh054889e2005-11-30 03:20:31 +00001380 sqlite3Os.xEnterMutex();
danielk1977e3026632004-06-22 11:29:02 +00001381 if( id->pOpen->nLock ){
1382 /* If there are outstanding locks, do not actually close the file just
1383 ** yet because that would clear those locks. Instead, add the file
1384 ** descriptor to pOpen->aPending. It will be automatically closed when
1385 ** the last lock is cleared.
1386 */
1387 int *aNew;
1388 struct openCnt *pOpen = id->pOpen;
drhad81e872005-08-21 21:45:01 +00001389 aNew = sqliteRealloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001390 if( aNew==0 ){
1391 /* If a malloc fails, just leak the file descriptor */
1392 }else{
1393 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001394 pOpen->aPending[pOpen->nPending] = id->h;
1395 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001396 }
1397 }else{
1398 /* There are no outstanding locks so we can close the file immediately */
1399 close(id->h);
1400 }
1401 releaseLockInfo(id->pLock);
1402 releaseOpenCnt(id->pOpen);
drh054889e2005-11-30 03:20:31 +00001403 sqlite3Os.xLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001404 id->isOpen = 0;
1405 TRACE2("CLOSE %-3d\n", id->h);
1406 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001407 sqliteFree(id);
1408 *pId = 0;
danielk1977e3026632004-06-22 11:29:02 +00001409 return SQLITE_OK;
1410}
1411
1412/*
drh0ccebe72005-06-07 22:22:50 +00001413** Turn a relative pathname into a full pathname. Return a pointer
1414** to the full pathname stored in space obtained from sqliteMalloc().
1415** The calling function is responsible for freeing this space once it
1416** is no longer needed.
1417*/
drh9c06c952005-11-26 00:25:00 +00001418static char *unixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001419 char *zFull = 0;
1420 if( zRelative[0]=='/' ){
1421 sqlite3SetString(&zFull, zRelative, (char*)0);
1422 }else{
drh79158e12005-09-06 21:40:45 +00001423 char *zBuf = sqliteMalloc(5000);
1424 if( zBuf==0 ){
1425 return 0;
1426 }
drh0ccebe72005-06-07 22:22:50 +00001427 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001428 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001429 (char*)0);
drh79158e12005-09-06 21:40:45 +00001430 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001431 }
1432 return zFull;
1433}
1434
drh18839212005-11-26 03:43:23 +00001435/*
drh9cbe6352005-11-29 03:13:21 +00001436** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001437*/
drh9cbe6352005-11-29 03:13:21 +00001438static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001439 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001440}
1441
1442/*
1443** Return the underlying file handle for an OsFile
1444*/
1445static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001446 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001447}
1448
1449/*
1450** Return an integer that indices the type of lock currently held
1451** by this handle. (Used for testing and analysis only.)
1452*/
1453static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001454 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001455}
drh0ccebe72005-06-07 22:22:50 +00001456
drh9c06c952005-11-26 00:25:00 +00001457/*
drh054889e2005-11-30 03:20:31 +00001458** This vector defines all the methods that can operate on an OsFile
1459** for unix.
drh9c06c952005-11-26 00:25:00 +00001460*/
drh054889e2005-11-30 03:20:31 +00001461static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001462 unixClose,
drh054889e2005-11-30 03:20:31 +00001463 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001464 unixRead,
1465 unixWrite,
1466 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001467 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001468 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001469 unixSetFullSync,
1470 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001471 unixFileSize,
1472 unixLock,
1473 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001474 unixLockState,
drh054889e2005-11-30 03:20:31 +00001475 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001476};
1477
drh054889e2005-11-30 03:20:31 +00001478/*
1479** Allocate memory for a unixFile. Initialize the new unixFile
1480** to the value given in pInit and return a pointer to the new
1481** OsFile. If we run out of memory, close the file and return NULL.
1482*/
1483static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1484 unixFile *pNew;
1485 pNew = sqliteMalloc( sizeof(unixFile) );
1486 if( pNew==0 ){
1487 close(pInit->h);
danielk19772e588c72005-12-09 14:25:08 +00001488 releaseLockInfo(pInit->pLock);
1489 releaseOpenCnt(pInit->pOpen);
drh054889e2005-11-30 03:20:31 +00001490 *pId = 0;
1491 return SQLITE_NOMEM;
1492 }else{
1493 *pNew = *pInit;
1494 pNew->pMethod = &sqlite3UnixIoMethod;
1495 *pId = (OsFile*)pNew;
1496 OpenCounter(+1);
1497 return SQLITE_OK;
1498 }
1499}
1500
drh9c06c952005-11-26 00:25:00 +00001501
drh0ccebe72005-06-07 22:22:50 +00001502#endif /* SQLITE_OMIT_DISKIO */
1503/***************************************************************************
1504** Everything above deals with file I/O. Everything that follows deals
1505** with other miscellanous aspects of the operating system interface
1506****************************************************************************/
1507
1508
1509/*
drhbbd42a62004-05-22 17:41:58 +00001510** Get information to seed the random number generator. The seed
1511** is written into the buffer zBuf[256]. The calling function must
1512** supply a sufficiently large buffer.
1513*/
drh054889e2005-11-30 03:20:31 +00001514static int unixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001515 /* We have to initialize zBuf to prevent valgrind from reporting
1516 ** errors. The reports issued by valgrind are incorrect - we would
1517 ** prefer that the randomness be increased by making use of the
1518 ** uninitialized space in zBuf - but valgrind errors tend to worry
1519 ** some users. Rather than argue, it seems easier just to initialize
1520 ** the whole array and silence valgrind, even if that means less randomness
1521 ** in the random seed.
1522 **
1523 ** When testing, initializing zBuf[] to zero is all we do. That means
1524 ** that we always use the same random number sequence.* This makes the
1525 ** tests repeatable.
1526 */
1527 memset(zBuf, 0, 256);
1528#if !defined(SQLITE_TEST)
1529 {
drh842b8642005-01-21 17:53:17 +00001530 int pid, fd;
1531 fd = open("/dev/urandom", O_RDONLY);
1532 if( fd<0 ){
1533 time((time_t*)zBuf);
1534 pid = getpid();
1535 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1536 }else{
1537 read(fd, zBuf, 256);
1538 close(fd);
1539 }
drhbbd42a62004-05-22 17:41:58 +00001540 }
1541#endif
1542 return SQLITE_OK;
1543}
1544
1545/*
1546** Sleep for a little while. Return the amount of time slept.
1547*/
drh054889e2005-11-30 03:20:31 +00001548static int unixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001549#if defined(HAVE_USLEEP) && HAVE_USLEEP
1550 usleep(ms*1000);
1551 return ms;
1552#else
1553 sleep((ms+999)/1000);
1554 return 1000*((ms+999)/1000);
1555#endif
1556}
1557
1558/*
1559** Static variables used for thread synchronization
1560*/
1561static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001562#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001563static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001564#endif
drhbbd42a62004-05-22 17:41:58 +00001565
1566/*
1567** The following pair of routine implement mutual exclusion for
1568** multi-threaded processes. Only a single thread is allowed to
1569** executed code that is surrounded by EnterMutex() and LeaveMutex().
1570**
1571** SQLite uses only a single Mutex. There is not much critical
1572** code and what little there is executes quickly and without blocking.
1573*/
drh054889e2005-11-30 03:20:31 +00001574static void unixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001575#ifdef SQLITE_UNIX_THREADS
1576 pthread_mutex_lock(&mutex);
1577#endif
1578 assert( !inMutex );
1579 inMutex = 1;
1580}
drh054889e2005-11-30 03:20:31 +00001581static void unixLeaveMutex(){
drhbbd42a62004-05-22 17:41:58 +00001582 assert( inMutex );
1583 inMutex = 0;
1584#ifdef SQLITE_UNIX_THREADS
1585 pthread_mutex_unlock(&mutex);
1586#endif
1587}
1588
1589/*
danielk197713a68c32005-12-15 10:11:30 +00001590** This function is called automatically when a thread exists to delete
1591** the threads SqliteTsd structure.
1592**
1593** Because the SqliteTsd structure is required by higher level routines
1594** such as sqliteMalloc() we use OsFree() and OsMalloc() directly to
1595** allocate the thread specific data.
1596*/
1597static void deleteTsd(void *pTsd){
1598 sqlite3OsFree(pTsd);
1599}
1600
1601/*
1602** The first time this function is called from a specific thread, nByte
1603** bytes of data area are allocated and zeroed. A pointer to the new
1604** allocation is returned to the caller.
1605**
1606** Each subsequent call to this function from the thread returns the same
1607** pointer. The argument is ignored in this case.
1608*/
1609static void *unixThreadSpecificData(int nByte){
1610#ifdef SQLITE_UNIX_THREADS
1611 static pthread_key_t key;
1612 static int keyInit = 0;
1613 void *pTsd;
1614
1615 if( !keyInit ){
1616 sqlite3Os.xEnterMutex();
1617 if( !keyInit ){
1618 int rc;
1619 rc = pthread_key_create(&key, deleteTsd);
1620 if( rc ){
1621 return 0;
1622 }
1623 keyInit = 1;
1624 }
1625 sqlite3Os.xLeaveMutex();
1626 }
1627
1628 pTsd = (SqliteTsd *)pthread_getspecific(key);
1629 if( !pTsd ){
1630 pTsd = sqlite3OsMalloc(sizeof(SqliteTsd));
1631 if( pTsd ){
1632 memset(pTsd, 0, sizeof(SqliteTsd));
1633 pthread_setspecific(key, pTsd);
1634 }
1635 }
1636 return pTsd;
1637#else
1638 static char tsd[sizeof(SqliteTsd)];
1639 static isInit = 0;
1640 assert( nByte==sizeof(SqliteTsd) );
1641 if( !isInit ){
1642 memset(tsd, 0, sizeof(SqliteTsd));
1643 isInit = 1;
1644 }
1645 return (void *)tsd;
1646#endif
1647}
1648
1649/*
drhbbd42a62004-05-22 17:41:58 +00001650** The following variable, if set to a non-zero value, becomes the result
drh054889e2005-11-30 03:20:31 +00001651** returned from sqlite3Os.xCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001652*/
1653#ifdef SQLITE_TEST
1654int sqlite3_current_time = 0;
1655#endif
1656
1657/*
1658** Find the current time (in Universal Coordinated Time). Write the
1659** current time and date as a Julian Day number into *prNow and
1660** return 0. Return 1 if the time and date cannot be found.
1661*/
drh054889e2005-11-30 03:20:31 +00001662static int unixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001663#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001664 time_t t;
1665 time(&t);
1666 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001667#else
1668 struct timeval sNow;
1669 struct timezone sTz; /* Not used */
1670 gettimeofday(&sNow, &sTz);
1671 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1672#endif
drhbbd42a62004-05-22 17:41:58 +00001673#ifdef SQLITE_TEST
1674 if( sqlite3_current_time ){
1675 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1676 }
1677#endif
1678 return 0;
1679}
1680
drh054889e2005-11-30 03:20:31 +00001681/* Macro used to comment out routines that do not exists when there is
1682** no disk I/O */
1683#ifdef SQLITE_OMIT_DISKIO
1684# define IF_DISKIO(X) 0
1685#else
1686# define IF_DISKIO(X) X
1687#endif
1688
1689/*
1690** This is the structure that defines all of the I/O routines.
1691*/
1692struct sqlite3OsVtbl sqlite3Os = {
1693 IF_DISKIO( unixOpenReadWrite ),
1694 IF_DISKIO( unixOpenExclusive ),
1695 IF_DISKIO( unixOpenReadOnly ),
1696 IF_DISKIO( unixDelete ),
1697 IF_DISKIO( unixFileExists ),
1698 IF_DISKIO( unixFullPathname ),
1699 IF_DISKIO( unixIsDirWritable ),
1700 IF_DISKIO( unixSyncDirectory ),
1701 IF_DISKIO( unixTempFileName ),
1702 unixRandomSeed,
1703 unixSleep,
1704 unixCurrentTime,
1705 unixEnterMutex,
1706 unixLeaveMutex,
danielk197713a68c32005-12-15 10:11:30 +00001707 unixThreadSpecificData
drh054889e2005-11-30 03:20:31 +00001708};
1709
1710
1711
drhbbd42a62004-05-22 17:41:58 +00001712#endif /* OS_UNIX */