blob: a19ba4920b558aa77894d464202754db292a0697 [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 */
drhbbd42a62004-05-22 17:41:58 +000018
19
20#include <time.h>
21#include <errno.h>
22#include <unistd.h>
drh0ccebe72005-06-07 22:22:50 +000023
24/*
25** Do not include any of the File I/O interface procedures if the
26** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
27** will be in-memory only)
28*/
29#ifndef SQLITE_OMIT_DISKIO
30
31
32/*
33** Define various macros that are missing from some systems.
34*/
drhbbd42a62004-05-22 17:41:58 +000035#ifndef O_LARGEFILE
36# define O_LARGEFILE 0
37#endif
38#ifdef SQLITE_DISABLE_LFS
39# undef O_LARGEFILE
40# define O_LARGEFILE 0
41#endif
42#ifndef O_NOFOLLOW
43# define O_NOFOLLOW 0
44#endif
45#ifndef O_BINARY
46# define O_BINARY 0
47#endif
48
49/*
50** The DJGPP compiler environment looks mostly like Unix, but it
51** lacks the fcntl() system call. So redefine fcntl() to be something
52** that always succeeds. This means that locking does not occur under
53** DJGPP. But its DOS - what did you expect?
54*/
55#ifdef __DJGPP__
56# define fcntl(A,B,C) 0
57#endif
58
59/*
drhbbd42a62004-05-22 17:41:58 +000060** Include code that is common to all os_*.c files
61*/
62#include "os_common.h"
63
drh2b4b5962005-06-15 17:47:55 +000064/*
65** The threadid macro resolves to the thread-id or to 0. Used for
66** testing and debugging only.
67*/
68#ifdef SQLITE_UNIX_THREADS
69#define threadid pthread_self()
70#else
71#define threadid 0
72#endif
73
74/*
75** Set or check the OsFile.tid field. This field is set when an OsFile
76** is first opened. All subsequent uses of the OsFile verify that the
77** same thread is operating on the OsFile. Some operating systems do
78** not allow locks to be overridden by other threads and that restriction
79** means that sqlite3* database handles cannot be moved from one thread
80** to another. This logic makes sure a user does not try to do that
81** by mistake.
82*/
83#ifdef SQLITE_UNIX_THREADS
84# define SET_THREADID(X) X->tid = pthread_self()
85# define CHECK_THREADID(X) (!pthread_equal(X->tid, pthread_self()))
86#else
87# define SET_THREADID(X)
88# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +000089#endif
90
drhbbd42a62004-05-22 17:41:58 +000091/*
92** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
93** section 6.5.2.2 lines 483 through 490 specify that when a process
94** sets or clears a lock, that operation overrides any prior locks set
95** by the same process. It does not explicitly say so, but this implies
96** that it overrides locks set by the same process using a different
97** file descriptor. Consider this test case:
98**
99** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
100** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
101**
102** Suppose ./file1 and ./file2 are really the same file (because
103** one is a hard or symbolic link to the other) then if you set
104** an exclusive lock on fd1, then try to get an exclusive lock
105** on fd2, it works. I would have expected the second lock to
106** fail since there was already a lock on the file due to fd1.
107** But not so. Since both locks came from the same process, the
108** second overrides the first, even though they were on different
109** file descriptors opened on different file names.
110**
111** Bummer. If you ask me, this is broken. Badly broken. It means
112** that we cannot use POSIX locks to synchronize file access among
113** competing threads of the same process. POSIX locks will work fine
114** to synchronize access for threads in separate processes, but not
115** threads within the same process.
116**
117** To work around the problem, SQLite has to manage file locks internally
118** on its own. Whenever a new database is opened, we have to find the
119** specific inode of the database file (the inode is determined by the
120** st_dev and st_ino fields of the stat structure that fstat() fills in)
121** and check for locks already existing on that inode. When locks are
122** created or removed, we have to look at our own internal record of the
123** locks to see if another thread has previously set a lock on that same
124** inode.
125**
126** The OsFile structure for POSIX is no longer just an integer file
127** descriptor. It is now a structure that holds the integer file
128** descriptor and a pointer to a structure that describes the internal
129** locks on the corresponding inode. There is one locking structure
130** per inode, so if the same inode is opened twice, both OsFile structures
131** point to the same locking structure. The locking structure keeps
132** a reference count (so we will know when to delete it) and a "cnt"
133** field that tells us its internal lock status. cnt==0 means the
134** file is unlocked. cnt==-1 means the file has an exclusive lock.
135** cnt>0 means there are cnt shared locks on the file.
136**
137** Any attempt to lock or unlock a file first checks the locking
138** structure. The fcntl() system call is only invoked to set a
139** POSIX lock if the internal lock structure transitions between
140** a locked and an unlocked state.
141**
142** 2004-Jan-11:
143** More recent discoveries about POSIX advisory locks. (The more
144** I discover, the more I realize the a POSIX advisory locks are
145** an abomination.)
146**
147** If you close a file descriptor that points to a file that has locks,
148** all locks on that file that are owned by the current process are
149** released. To work around this problem, each OsFile structure contains
150** a pointer to an openCnt structure. There is one openCnt structure
151** per open inode, which means that multiple OsFiles can point to a single
152** openCnt. When an attempt is made to close an OsFile, if there are
153** other OsFiles open on the same inode that are holding locks, the call
154** to close() the file descriptor is deferred until all of the locks clear.
155** The openCnt structure keeps a list of file descriptors that need to
156** be closed and that list is walked (and cleared) when the last lock
157** clears.
158**
159** First, under Linux threads, because each thread has a separate
160** process ID, lock operations in one thread do not override locks
161** to the same file in other threads. Linux threads behave like
162** separate processes in this respect. But, if you close a file
163** descriptor in linux threads, all locks are cleared, even locks
164** on other threads and even though the other threads have different
165** process IDs. Linux threads is inconsistent in this respect.
166** (I'm beginning to think that linux threads is an abomination too.)
167** The consequence of this all is that the hash table for the lockInfo
168** structure has to include the process id as part of its key because
169** locks in different threads are treated as distinct. But the
170** openCnt structure should not include the process id in its
171** key because close() clears lock on all threads, not just the current
172** thread. Were it not for this goofiness in linux threads, we could
173** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000174**
175** 2004-Jun-28:
176** On some versions of linux, threads can override each others locks.
177** On others not. Sometimes you can change the behavior on the same
178** system by setting the LD_ASSUME_KERNEL environment variable. The
179** POSIX standard is silent as to which behavior is correct, as far
180** as I can tell, so other versions of unix might show the same
181** inconsistency. There is no little doubt in my mind that posix
182** advisory locks and linux threads are profoundly broken.
183**
184** To work around the inconsistencies, we have to test at runtime
185** whether or not threads can override each others locks. This test
186** is run once, the first time any lock is attempted. A static
187** variable is set to record the results of this test for future
188** use.
drhbbd42a62004-05-22 17:41:58 +0000189*/
190
191/*
192** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000193** to locate a particular lockInfo structure given its inode.
194**
195** If threads cannot override each others locks, then we set the
196** lockKey.tid field to the thread ID. If threads can override
197** each others locks then tid is always set to zero. tid is also
198** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000199*/
200struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000201 dev_t dev; /* Device number */
202 ino_t ino; /* Inode number */
203#ifdef SQLITE_UNIX_THREADS
204 pthread_t tid; /* Thread ID or zero if threads cannot override each other */
205#endif
drhbbd42a62004-05-22 17:41:58 +0000206};
207
208/*
209** An instance of the following structure is allocated for each open
210** inode on each thread with a different process ID. (Threads have
211** different process IDs on linux, but not on most other unixes.)
212**
213** A single inode can have multiple file descriptors, so each OsFile
214** structure contains a pointer to an instance of this object and this
215** object keeps a count of the number of OsFiles pointing to it.
216*/
217struct lockInfo {
218 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000219 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000220 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000221 int nRef; /* Number of pointers to this structure */
222};
223
224/*
225** An instance of the following structure serves as the key used
226** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000227** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000228*/
229struct openKey {
230 dev_t dev; /* Device number */
231 ino_t ino; /* Inode number */
232};
233
234/*
235** An instance of the following structure is allocated for each open
236** inode. This structure keeps track of the number of locks on that
237** inode. If a close is attempted against an inode that is holding
238** locks, the close is deferred until all locks clear by adding the
239** file descriptor to be closed to the pending list.
240*/
241struct openCnt {
242 struct openKey key; /* The lookup key */
243 int nRef; /* Number of pointers to this structure */
244 int nLock; /* Number of outstanding locks */
245 int nPending; /* Number of pending close() operations */
246 int *aPending; /* Malloced space holding fd's awaiting a close() */
247};
248
249/*
250** These hash table maps inodes and process IDs into lockInfo and openCnt
251** structures. Access to these hash tables must be protected by a mutex.
252*/
253static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
254static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
255
drh5fdae772004-06-29 03:29:00 +0000256
257#ifdef SQLITE_UNIX_THREADS
258/*
259** This variable records whether or not threads can override each others
260** locks.
261**
262** 0: No. Threads cannot override each others locks.
263** 1: Yes. Threads can override each others locks.
264** -1: We don't know yet.
265*/
266static int threadsOverrideEachOthersLocks = -1;
267
268/*
269** This structure holds information passed into individual test
270** threads by the testThreadLockingBehavior() routine.
271*/
272struct threadTestData {
273 int fd; /* File to be locked */
274 struct flock lock; /* The locking operation */
275 int result; /* Result of the locking operation */
276};
277
drh2b4b5962005-06-15 17:47:55 +0000278#ifdef SQLITE_LOCK_TRACE
279/*
280** Print out information about all locking operations.
281**
282** This routine is used for troubleshooting locks on multithreaded
283** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
284** command-line option on the compiler. This code is normally
285** turnned off.
286*/
287static int lockTrace(int fd, int op, struct flock *p){
288 char *zOpName, *zType;
289 int s;
290 int savedErrno;
291 if( op==F_GETLK ){
292 zOpName = "GETLK";
293 }else if( op==F_SETLK ){
294 zOpName = "SETLK";
295 }else{
296 s = fcntl(fd, op, p);
297 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
298 return s;
299 }
300 if( p->l_type==F_RDLCK ){
301 zType = "RDLCK";
302 }else if( p->l_type==F_WRLCK ){
303 zType = "WRLCK";
304 }else if( p->l_type==F_UNLCK ){
305 zType = "UNLCK";
306 }else{
307 assert( 0 );
308 }
309 assert( p->l_whence==SEEK_SET );
310 s = fcntl(fd, op, p);
311 savedErrno = errno;
312 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
313 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
314 (int)p->l_pid, s);
315 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
316 struct flock l2;
317 l2 = *p;
318 fcntl(fd, F_GETLK, &l2);
319 if( l2.l_type==F_RDLCK ){
320 zType = "RDLCK";
321 }else if( l2.l_type==F_WRLCK ){
322 zType = "WRLCK";
323 }else if( l2.l_type==F_UNLCK ){
324 zType = "UNLCK";
325 }else{
326 assert( 0 );
327 }
328 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
329 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
330 }
331 errno = savedErrno;
332 return s;
333}
334#define fcntl lockTrace
335#endif /* SQLITE_LOCK_TRACE */
336
drh5fdae772004-06-29 03:29:00 +0000337/*
338** The testThreadLockingBehavior() routine launches two separate
339** threads on this routine. This routine attempts to lock a file
340** descriptor then returns. The success or failure of that attempt
341** allows the testThreadLockingBehavior() procedure to determine
342** whether or not threads can override each others locks.
343*/
344static void *threadLockingTest(void *pArg){
345 struct threadTestData *pData = (struct threadTestData*)pArg;
346 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
347 return pArg;
348}
349
350/*
351** This procedure attempts to determine whether or not threads
352** can override each others locks then sets the
353** threadsOverrideEachOthersLocks variable appropriately.
354*/
355static void testThreadLockingBehavior(fd_orig){
356 int fd;
357 struct threadTestData d[2];
358 pthread_t t[2];
359
360 fd = dup(fd_orig);
361 if( fd<0 ) return;
362 memset(d, 0, sizeof(d));
363 d[0].fd = fd;
364 d[0].lock.l_type = F_RDLCK;
365 d[0].lock.l_len = 1;
366 d[0].lock.l_start = 0;
367 d[0].lock.l_whence = SEEK_SET;
368 d[1] = d[0];
369 d[1].lock.l_type = F_WRLCK;
370 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
371 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
372 pthread_join(t[0], 0);
373 pthread_join(t[1], 0);
374 close(fd);
375 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
376}
377#endif /* SQLITE_UNIX_THREADS */
378
drhbbd42a62004-05-22 17:41:58 +0000379/*
380** Release a lockInfo structure previously allocated by findLockInfo().
381*/
382static void releaseLockInfo(struct lockInfo *pLock){
383 pLock->nRef--;
384 if( pLock->nRef==0 ){
385 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
386 sqliteFree(pLock);
387 }
388}
389
390/*
391** Release a openCnt structure previously allocated by findLockInfo().
392*/
393static void releaseOpenCnt(struct openCnt *pOpen){
394 pOpen->nRef--;
395 if( pOpen->nRef==0 ){
396 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
397 sqliteFree(pOpen->aPending);
398 sqliteFree(pOpen);
399 }
400}
401
402/*
403** Given a file descriptor, locate lockInfo and openCnt structures that
404** describes that file descriptor. Create a new ones if necessary. The
405** return values might be unset if an error occurs.
406**
407** Return the number of errors.
408*/
drh38f82712004-06-18 17:10:16 +0000409static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000410 int fd, /* The file descriptor used in the key */
411 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000412 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000413){
414 int rc;
415 struct lockKey key1;
416 struct openKey key2;
417 struct stat statbuf;
418 struct lockInfo *pLock;
419 struct openCnt *pOpen;
420 rc = fstat(fd, &statbuf);
421 if( rc!=0 ) return 1;
422 memset(&key1, 0, sizeof(key1));
423 key1.dev = statbuf.st_dev;
424 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000425#ifdef SQLITE_UNIX_THREADS
426 if( threadsOverrideEachOthersLocks<0 ){
427 testThreadLockingBehavior(fd);
428 }
429 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
430#endif
drhbbd42a62004-05-22 17:41:58 +0000431 memset(&key2, 0, sizeof(key2));
432 key2.dev = statbuf.st_dev;
433 key2.ino = statbuf.st_ino;
434 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
435 if( pLock==0 ){
436 struct lockInfo *pOld;
437 pLock = sqliteMallocRaw( sizeof(*pLock) );
438 if( pLock==0 ) return 1;
439 pLock->key = key1;
440 pLock->nRef = 1;
441 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000442 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000443 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
444 if( pOld!=0 ){
445 assert( pOld==pLock );
446 sqliteFree(pLock);
447 return 1;
448 }
449 }else{
450 pLock->nRef++;
451 }
452 *ppLock = pLock;
453 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
454 if( pOpen==0 ){
455 struct openCnt *pOld;
456 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
457 if( pOpen==0 ){
458 releaseLockInfo(pLock);
459 return 1;
460 }
461 pOpen->key = key2;
462 pOpen->nRef = 1;
463 pOpen->nLock = 0;
464 pOpen->nPending = 0;
465 pOpen->aPending = 0;
466 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
467 if( pOld!=0 ){
468 assert( pOld==pOpen );
469 sqliteFree(pOpen);
470 releaseLockInfo(pLock);
471 return 1;
472 }
473 }else{
474 pOpen->nRef++;
475 }
476 *ppOpen = pOpen;
477 return 0;
478}
479
480/*
481** Delete the named file
482*/
483int sqlite3OsDelete(const char *zFilename){
484 unlink(zFilename);
485 return SQLITE_OK;
486}
487
488/*
489** Return TRUE if the named file exists.
490*/
491int sqlite3OsFileExists(const char *zFilename){
492 return access(zFilename, 0)==0;
493}
494
495/*
496** Attempt to open a file for both reading and writing. If that
497** fails, try opening it read-only. If the file does not exist,
498** try to create it.
499**
500** On success, a handle for the open file is written to *id
501** and *pReadonly is set to 0 if the file was opened for reading and
502** writing or 1 if the file was opened read-only. The function returns
503** SQLITE_OK.
504**
505** On failure, the function returns SQLITE_CANTOPEN and leaves
506** *id and *pReadonly unchanged.
507*/
508int sqlite3OsOpenReadWrite(
509 const char *zFilename,
510 OsFile *id,
511 int *pReadonly
512){
513 int rc;
drhda71ce12004-06-21 18:14:45 +0000514 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000515 id->dirfd = -1;
drh2b4b5962005-06-15 17:47:55 +0000516 SET_THREADID(id);
drh8e855772005-05-17 11:25:31 +0000517 id->h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
518 SQLITE_DEFAULT_FILE_PERMISSIONS);
drha6abd042004-06-09 17:37:22 +0000519 if( id->h<0 ){
drh6458e392004-07-20 01:14:13 +0000520#ifdef EISDIR
521 if( errno==EISDIR ){
522 return SQLITE_CANTOPEN;
523 }
524#endif
drha6abd042004-06-09 17:37:22 +0000525 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
526 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000527 return SQLITE_CANTOPEN;
528 }
529 *pReadonly = 1;
530 }else{
531 *pReadonly = 0;
532 }
533 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000534 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000535 sqlite3OsLeaveMutex();
536 if( rc ){
drha6abd042004-06-09 17:37:22 +0000537 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000538 return SQLITE_NOMEM;
539 }
danielk197713adf8a2004-06-03 16:08:41 +0000540 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000541 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000542 TRACE3("OPEN %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000543 OpenCounter(+1);
544 return SQLITE_OK;
545}
546
547
548/*
549** Attempt to open a new file for exclusive access by this process.
550** The file will be opened for both reading and writing. To avoid
551** a potential security problem, we do not allow the file to have
552** previously existed. Nor do we allow the file to be a symbolic
553** link.
554**
555** If delFlag is true, then make arrangements to automatically delete
556** the file when it is closed.
557**
558** On success, write the file handle into *id and return SQLITE_OK.
559**
560** On failure, return SQLITE_CANTOPEN.
561*/
562int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
563 int rc;
drhda71ce12004-06-21 18:14:45 +0000564 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000565 if( access(zFilename, 0)==0 ){
566 return SQLITE_CANTOPEN;
567 }
drh2b4b5962005-06-15 17:47:55 +0000568 SET_THREADID(id);
drhbbd42a62004-05-22 17:41:58 +0000569 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000570 id->h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000571 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
572 SQLITE_DEFAULT_FILE_PERMISSIONS);
drha6abd042004-06-09 17:37:22 +0000573 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000574 return SQLITE_CANTOPEN;
575 }
576 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000577 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000578 sqlite3OsLeaveMutex();
579 if( rc ){
drha6abd042004-06-09 17:37:22 +0000580 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000581 unlink(zFilename);
582 return SQLITE_NOMEM;
583 }
danielk197713adf8a2004-06-03 16:08:41 +0000584 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000585 id->isOpen = 1;
drhbbd42a62004-05-22 17:41:58 +0000586 if( delFlag ){
587 unlink(zFilename);
588 }
drha6abd042004-06-09 17:37:22 +0000589 TRACE3("OPEN-EX %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000590 OpenCounter(+1);
591 return SQLITE_OK;
592}
593
594/*
595** Attempt to open a new file for read-only access.
596**
597** On success, write the file handle into *id and return SQLITE_OK.
598**
599** On failure, return SQLITE_CANTOPEN.
600*/
601int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
602 int rc;
drhda71ce12004-06-21 18:14:45 +0000603 assert( !id->isOpen );
drh2b4b5962005-06-15 17:47:55 +0000604 SET_THREADID(id);
drhbbd42a62004-05-22 17:41:58 +0000605 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000606 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
607 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000608 return SQLITE_CANTOPEN;
609 }
610 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000611 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000612 sqlite3OsLeaveMutex();
613 if( rc ){
drha6abd042004-06-09 17:37:22 +0000614 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000615 return SQLITE_NOMEM;
616 }
danielk197713adf8a2004-06-03 16:08:41 +0000617 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000618 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000619 TRACE3("OPEN-RO %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000620 OpenCounter(+1);
621 return SQLITE_OK;
622}
623
624/*
625** Attempt to open a file descriptor for the directory that contains a
626** file. This file descriptor can be used to fsync() the directory
627** in order to make sure the creation of a new file is actually written
628** to disk.
629**
630** This routine is only meaningful for Unix. It is a no-op under
631** windows since windows does not support hard links.
632**
633** On success, a handle for a previously open file is at *id is
634** updated with the new directory file descriptor and SQLITE_OK is
635** returned.
636**
637** On failure, the function returns SQLITE_CANTOPEN and leaves
638** *id unchanged.
639*/
640int sqlite3OsOpenDirectory(
641 const char *zDirname,
642 OsFile *id
643){
drhda71ce12004-06-21 18:14:45 +0000644 if( !id->isOpen ){
drhbbd42a62004-05-22 17:41:58 +0000645 /* Do not open the directory if the corresponding file is not already
646 ** open. */
647 return SQLITE_CANTOPEN;
648 }
drh2b4b5962005-06-15 17:47:55 +0000649 SET_THREADID(id);
drhbbd42a62004-05-22 17:41:58 +0000650 assert( id->dirfd<0 );
drh8e855772005-05-17 11:25:31 +0000651 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
drhbbd42a62004-05-22 17:41:58 +0000652 if( id->dirfd<0 ){
653 return SQLITE_CANTOPEN;
654 }
655 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
656 return SQLITE_OK;
657}
658
659/*
drhab3f9fe2004-08-14 17:10:10 +0000660** If the following global variable points to a string which is the
661** name of a directory, then that directory will be used to store
662** temporary files.
663*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000664char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000665
666/*
drhbbd42a62004-05-22 17:41:58 +0000667** Create a temporary file name in zBuf. zBuf must be big enough to
668** hold at least SQLITE_TEMPNAME_SIZE characters.
669*/
670int sqlite3OsTempFileName(char *zBuf){
671 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000672 0,
drhbbd42a62004-05-22 17:41:58 +0000673 "/var/tmp",
674 "/usr/tmp",
675 "/tmp",
676 ".",
677 };
drh57196282004-10-06 15:41:16 +0000678 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000679 "abcdefghijklmnopqrstuvwxyz"
680 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
681 "0123456789";
682 int i, j;
683 struct stat buf;
684 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000685 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000686 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000687 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000688 if( stat(azDirs[i], &buf) ) continue;
689 if( !S_ISDIR(buf.st_mode) ) continue;
690 if( access(azDirs[i], 07) ) continue;
691 zDir = azDirs[i];
692 break;
693 }
694 do{
695 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
696 j = strlen(zBuf);
697 sqlite3Randomness(15, &zBuf[j]);
698 for(i=0; i<15; i++, j++){
699 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
700 }
701 zBuf[j] = 0;
702 }while( access(zBuf,0)==0 );
703 return SQLITE_OK;
704}
705
drh268283b2005-01-08 15:44:25 +0000706#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhbbd42a62004-05-22 17:41:58 +0000707/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000708** Check that a given pathname is a directory and is writable
709**
710*/
711int sqlite3OsIsDirWritable(char *zBuf){
712 struct stat buf;
713 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000714 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000715 if( stat(zBuf, &buf) ) return 0;
716 if( !S_ISDIR(buf.st_mode) ) return 0;
717 if( access(zBuf, 07) ) return 0;
718 return 1;
719}
drh268283b2005-01-08 15:44:25 +0000720#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000721
722/*
drhbbd42a62004-05-22 17:41:58 +0000723** Read data from a file into a buffer. Return SQLITE_OK if all
724** bytes were read successfully and SQLITE_IOERR if anything goes
725** wrong.
726*/
727int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
728 int got;
drhda71ce12004-06-21 18:14:45 +0000729 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000730 SimulateIOError(SQLITE_IOERR);
731 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000732 got = read(id->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000733 TIMER_END;
drhe29b9152005-03-18 14:03:15 +0000734 TRACE5("READ %-3d %5d %7d %d\n", id->h, got, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000735 SEEK(0);
736 /* if( got<0 ) got = 0; */
737 if( got==amt ){
738 return SQLITE_OK;
739 }else{
740 return SQLITE_IOERR;
741 }
742}
743
744/*
745** Write data from a buffer into a file. Return SQLITE_OK on success
746** or some other error code on failure.
747*/
748int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
749 int wrote = 0;
drhda71ce12004-06-21 18:14:45 +0000750 assert( id->isOpen );
drh4c7f9412005-02-03 00:29:47 +0000751 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000752 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000753 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000754 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000755 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000756 amt -= wrote;
757 pBuf = &((char*)pBuf)[wrote];
758 }
759 TIMER_END;
drhe29b9152005-03-18 14:03:15 +0000760 TRACE5("WRITE %-3d %5d %7d %d\n", id->h, wrote, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000761 SEEK(0);
762 if( amt>0 ){
763 return SQLITE_FULL;
764 }
765 return SQLITE_OK;
766}
767
768/*
769** Move the read/write pointer in a file.
770*/
drheb206252004-10-01 02:00:31 +0000771int sqlite3OsSeek(OsFile *id, i64 offset){
drhda71ce12004-06-21 18:14:45 +0000772 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000773 SEEK(offset/1024 + 1);
drha6abd042004-06-09 17:37:22 +0000774 lseek(id->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000775 return SQLITE_OK;
776}
777
drhb851b2c2005-03-10 14:11:12 +0000778#ifdef SQLITE_TEST
779/*
780** Count the number of fullsyncs and normal syncs. This is used to test
781** that syncs and fullsyncs are occuring at the right times.
782*/
783int sqlite3_sync_count = 0;
784int sqlite3_fullsync_count = 0;
785#endif
786
787
drhbbd42a62004-05-22 17:41:58 +0000788/*
drhdd809b02004-07-17 21:44:57 +0000789** The fsync() system call does not work as advertised on many
790** unix systems. The following procedure is an attempt to make
791** it work better.
drh1398ad32005-01-19 23:24:50 +0000792**
793** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
794** for testing when we want to run through the test suite quickly.
795** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
796** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
797** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000798*/
drhb851b2c2005-03-10 14:11:12 +0000799static int full_fsync(int fd, int fullSync){
drhdd809b02004-07-17 21:44:57 +0000800 int rc;
drhb851b2c2005-03-10 14:11:12 +0000801
802 /* Record the number of times that we do a normal fsync() and
803 ** FULLSYNC. This is used during testing to verify that this procedure
804 ** gets called with the correct arguments.
805 */
806#ifdef SQLITE_TEST
807 if( fullSync ) sqlite3_fullsync_count++;
808 sqlite3_sync_count++;
809#endif
810
811 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
812 ** no-op
813 */
814#ifdef SQLITE_NO_SYNC
815 rc = SQLITE_OK;
816#else
817
drhdd809b02004-07-17 21:44:57 +0000818#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000819 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000820 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +0000821 }else{
822 rc = 1;
823 }
824 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +0000825 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +0000826
drhdd809b02004-07-17 21:44:57 +0000827#else
828 rc = fsync(fd);
drhf30cc942005-03-11 17:52:34 +0000829#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +0000830#endif /* defined(SQLITE_NO_SYNC) */
831
drhdd809b02004-07-17 21:44:57 +0000832 return rc;
833}
834
835/*
drhbbd42a62004-05-22 17:41:58 +0000836** Make sure all writes to a particular file are committed to disk.
837**
838** Under Unix, also make sure that the directory entry for the file
839** has been created by fsync-ing the directory that contains the file.
840** If we do not do this and we encounter a power failure, the directory
841** entry for the journal might not exist after we reboot. The next
842** SQLite to access the file will not know that the journal exists (because
843** the directory entry for the journal was never created) and the transaction
844** will not roll back - possibly leading to database corruption.
845*/
846int sqlite3OsSync(OsFile *id){
drhda71ce12004-06-21 18:14:45 +0000847 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000848 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000849 TRACE2("SYNC %-3d\n", id->h);
drhb851b2c2005-03-10 14:11:12 +0000850 if( full_fsync(id->h, id->fullSync) ){
drhbbd42a62004-05-22 17:41:58 +0000851 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000852 }
drha2854222004-06-17 19:04:17 +0000853 if( id->dirfd>=0 ){
854 TRACE2("DIRSYNC %-3d\n", id->dirfd);
drhb851b2c2005-03-10 14:11:12 +0000855 full_fsync(id->dirfd, id->fullSync);
drha2854222004-06-17 19:04:17 +0000856 close(id->dirfd); /* Only need to sync once, so close the directory */
857 id->dirfd = -1; /* when we are done. */
858 }
drha2854222004-06-17 19:04:17 +0000859 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000860}
861
862/*
danielk1977962398d2004-06-14 09:35:16 +0000863** Sync the directory zDirname. This is a no-op on operating systems other
864** than UNIX.
drhb851b2c2005-03-10 14:11:12 +0000865**
866** This is used to make sure the master journal file has truely been deleted
867** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +0000868** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +0000869*/
870int sqlite3OsSyncDirectory(const char *zDirname){
871 int fd;
872 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000873 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +0000874 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +0000875 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000876 if( fd<0 ){
877 return SQLITE_CANTOPEN;
878 }
879 r = fsync(fd);
880 close(fd);
881 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
882}
883
884/*
drhbbd42a62004-05-22 17:41:58 +0000885** Truncate an open file to a specified size
886*/
drheb206252004-10-01 02:00:31 +0000887int sqlite3OsTruncate(OsFile *id, i64 nByte){
drhda71ce12004-06-21 18:14:45 +0000888 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000889 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000890 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000891}
892
893/*
894** Determine the current size of a file in bytes
895*/
drheb206252004-10-01 02:00:31 +0000896int sqlite3OsFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +0000897 struct stat buf;
drhda71ce12004-06-21 18:14:45 +0000898 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000899 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000900 if( fstat(id->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +0000901 return SQLITE_IOERR;
902 }
903 *pSize = buf.st_size;
904 return SQLITE_OK;
905}
906
danielk19779a1d0ab2004-06-01 14:09:28 +0000907/*
danielk197713adf8a2004-06-03 16:08:41 +0000908** This routine checks if there is a RESERVED lock held on the specified
909** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000910** non-zero. If the file is unlocked or holds only SHARED locks, then
911** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000912*/
drha6abd042004-06-09 17:37:22 +0000913int sqlite3OsCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +0000914 int r = 0;
915
drhda71ce12004-06-21 18:14:45 +0000916 assert( id->isOpen );
drh2b4b5962005-06-15 17:47:55 +0000917 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
drh2ac3ee92004-06-07 16:27:46 +0000918 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000919
920 /* Check if a thread in this process holds such a lock */
921 if( id->pLock->locktype>SHARED_LOCK ){
922 r = 1;
923 }
924
drh2ac3ee92004-06-07 16:27:46 +0000925 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000926 */
927 if( !r ){
928 struct flock lock;
929 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000930 lock.l_start = RESERVED_BYTE;
931 lock.l_len = 1;
932 lock.l_type = F_WRLCK;
drha6abd042004-06-09 17:37:22 +0000933 fcntl(id->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +0000934 if( lock.l_type!=F_UNLCK ){
935 r = 1;
936 }
937 }
938
939 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000940 TRACE3("TEST WR-LOCK %d %d\n", id->h, r);
danielk197713adf8a2004-06-03 16:08:41 +0000941
942 return r;
943}
944
danielk19772b444852004-06-29 07:45:33 +0000945#ifdef SQLITE_DEBUG
946/*
947** Helper function for printing out trace information from debugging
948** binaries. This returns the string represetation of the supplied
949** integer lock-type.
950*/
951static const char * locktypeName(int locktype){
952 switch( locktype ){
953 case NO_LOCK: return "NONE";
954 case SHARED_LOCK: return "SHARED";
955 case RESERVED_LOCK: return "RESERVED";
956 case PENDING_LOCK: return "PENDING";
957 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
958 }
959 return "ERROR";
960}
961#endif
962
danielk197713adf8a2004-06-03 16:08:41 +0000963/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000964** Lock the file with the lock specified by parameter locktype - one
965** of the following:
966**
drh2ac3ee92004-06-07 16:27:46 +0000967** (1) SHARED_LOCK
968** (2) RESERVED_LOCK
969** (3) PENDING_LOCK
970** (4) EXCLUSIVE_LOCK
971**
drhb3e04342004-06-08 00:47:47 +0000972** Sometimes when requesting one lock state, additional lock states
973** are inserted in between. The locking might fail on one of the later
974** transitions leaving the lock state different from what it started but
975** still short of its goal. The following chart shows the allowed
976** transitions and the inserted intermediate states:
977**
978** UNLOCKED -> SHARED
979** SHARED -> RESERVED
980** SHARED -> (PENDING) -> EXCLUSIVE
981** RESERVED -> (PENDING) -> EXCLUSIVE
982** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000983**
drha6abd042004-06-09 17:37:22 +0000984** This routine will only increase a lock. Use the sqlite3OsUnlock()
985** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000986*/
987int sqlite3OsLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +0000988 /* The following describes the implementation of the various locks and
989 ** lock transitions in terms of the POSIX advisory shared and exclusive
990 ** lock primitives (called read-locks and write-locks below, to avoid
991 ** confusion with SQLite lock names). The algorithms are complicated
992 ** slightly in order to be compatible with windows systems simultaneously
993 ** accessing the same database file, in case that is ever required.
994 **
995 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
996 ** byte', each single bytes at well known offsets, and the 'shared byte
997 ** range', a range of 510 bytes at a well known offset.
998 **
999 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1000 ** byte'. If this is successful, a random byte from the 'shared byte
1001 ** range' is read-locked and the lock on the 'pending byte' released.
1002 **
danielk197790ba3bd2004-06-25 08:32:25 +00001003 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1004 ** A RESERVED lock is implemented by grabbing a write-lock on the
1005 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001006 **
1007 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001008 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1009 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1010 ** obtained, but existing SHARED locks are allowed to persist. A process
1011 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1012 ** This property is used by the algorithm for rolling back a journal file
1013 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001014 **
danielk197790ba3bd2004-06-25 08:32:25 +00001015 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1016 ** implemented by obtaining a write-lock on the entire 'shared byte
1017 ** range'. Since all other locks require a read-lock on one of the bytes
1018 ** within this range, this ensures that no other locks are held on the
1019 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001020 **
1021 ** The reason a single byte cannot be used instead of the 'shared byte
1022 ** range' is that some versions of windows do not support read-locks. By
1023 ** locking a random byte from a range, concurrent SHARED locks may exist
1024 ** even if the locking primitive used is always a write-lock.
1025 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001026 int rc = SQLITE_OK;
1027 struct lockInfo *pLock = id->pLock;
1028 struct flock lock;
1029 int s;
1030
drhda71ce12004-06-21 18:14:45 +00001031 assert( id->isOpen );
drhe29b9152005-03-18 14:03:15 +00001032 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", id->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001033 locktypeName(id->locktype), locktypeName(pLock->locktype), pLock->cnt
1034 ,getpid() );
drh2b4b5962005-06-15 17:47:55 +00001035 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001036
1037 /* If there is already a lock of this type or more restrictive on the
1038 ** OsFile, do nothing. Don't use the end_lock: exit path, as
1039 ** sqlite3OsEnterMutex() hasn't been called yet.
1040 */
danielk197713adf8a2004-06-03 16:08:41 +00001041 if( id->locktype>=locktype ){
drhe29b9152005-03-18 14:03:15 +00001042 TRACE3("LOCK %d %s ok (already held)\n", id->h, locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001043 return SQLITE_OK;
1044 }
1045
drhb3e04342004-06-08 00:47:47 +00001046 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001047 */
drhb3e04342004-06-08 00:47:47 +00001048 assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1049 assert( locktype!=PENDING_LOCK );
1050 assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001051
drhb3e04342004-06-08 00:47:47 +00001052 /* This mutex is needed because id->pLock is shared across threads
1053 */
1054 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001055
1056 /* If some thread using this PID has a lock via a different OsFile*
1057 ** handle that precludes the requested lock, return BUSY.
1058 */
danielk197713adf8a2004-06-03 16:08:41 +00001059 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001060 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001061 ){
1062 rc = SQLITE_BUSY;
1063 goto end_lock;
1064 }
1065
1066 /* If a SHARED lock is requested, and some thread using this PID already
1067 ** has a SHARED or RESERVED lock, then increment reference counts and
1068 ** return SQLITE_OK.
1069 */
1070 if( locktype==SHARED_LOCK &&
1071 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1072 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +00001073 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001074 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +00001075 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001076 pLock->cnt++;
1077 id->pOpen->nLock++;
1078 goto end_lock;
1079 }
1080
danielk197713adf8a2004-06-03 16:08:41 +00001081 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001082
danielk19779a1d0ab2004-06-01 14:09:28 +00001083 lock.l_whence = SEEK_SET;
1084
drh3cde3bb2004-06-12 02:17:14 +00001085 /* A PENDING lock is needed before acquiring a SHARED lock and before
1086 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1087 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001088 */
drh3cde3bb2004-06-12 02:17:14 +00001089 if( locktype==SHARED_LOCK
1090 || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)
1091 ){
danielk1977489468c2004-06-28 08:25:47 +00001092 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001093 lock.l_start = PENDING_BYTE;
drha6abd042004-06-09 17:37:22 +00001094 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001095 if( s ){
1096 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1097 goto end_lock;
1098 }
drh3cde3bb2004-06-12 02:17:14 +00001099 }
1100
1101
1102 /* If control gets to this point, then actually go ahead and make
1103 ** operating system calls for the specified lock.
1104 */
1105 if( locktype==SHARED_LOCK ){
1106 assert( pLock->cnt==0 );
1107 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001108
drh2ac3ee92004-06-07 16:27:46 +00001109 /* Now get the read-lock */
1110 lock.l_start = SHARED_FIRST;
1111 lock.l_len = SHARED_SIZE;
drha6abd042004-06-09 17:37:22 +00001112 s = fcntl(id->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001113
1114 /* Drop the temporary PENDING lock */
1115 lock.l_start = PENDING_BYTE;
1116 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001117 lock.l_type = F_UNLCK;
drh2b4b5962005-06-15 17:47:55 +00001118 if( fcntl(id->h, F_SETLK, &lock)!=0 ){
1119 rc = SQLITE_IOERR; /* This should never happen */
1120 goto end_lock;
1121 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001122 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001123 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1124 }else{
danielk197713adf8a2004-06-03 16:08:41 +00001125 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001126 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001127 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001128 }
drh3cde3bb2004-06-12 02:17:14 +00001129 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1130 /* We are trying for an exclusive lock but another thread in this
1131 ** same process is still holding a shared lock. */
1132 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001133 }else{
drh3cde3bb2004-06-12 02:17:14 +00001134 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001135 ** assumed that there is a SHARED or greater lock on the file
1136 ** already.
1137 */
danielk197713adf8a2004-06-03 16:08:41 +00001138 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001139 lock.l_type = F_WRLCK;
1140 switch( locktype ){
1141 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001142 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001143 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001144 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001145 lock.l_start = SHARED_FIRST;
1146 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001147 break;
1148 default:
1149 assert(0);
1150 }
drha6abd042004-06-09 17:37:22 +00001151 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001152 if( s ){
1153 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1154 }
drhbbd42a62004-05-22 17:41:58 +00001155 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001156
danielk1977ecb2a962004-06-02 06:30:16 +00001157 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +00001158 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001159 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001160 }else if( locktype==EXCLUSIVE_LOCK ){
1161 id->locktype = PENDING_LOCK;
1162 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001163 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001164
1165end_lock:
drhbbd42a62004-05-22 17:41:58 +00001166 sqlite3OsLeaveMutex();
drhe29b9152005-03-18 14:03:15 +00001167 TRACE4("LOCK %d %s %s\n", id->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001168 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001169 return rc;
1170}
1171
1172/*
drha6abd042004-06-09 17:37:22 +00001173** Lower the locking level on file descriptor id to locktype. locktype
1174** must be either NO_LOCK or SHARED_LOCK.
1175**
1176** If the locking level of the file descriptor is already at or below
1177** the requested locking level, this routine is a no-op.
1178**
drh9c105bb2004-10-02 20:38:28 +00001179** It is not possible for this routine to fail if the second argument
1180** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1181** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001182*/
drha6abd042004-06-09 17:37:22 +00001183int sqlite3OsUnlock(OsFile *id, int locktype){
1184 struct lockInfo *pLock;
1185 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001186 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001187
drhda71ce12004-06-21 18:14:45 +00001188 assert( id->isOpen );
drhe29b9152005-03-18 14:03:15 +00001189 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", id->h, locktype, id->locktype,
danielk19772b444852004-06-29 07:45:33 +00001190 id->pLock->locktype, id->pLock->cnt, getpid());
drh2b4b5962005-06-15 17:47:55 +00001191 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
drha6abd042004-06-09 17:37:22 +00001192
1193 assert( locktype<=SHARED_LOCK );
1194 if( id->locktype<=locktype ){
1195 return SQLITE_OK;
1196 }
drhbbd42a62004-05-22 17:41:58 +00001197 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +00001198 pLock = id->pLock;
1199 assert( pLock->cnt!=0 );
1200 if( id->locktype>SHARED_LOCK ){
1201 assert( pLock->locktype==id->locktype );
drh9c105bb2004-10-02 20:38:28 +00001202 if( locktype==SHARED_LOCK ){
1203 lock.l_type = F_RDLCK;
1204 lock.l_whence = SEEK_SET;
1205 lock.l_start = SHARED_FIRST;
1206 lock.l_len = SHARED_SIZE;
1207 if( fcntl(id->h, F_SETLK, &lock)!=0 ){
1208 /* This should never happen */
1209 rc = SQLITE_IOERR;
1210 }
1211 }
drhbbd42a62004-05-22 17:41:58 +00001212 lock.l_type = F_UNLCK;
1213 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001214 lock.l_start = PENDING_BYTE;
1215 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh2b4b5962005-06-15 17:47:55 +00001216 if( fcntl(id->h, F_SETLK, &lock)==0 ){
1217 pLock->locktype = SHARED_LOCK;
1218 }else{
1219 rc = SQLITE_IOERR; /* This should never happen */
1220 }
drhbbd42a62004-05-22 17:41:58 +00001221 }
drha6abd042004-06-09 17:37:22 +00001222 if( locktype==NO_LOCK ){
1223 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001224
drha6abd042004-06-09 17:37:22 +00001225 /* Decrement the shared lock counter. Release the lock using an
1226 ** OS call only when all threads in this same process have released
1227 ** the lock.
1228 */
1229 pLock->cnt--;
1230 if( pLock->cnt==0 ){
1231 lock.l_type = F_UNLCK;
1232 lock.l_whence = SEEK_SET;
1233 lock.l_start = lock.l_len = 0L;
drh2b4b5962005-06-15 17:47:55 +00001234 if( fcntl(id->h, F_SETLK, &lock)==0 ){
1235 pLock->locktype = NO_LOCK;
1236 }else{
1237 rc = SQLITE_IOERR; /* This should never happen */
1238 }
drha6abd042004-06-09 17:37:22 +00001239 }
1240
drhbbd42a62004-05-22 17:41:58 +00001241 /* Decrement the count of locks against this same file. When the
1242 ** count reaches zero, close any other file descriptors whose close
1243 ** was deferred because of outstanding locks.
1244 */
drha6abd042004-06-09 17:37:22 +00001245 pOpen = id->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001246 pOpen->nLock--;
1247 assert( pOpen->nLock>=0 );
1248 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1249 int i;
1250 for(i=0; i<pOpen->nPending; i++){
1251 close(pOpen->aPending[i]);
1252 }
1253 sqliteFree(pOpen->aPending);
1254 pOpen->nPending = 0;
1255 pOpen->aPending = 0;
1256 }
1257 }
1258 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +00001259 id->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001260 return rc;
drhbbd42a62004-05-22 17:41:58 +00001261}
1262
1263/*
danielk1977e3026632004-06-22 11:29:02 +00001264** Close a file.
1265*/
1266int sqlite3OsClose(OsFile *id){
1267 if( !id->isOpen ) return SQLITE_OK;
drh2b4b5962005-06-15 17:47:55 +00001268 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
danielk1977e3026632004-06-22 11:29:02 +00001269 sqlite3OsUnlock(id, NO_LOCK);
1270 if( id->dirfd>=0 ) close(id->dirfd);
1271 id->dirfd = -1;
1272 sqlite3OsEnterMutex();
1273 if( id->pOpen->nLock ){
1274 /* If there are outstanding locks, do not actually close the file just
1275 ** yet because that would clear those locks. Instead, add the file
1276 ** descriptor to pOpen->aPending. It will be automatically closed when
1277 ** the last lock is cleared.
1278 */
1279 int *aNew;
1280 struct openCnt *pOpen = id->pOpen;
1281 pOpen->nPending++;
1282 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1283 if( aNew==0 ){
1284 /* If a malloc fails, just leak the file descriptor */
1285 }else{
1286 pOpen->aPending = aNew;
1287 pOpen->aPending[pOpen->nPending-1] = id->h;
1288 }
1289 }else{
1290 /* There are no outstanding locks so we can close the file immediately */
1291 close(id->h);
1292 }
1293 releaseLockInfo(id->pLock);
1294 releaseOpenCnt(id->pOpen);
1295 sqlite3OsLeaveMutex();
1296 id->isOpen = 0;
1297 TRACE2("CLOSE %-3d\n", id->h);
1298 OpenCounter(-1);
1299 return SQLITE_OK;
1300}
1301
1302/*
drh0ccebe72005-06-07 22:22:50 +00001303** Turn a relative pathname into a full pathname. Return a pointer
1304** to the full pathname stored in space obtained from sqliteMalloc().
1305** The calling function is responsible for freeing this space once it
1306** is no longer needed.
1307*/
1308char *sqlite3OsFullPathname(const char *zRelative){
1309 char *zFull = 0;
1310 if( zRelative[0]=='/' ){
1311 sqlite3SetString(&zFull, zRelative, (char*)0);
1312 }else{
1313 char zBuf[5000];
1314 zBuf[0] = 0;
1315 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1316 (char*)0);
1317 }
1318 return zFull;
1319}
1320
1321
1322#endif /* SQLITE_OMIT_DISKIO */
1323/***************************************************************************
1324** Everything above deals with file I/O. Everything that follows deals
1325** with other miscellanous aspects of the operating system interface
1326****************************************************************************/
1327
1328
1329/*
drhbbd42a62004-05-22 17:41:58 +00001330** Get information to seed the random number generator. The seed
1331** is written into the buffer zBuf[256]. The calling function must
1332** supply a sufficiently large buffer.
1333*/
1334int sqlite3OsRandomSeed(char *zBuf){
1335 /* We have to initialize zBuf to prevent valgrind from reporting
1336 ** errors. The reports issued by valgrind are incorrect - we would
1337 ** prefer that the randomness be increased by making use of the
1338 ** uninitialized space in zBuf - but valgrind errors tend to worry
1339 ** some users. Rather than argue, it seems easier just to initialize
1340 ** the whole array and silence valgrind, even if that means less randomness
1341 ** in the random seed.
1342 **
1343 ** When testing, initializing zBuf[] to zero is all we do. That means
1344 ** that we always use the same random number sequence.* This makes the
1345 ** tests repeatable.
1346 */
1347 memset(zBuf, 0, 256);
1348#if !defined(SQLITE_TEST)
1349 {
drh842b8642005-01-21 17:53:17 +00001350 int pid, fd;
1351 fd = open("/dev/urandom", O_RDONLY);
1352 if( fd<0 ){
1353 time((time_t*)zBuf);
1354 pid = getpid();
1355 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1356 }else{
1357 read(fd, zBuf, 256);
1358 close(fd);
1359 }
drhbbd42a62004-05-22 17:41:58 +00001360 }
1361#endif
1362 return SQLITE_OK;
1363}
1364
1365/*
1366** Sleep for a little while. Return the amount of time slept.
1367*/
1368int sqlite3OsSleep(int ms){
1369#if defined(HAVE_USLEEP) && HAVE_USLEEP
1370 usleep(ms*1000);
1371 return ms;
1372#else
1373 sleep((ms+999)/1000);
1374 return 1000*((ms+999)/1000);
1375#endif
1376}
1377
1378/*
1379** Static variables used for thread synchronization
1380*/
1381static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001382#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001383static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001384#endif
drhbbd42a62004-05-22 17:41:58 +00001385
1386/*
1387** The following pair of routine implement mutual exclusion for
1388** multi-threaded processes. Only a single thread is allowed to
1389** executed code that is surrounded by EnterMutex() and LeaveMutex().
1390**
1391** SQLite uses only a single Mutex. There is not much critical
1392** code and what little there is executes quickly and without blocking.
1393*/
1394void sqlite3OsEnterMutex(){
1395#ifdef SQLITE_UNIX_THREADS
1396 pthread_mutex_lock(&mutex);
1397#endif
1398 assert( !inMutex );
1399 inMutex = 1;
1400}
1401void sqlite3OsLeaveMutex(){
1402 assert( inMutex );
1403 inMutex = 0;
1404#ifdef SQLITE_UNIX_THREADS
1405 pthread_mutex_unlock(&mutex);
1406#endif
1407}
1408
1409/*
drhbbd42a62004-05-22 17:41:58 +00001410** The following variable, if set to a non-zero value, becomes the result
1411** returned from sqlite3OsCurrentTime(). This is used for testing.
1412*/
1413#ifdef SQLITE_TEST
1414int sqlite3_current_time = 0;
1415#endif
1416
1417/*
1418** Find the current time (in Universal Coordinated Time). Write the
1419** current time and date as a Julian Day number into *prNow and
1420** return 0. Return 1 if the time and date cannot be found.
1421*/
1422int sqlite3OsCurrentTime(double *prNow){
1423 time_t t;
1424 time(&t);
1425 *prNow = t/86400.0 + 2440587.5;
1426#ifdef SQLITE_TEST
1427 if( sqlite3_current_time ){
1428 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1429 }
1430#endif
1431 return 0;
1432}
1433
drhbbd42a62004-05-22 17:41:58 +00001434#endif /* OS_UNIX */