blob: bc5c0b111b3102af8aa296cc64cd56dece9babc7 [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>
23#ifndef O_LARGEFILE
24# define O_LARGEFILE 0
25#endif
26#ifdef SQLITE_DISABLE_LFS
27# undef O_LARGEFILE
28# define O_LARGEFILE 0
29#endif
30#ifndef O_NOFOLLOW
31# define O_NOFOLLOW 0
32#endif
33#ifndef O_BINARY
34# define O_BINARY 0
35#endif
36
drheb206252004-10-01 02:00:31 +000037
drhbbd42a62004-05-22 17:41:58 +000038/*
39** The DJGPP compiler environment looks mostly like Unix, but it
40** lacks the fcntl() system call. So redefine fcntl() to be something
41** that always succeeds. This means that locking does not occur under
42** DJGPP. But its DOS - what did you expect?
43*/
44#ifdef __DJGPP__
45# define fcntl(A,B,C) 0
46#endif
47
48/*
49** Macros used to determine whether or not to use threads. The
50** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
51** Posix threads and SQLITE_W32_THREADS is defined if we are
52** synchronizing using Win32 threads.
53*/
54#if defined(THREADSAFE) && THREADSAFE
55# include <pthread.h>
56# define SQLITE_UNIX_THREADS 1
57#endif
58
59
60/*
61** Include code that is common to all os_*.c files
62*/
63#include "os_common.h"
64
drh0bb132b2004-07-20 14:06:51 +000065#if defined(THREADSAFE) && THREADSAFE && defined(__linux__)
danielk197713adf8a2004-06-03 16:08:41 +000066#define getpid pthread_self
67#endif
68
drhbbd42a62004-05-22 17:41:58 +000069/*
70** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
71** section 6.5.2.2 lines 483 through 490 specify that when a process
72** sets or clears a lock, that operation overrides any prior locks set
73** by the same process. It does not explicitly say so, but this implies
74** that it overrides locks set by the same process using a different
75** file descriptor. Consider this test case:
76**
77** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
78** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
79**
80** Suppose ./file1 and ./file2 are really the same file (because
81** one is a hard or symbolic link to the other) then if you set
82** an exclusive lock on fd1, then try to get an exclusive lock
83** on fd2, it works. I would have expected the second lock to
84** fail since there was already a lock on the file due to fd1.
85** But not so. Since both locks came from the same process, the
86** second overrides the first, even though they were on different
87** file descriptors opened on different file names.
88**
89** Bummer. If you ask me, this is broken. Badly broken. It means
90** that we cannot use POSIX locks to synchronize file access among
91** competing threads of the same process. POSIX locks will work fine
92** to synchronize access for threads in separate processes, but not
93** threads within the same process.
94**
95** To work around the problem, SQLite has to manage file locks internally
96** on its own. Whenever a new database is opened, we have to find the
97** specific inode of the database file (the inode is determined by the
98** st_dev and st_ino fields of the stat structure that fstat() fills in)
99** and check for locks already existing on that inode. When locks are
100** created or removed, we have to look at our own internal record of the
101** locks to see if another thread has previously set a lock on that same
102** inode.
103**
104** The OsFile structure for POSIX is no longer just an integer file
105** descriptor. It is now a structure that holds the integer file
106** descriptor and a pointer to a structure that describes the internal
107** locks on the corresponding inode. There is one locking structure
108** per inode, so if the same inode is opened twice, both OsFile structures
109** point to the same locking structure. The locking structure keeps
110** a reference count (so we will know when to delete it) and a "cnt"
111** field that tells us its internal lock status. cnt==0 means the
112** file is unlocked. cnt==-1 means the file has an exclusive lock.
113** cnt>0 means there are cnt shared locks on the file.
114**
115** Any attempt to lock or unlock a file first checks the locking
116** structure. The fcntl() system call is only invoked to set a
117** POSIX lock if the internal lock structure transitions between
118** a locked and an unlocked state.
119**
120** 2004-Jan-11:
121** More recent discoveries about POSIX advisory locks. (The more
122** I discover, the more I realize the a POSIX advisory locks are
123** an abomination.)
124**
125** If you close a file descriptor that points to a file that has locks,
126** all locks on that file that are owned by the current process are
127** released. To work around this problem, each OsFile structure contains
128** a pointer to an openCnt structure. There is one openCnt structure
129** per open inode, which means that multiple OsFiles can point to a single
130** openCnt. When an attempt is made to close an OsFile, if there are
131** other OsFiles open on the same inode that are holding locks, the call
132** to close() the file descriptor is deferred until all of the locks clear.
133** The openCnt structure keeps a list of file descriptors that need to
134** be closed and that list is walked (and cleared) when the last lock
135** clears.
136**
137** First, under Linux threads, because each thread has a separate
138** process ID, lock operations in one thread do not override locks
139** to the same file in other threads. Linux threads behave like
140** separate processes in this respect. But, if you close a file
141** descriptor in linux threads, all locks are cleared, even locks
142** on other threads and even though the other threads have different
143** process IDs. Linux threads is inconsistent in this respect.
144** (I'm beginning to think that linux threads is an abomination too.)
145** The consequence of this all is that the hash table for the lockInfo
146** structure has to include the process id as part of its key because
147** locks in different threads are treated as distinct. But the
148** openCnt structure should not include the process id in its
149** key because close() clears lock on all threads, not just the current
150** thread. Were it not for this goofiness in linux threads, we could
151** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000152**
153** 2004-Jun-28:
154** On some versions of linux, threads can override each others locks.
155** On others not. Sometimes you can change the behavior on the same
156** system by setting the LD_ASSUME_KERNEL environment variable. The
157** POSIX standard is silent as to which behavior is correct, as far
158** as I can tell, so other versions of unix might show the same
159** inconsistency. There is no little doubt in my mind that posix
160** advisory locks and linux threads are profoundly broken.
161**
162** To work around the inconsistencies, we have to test at runtime
163** whether or not threads can override each others locks. This test
164** is run once, the first time any lock is attempted. A static
165** variable is set to record the results of this test for future
166** use.
drhbbd42a62004-05-22 17:41:58 +0000167*/
168
169/*
170** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000171** to locate a particular lockInfo structure given its inode.
172**
173** If threads cannot override each others locks, then we set the
174** lockKey.tid field to the thread ID. If threads can override
175** each others locks then tid is always set to zero. tid is also
176** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000177*/
178struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000179 dev_t dev; /* Device number */
180 ino_t ino; /* Inode number */
181#ifdef SQLITE_UNIX_THREADS
182 pthread_t tid; /* Thread ID or zero if threads cannot override each other */
183#endif
drhbbd42a62004-05-22 17:41:58 +0000184};
185
186/*
187** An instance of the following structure is allocated for each open
188** inode on each thread with a different process ID. (Threads have
189** different process IDs on linux, but not on most other unixes.)
190**
191** A single inode can have multiple file descriptors, so each OsFile
192** structure contains a pointer to an instance of this object and this
193** object keeps a count of the number of OsFiles pointing to it.
194*/
195struct lockInfo {
196 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000197 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000198 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000199 int nRef; /* Number of pointers to this structure */
200};
201
202/*
203** An instance of the following structure serves as the key used
204** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000205** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000206*/
207struct openKey {
208 dev_t dev; /* Device number */
209 ino_t ino; /* Inode number */
210};
211
212/*
213** An instance of the following structure is allocated for each open
214** inode. This structure keeps track of the number of locks on that
215** inode. If a close is attempted against an inode that is holding
216** locks, the close is deferred until all locks clear by adding the
217** file descriptor to be closed to the pending list.
218*/
219struct openCnt {
220 struct openKey key; /* The lookup key */
221 int nRef; /* Number of pointers to this structure */
222 int nLock; /* Number of outstanding locks */
223 int nPending; /* Number of pending close() operations */
224 int *aPending; /* Malloced space holding fd's awaiting a close() */
225};
226
227/*
228** These hash table maps inodes and process IDs into lockInfo and openCnt
229** structures. Access to these hash tables must be protected by a mutex.
230*/
231static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
232static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
233
drh5fdae772004-06-29 03:29:00 +0000234
235#ifdef SQLITE_UNIX_THREADS
236/*
237** This variable records whether or not threads can override each others
238** locks.
239**
240** 0: No. Threads cannot override each others locks.
241** 1: Yes. Threads can override each others locks.
242** -1: We don't know yet.
243*/
244static int threadsOverrideEachOthersLocks = -1;
245
246/*
247** This structure holds information passed into individual test
248** threads by the testThreadLockingBehavior() routine.
249*/
250struct threadTestData {
251 int fd; /* File to be locked */
252 struct flock lock; /* The locking operation */
253 int result; /* Result of the locking operation */
254};
255
256/*
257** The testThreadLockingBehavior() routine launches two separate
258** threads on this routine. This routine attempts to lock a file
259** descriptor then returns. The success or failure of that attempt
260** allows the testThreadLockingBehavior() procedure to determine
261** whether or not threads can override each others locks.
262*/
263static void *threadLockingTest(void *pArg){
264 struct threadTestData *pData = (struct threadTestData*)pArg;
265 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
266 return pArg;
267}
268
269/*
270** This procedure attempts to determine whether or not threads
271** can override each others locks then sets the
272** threadsOverrideEachOthersLocks variable appropriately.
273*/
274static void testThreadLockingBehavior(fd_orig){
275 int fd;
276 struct threadTestData d[2];
277 pthread_t t[2];
278
279 fd = dup(fd_orig);
280 if( fd<0 ) return;
281 memset(d, 0, sizeof(d));
282 d[0].fd = fd;
283 d[0].lock.l_type = F_RDLCK;
284 d[0].lock.l_len = 1;
285 d[0].lock.l_start = 0;
286 d[0].lock.l_whence = SEEK_SET;
287 d[1] = d[0];
288 d[1].lock.l_type = F_WRLCK;
289 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
290 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
291 pthread_join(t[0], 0);
292 pthread_join(t[1], 0);
293 close(fd);
294 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
295}
296#endif /* SQLITE_UNIX_THREADS */
297
drhbbd42a62004-05-22 17:41:58 +0000298/*
299** Release a lockInfo structure previously allocated by findLockInfo().
300*/
301static void releaseLockInfo(struct lockInfo *pLock){
302 pLock->nRef--;
303 if( pLock->nRef==0 ){
304 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
305 sqliteFree(pLock);
306 }
307}
308
309/*
310** Release a openCnt structure previously allocated by findLockInfo().
311*/
312static void releaseOpenCnt(struct openCnt *pOpen){
313 pOpen->nRef--;
314 if( pOpen->nRef==0 ){
315 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
316 sqliteFree(pOpen->aPending);
317 sqliteFree(pOpen);
318 }
319}
320
321/*
322** Given a file descriptor, locate lockInfo and openCnt structures that
323** describes that file descriptor. Create a new ones if necessary. The
324** return values might be unset if an error occurs.
325**
326** Return the number of errors.
327*/
drh38f82712004-06-18 17:10:16 +0000328static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000329 int fd, /* The file descriptor used in the key */
330 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000331 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000332){
333 int rc;
334 struct lockKey key1;
335 struct openKey key2;
336 struct stat statbuf;
337 struct lockInfo *pLock;
338 struct openCnt *pOpen;
339 rc = fstat(fd, &statbuf);
340 if( rc!=0 ) return 1;
341 memset(&key1, 0, sizeof(key1));
342 key1.dev = statbuf.st_dev;
343 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000344#ifdef SQLITE_UNIX_THREADS
345 if( threadsOverrideEachOthersLocks<0 ){
346 testThreadLockingBehavior(fd);
347 }
348 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
349#endif
drhbbd42a62004-05-22 17:41:58 +0000350 memset(&key2, 0, sizeof(key2));
351 key2.dev = statbuf.st_dev;
352 key2.ino = statbuf.st_ino;
353 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
354 if( pLock==0 ){
355 struct lockInfo *pOld;
356 pLock = sqliteMallocRaw( sizeof(*pLock) );
357 if( pLock==0 ) return 1;
358 pLock->key = key1;
359 pLock->nRef = 1;
360 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000361 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000362 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
363 if( pOld!=0 ){
364 assert( pOld==pLock );
365 sqliteFree(pLock);
366 return 1;
367 }
368 }else{
369 pLock->nRef++;
370 }
371 *ppLock = pLock;
372 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
373 if( pOpen==0 ){
374 struct openCnt *pOld;
375 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
376 if( pOpen==0 ){
377 releaseLockInfo(pLock);
378 return 1;
379 }
380 pOpen->key = key2;
381 pOpen->nRef = 1;
382 pOpen->nLock = 0;
383 pOpen->nPending = 0;
384 pOpen->aPending = 0;
385 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
386 if( pOld!=0 ){
387 assert( pOld==pOpen );
388 sqliteFree(pOpen);
389 releaseLockInfo(pLock);
390 return 1;
391 }
392 }else{
393 pOpen->nRef++;
394 }
395 *ppOpen = pOpen;
396 return 0;
397}
398
399/*
400** Delete the named file
401*/
402int sqlite3OsDelete(const char *zFilename){
403 unlink(zFilename);
404 return SQLITE_OK;
405}
406
407/*
408** Return TRUE if the named file exists.
409*/
410int sqlite3OsFileExists(const char *zFilename){
411 return access(zFilename, 0)==0;
412}
413
414/*
415** Attempt to open a file for both reading and writing. If that
416** fails, try opening it read-only. If the file does not exist,
417** try to create it.
418**
419** On success, a handle for the open file is written to *id
420** and *pReadonly is set to 0 if the file was opened for reading and
421** writing or 1 if the file was opened read-only. The function returns
422** SQLITE_OK.
423**
424** On failure, the function returns SQLITE_CANTOPEN and leaves
425** *id and *pReadonly unchanged.
426*/
427int sqlite3OsOpenReadWrite(
428 const char *zFilename,
429 OsFile *id,
430 int *pReadonly
431){
432 int rc;
drhda71ce12004-06-21 18:14:45 +0000433 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000434 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000435 id->h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
436 if( id->h<0 ){
drh6458e392004-07-20 01:14:13 +0000437#ifdef EISDIR
438 if( errno==EISDIR ){
439 return SQLITE_CANTOPEN;
440 }
441#endif
drha6abd042004-06-09 17:37:22 +0000442 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
443 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000444 return SQLITE_CANTOPEN;
445 }
446 *pReadonly = 1;
447 }else{
448 *pReadonly = 0;
449 }
450 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000451 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000452 sqlite3OsLeaveMutex();
453 if( rc ){
drha6abd042004-06-09 17:37:22 +0000454 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000455 return SQLITE_NOMEM;
456 }
danielk197713adf8a2004-06-03 16:08:41 +0000457 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000458 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000459 TRACE3("OPEN %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000460 OpenCounter(+1);
461 return SQLITE_OK;
462}
463
464
465/*
466** Attempt to open a new file for exclusive access by this process.
467** The file will be opened for both reading and writing. To avoid
468** a potential security problem, we do not allow the file to have
469** previously existed. Nor do we allow the file to be a symbolic
470** link.
471**
472** If delFlag is true, then make arrangements to automatically delete
473** the file when it is closed.
474**
475** On success, write the file handle into *id and return SQLITE_OK.
476**
477** On failure, return SQLITE_CANTOPEN.
478*/
479int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
480 int rc;
drhda71ce12004-06-21 18:14:45 +0000481 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000482 if( access(zFilename, 0)==0 ){
483 return SQLITE_CANTOPEN;
484 }
485 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000486 id->h = open(zFilename,
drhbbd42a62004-05-22 17:41:58 +0000487 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
drha6abd042004-06-09 17:37:22 +0000488 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000489 return SQLITE_CANTOPEN;
490 }
491 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000492 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000493 sqlite3OsLeaveMutex();
494 if( rc ){
drha6abd042004-06-09 17:37:22 +0000495 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000496 unlink(zFilename);
497 return SQLITE_NOMEM;
498 }
danielk197713adf8a2004-06-03 16:08:41 +0000499 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000500 id->isOpen = 1;
drhbbd42a62004-05-22 17:41:58 +0000501 if( delFlag ){
502 unlink(zFilename);
503 }
drha6abd042004-06-09 17:37:22 +0000504 TRACE3("OPEN-EX %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000505 OpenCounter(+1);
506 return SQLITE_OK;
507}
508
509/*
510** Attempt to open a new file for read-only access.
511**
512** On success, write the file handle into *id and return SQLITE_OK.
513**
514** On failure, return SQLITE_CANTOPEN.
515*/
516int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
517 int rc;
drhda71ce12004-06-21 18:14:45 +0000518 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000519 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000520 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
521 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000522 return SQLITE_CANTOPEN;
523 }
524 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000525 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000526 sqlite3OsLeaveMutex();
527 if( rc ){
drha6abd042004-06-09 17:37:22 +0000528 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000529 return SQLITE_NOMEM;
530 }
danielk197713adf8a2004-06-03 16:08:41 +0000531 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000532 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000533 TRACE3("OPEN-RO %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000534 OpenCounter(+1);
535 return SQLITE_OK;
536}
537
538/*
539** Attempt to open a file descriptor for the directory that contains a
540** file. This file descriptor can be used to fsync() the directory
541** in order to make sure the creation of a new file is actually written
542** to disk.
543**
544** This routine is only meaningful for Unix. It is a no-op under
545** windows since windows does not support hard links.
546**
547** On success, a handle for a previously open file is at *id is
548** updated with the new directory file descriptor and SQLITE_OK is
549** returned.
550**
551** On failure, the function returns SQLITE_CANTOPEN and leaves
552** *id unchanged.
553*/
554int sqlite3OsOpenDirectory(
555 const char *zDirname,
556 OsFile *id
557){
drhda71ce12004-06-21 18:14:45 +0000558 if( !id->isOpen ){
drhbbd42a62004-05-22 17:41:58 +0000559 /* Do not open the directory if the corresponding file is not already
560 ** open. */
561 return SQLITE_CANTOPEN;
562 }
563 assert( id->dirfd<0 );
564 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
565 if( id->dirfd<0 ){
566 return SQLITE_CANTOPEN;
567 }
568 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
569 return SQLITE_OK;
570}
571
572/*
drhab3f9fe2004-08-14 17:10:10 +0000573** If the following global variable points to a string which is the
574** name of a directory, then that directory will be used to store
575** temporary files.
576*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000577char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000578
579/*
drhbbd42a62004-05-22 17:41:58 +0000580** Create a temporary file name in zBuf. zBuf must be big enough to
581** hold at least SQLITE_TEMPNAME_SIZE characters.
582*/
583int sqlite3OsTempFileName(char *zBuf){
584 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000585 0,
drhbbd42a62004-05-22 17:41:58 +0000586 "/var/tmp",
587 "/usr/tmp",
588 "/tmp",
589 ".",
590 };
drh57196282004-10-06 15:41:16 +0000591 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000592 "abcdefghijklmnopqrstuvwxyz"
593 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
594 "0123456789";
595 int i, j;
596 struct stat buf;
597 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000598 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000599 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000600 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000601 if( stat(azDirs[i], &buf) ) continue;
602 if( !S_ISDIR(buf.st_mode) ) continue;
603 if( access(azDirs[i], 07) ) continue;
604 zDir = azDirs[i];
605 break;
606 }
607 do{
608 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
609 j = strlen(zBuf);
610 sqlite3Randomness(15, &zBuf[j]);
611 for(i=0; i<15; i++, j++){
612 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
613 }
614 zBuf[j] = 0;
615 }while( access(zBuf,0)==0 );
616 return SQLITE_OK;
617}
618
drh268283b2005-01-08 15:44:25 +0000619#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhbbd42a62004-05-22 17:41:58 +0000620/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000621** Check that a given pathname is a directory and is writable
622**
623*/
624int sqlite3OsIsDirWritable(char *zBuf){
625 struct stat buf;
626 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000627 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000628 if( stat(zBuf, &buf) ) return 0;
629 if( !S_ISDIR(buf.st_mode) ) return 0;
630 if( access(zBuf, 07) ) return 0;
631 return 1;
632}
drh268283b2005-01-08 15:44:25 +0000633#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000634
635/*
drhbbd42a62004-05-22 17:41:58 +0000636** Read data from a file into a buffer. Return SQLITE_OK if all
637** bytes were read successfully and SQLITE_IOERR if anything goes
638** wrong.
639*/
640int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
641 int got;
drhda71ce12004-06-21 18:14:45 +0000642 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000643 SimulateIOError(SQLITE_IOERR);
644 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000645 got = read(id->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000646 TIMER_END;
drha9600bc2004-08-04 14:44:33 +0000647 TRACE4("READ %-3d %7d %d\n", id->h, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000648 SEEK(0);
649 /* if( got<0 ) got = 0; */
650 if( got==amt ){
651 return SQLITE_OK;
652 }else{
653 return SQLITE_IOERR;
654 }
655}
656
657/*
658** Write data from a buffer into a file. Return SQLITE_OK on success
659** or some other error code on failure.
660*/
661int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
662 int wrote = 0;
drhda71ce12004-06-21 18:14:45 +0000663 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000664 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000665 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000666 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000667 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000668 amt -= wrote;
669 pBuf = &((char*)pBuf)[wrote];
670 }
671 TIMER_END;
drha9600bc2004-08-04 14:44:33 +0000672 TRACE4("WRITE %-3d %7d %d\n", id->h, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000673 SEEK(0);
674 if( amt>0 ){
675 return SQLITE_FULL;
676 }
677 return SQLITE_OK;
678}
679
680/*
681** Move the read/write pointer in a file.
682*/
drheb206252004-10-01 02:00:31 +0000683int sqlite3OsSeek(OsFile *id, i64 offset){
drhda71ce12004-06-21 18:14:45 +0000684 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000685 SEEK(offset/1024 + 1);
drha6abd042004-06-09 17:37:22 +0000686 lseek(id->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000687 return SQLITE_OK;
688}
689
690/*
drhdd809b02004-07-17 21:44:57 +0000691** The fsync() system call does not work as advertised on many
692** unix systems. The following procedure is an attempt to make
693** it work better.
drh1398ad32005-01-19 23:24:50 +0000694**
695** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
696** for testing when we want to run through the test suite quickly.
697** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
698** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
699** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000700*/
701static int full_fsync(int fd){
drh1398ad32005-01-19 23:24:50 +0000702#ifdef SQLITE_NO_SYNC
703 return SQLITE_OK;
704#else
drhdd809b02004-07-17 21:44:57 +0000705 int rc;
706#ifdef F_FULLFSYNC
707 rc = fcntl(fd, F_FULLFSYNC, 0);
708 if( rc ) rc = fsync(fd);
709#else
710 rc = fsync(fd);
711#endif
712 return rc;
drh1398ad32005-01-19 23:24:50 +0000713#endif
drhdd809b02004-07-17 21:44:57 +0000714}
715
716/*
drhbbd42a62004-05-22 17:41:58 +0000717** Make sure all writes to a particular file are committed to disk.
718**
719** Under Unix, also make sure that the directory entry for the file
720** has been created by fsync-ing the directory that contains the file.
721** If we do not do this and we encounter a power failure, the directory
722** entry for the journal might not exist after we reboot. The next
723** SQLite to access the file will not know that the journal exists (because
724** the directory entry for the journal was never created) and the transaction
725** will not roll back - possibly leading to database corruption.
726*/
727int sqlite3OsSync(OsFile *id){
drhda71ce12004-06-21 18:14:45 +0000728 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000729 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000730 TRACE2("SYNC %-3d\n", id->h);
drhdd809b02004-07-17 21:44:57 +0000731 if( full_fsync(id->h) ){
drhbbd42a62004-05-22 17:41:58 +0000732 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000733 }
drha2854222004-06-17 19:04:17 +0000734 if( id->dirfd>=0 ){
735 TRACE2("DIRSYNC %-3d\n", id->dirfd);
drhdd809b02004-07-17 21:44:57 +0000736 full_fsync(id->dirfd);
drha2854222004-06-17 19:04:17 +0000737 close(id->dirfd); /* Only need to sync once, so close the directory */
738 id->dirfd = -1; /* when we are done. */
739 }
drha2854222004-06-17 19:04:17 +0000740 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000741}
742
743/*
danielk1977962398d2004-06-14 09:35:16 +0000744** Sync the directory zDirname. This is a no-op on operating systems other
745** than UNIX.
746*/
747int sqlite3OsSyncDirectory(const char *zDirname){
748 int fd;
749 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000750 SimulateIOError(SQLITE_IOERR);
danielk1977962398d2004-06-14 09:35:16 +0000751 fd = open(zDirname, O_RDONLY|O_BINARY, 0644);
danielk1977369f27e2004-06-15 11:40:04 +0000752 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000753 if( fd<0 ){
754 return SQLITE_CANTOPEN;
755 }
756 r = fsync(fd);
757 close(fd);
758 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
759}
760
761/*
drhbbd42a62004-05-22 17:41:58 +0000762** Truncate an open file to a specified size
763*/
drheb206252004-10-01 02:00:31 +0000764int sqlite3OsTruncate(OsFile *id, i64 nByte){
drhda71ce12004-06-21 18:14:45 +0000765 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000766 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000767 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000768}
769
770/*
771** Determine the current size of a file in bytes
772*/
drheb206252004-10-01 02:00:31 +0000773int sqlite3OsFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +0000774 struct stat buf;
drhda71ce12004-06-21 18:14:45 +0000775 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000776 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000777 if( fstat(id->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +0000778 return SQLITE_IOERR;
779 }
780 *pSize = buf.st_size;
781 return SQLITE_OK;
782}
783
danielk19779a1d0ab2004-06-01 14:09:28 +0000784/*
danielk197713adf8a2004-06-03 16:08:41 +0000785** This routine checks if there is a RESERVED lock held on the specified
786** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000787** non-zero. If the file is unlocked or holds only SHARED locks, then
788** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000789*/
drha6abd042004-06-09 17:37:22 +0000790int sqlite3OsCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +0000791 int r = 0;
792
drhda71ce12004-06-21 18:14:45 +0000793 assert( id->isOpen );
drh2ac3ee92004-06-07 16:27:46 +0000794 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000795
796 /* Check if a thread in this process holds such a lock */
797 if( id->pLock->locktype>SHARED_LOCK ){
798 r = 1;
799 }
800
drh2ac3ee92004-06-07 16:27:46 +0000801 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000802 */
803 if( !r ){
804 struct flock lock;
805 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000806 lock.l_start = RESERVED_BYTE;
807 lock.l_len = 1;
808 lock.l_type = F_WRLCK;
drha6abd042004-06-09 17:37:22 +0000809 fcntl(id->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +0000810 if( lock.l_type!=F_UNLCK ){
811 r = 1;
812 }
813 }
814
815 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000816 TRACE3("TEST WR-LOCK %d %d\n", id->h, r);
danielk197713adf8a2004-06-03 16:08:41 +0000817
818 return r;
819}
820
danielk19772b444852004-06-29 07:45:33 +0000821#ifdef SQLITE_DEBUG
822/*
823** Helper function for printing out trace information from debugging
824** binaries. This returns the string represetation of the supplied
825** integer lock-type.
826*/
827static const char * locktypeName(int locktype){
828 switch( locktype ){
829 case NO_LOCK: return "NONE";
830 case SHARED_LOCK: return "SHARED";
831 case RESERVED_LOCK: return "RESERVED";
832 case PENDING_LOCK: return "PENDING";
833 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
834 }
835 return "ERROR";
836}
837#endif
838
danielk197713adf8a2004-06-03 16:08:41 +0000839/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000840** Lock the file with the lock specified by parameter locktype - one
841** of the following:
842**
drh2ac3ee92004-06-07 16:27:46 +0000843** (1) SHARED_LOCK
844** (2) RESERVED_LOCK
845** (3) PENDING_LOCK
846** (4) EXCLUSIVE_LOCK
847**
drhb3e04342004-06-08 00:47:47 +0000848** Sometimes when requesting one lock state, additional lock states
849** are inserted in between. The locking might fail on one of the later
850** transitions leaving the lock state different from what it started but
851** still short of its goal. The following chart shows the allowed
852** transitions and the inserted intermediate states:
853**
854** UNLOCKED -> SHARED
855** SHARED -> RESERVED
856** SHARED -> (PENDING) -> EXCLUSIVE
857** RESERVED -> (PENDING) -> EXCLUSIVE
858** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000859**
drha6abd042004-06-09 17:37:22 +0000860** This routine will only increase a lock. Use the sqlite3OsUnlock()
861** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000862*/
863int sqlite3OsLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +0000864 /* The following describes the implementation of the various locks and
865 ** lock transitions in terms of the POSIX advisory shared and exclusive
866 ** lock primitives (called read-locks and write-locks below, to avoid
867 ** confusion with SQLite lock names). The algorithms are complicated
868 ** slightly in order to be compatible with windows systems simultaneously
869 ** accessing the same database file, in case that is ever required.
870 **
871 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
872 ** byte', each single bytes at well known offsets, and the 'shared byte
873 ** range', a range of 510 bytes at a well known offset.
874 **
875 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
876 ** byte'. If this is successful, a random byte from the 'shared byte
877 ** range' is read-locked and the lock on the 'pending byte' released.
878 **
danielk197790ba3bd2004-06-25 08:32:25 +0000879 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
880 ** A RESERVED lock is implemented by grabbing a write-lock on the
881 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000882 **
883 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000884 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
885 ** on the 'pending byte'. This ensures that no new SHARED locks can be
886 ** obtained, but existing SHARED locks are allowed to persist. A process
887 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
888 ** This property is used by the algorithm for rolling back a journal file
889 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000890 **
danielk197790ba3bd2004-06-25 08:32:25 +0000891 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
892 ** implemented by obtaining a write-lock on the entire 'shared byte
893 ** range'. Since all other locks require a read-lock on one of the bytes
894 ** within this range, this ensures that no other locks are held on the
895 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000896 **
897 ** The reason a single byte cannot be used instead of the 'shared byte
898 ** range' is that some versions of windows do not support read-locks. By
899 ** locking a random byte from a range, concurrent SHARED locks may exist
900 ** even if the locking primitive used is always a write-lock.
901 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000902 int rc = SQLITE_OK;
903 struct lockInfo *pLock = id->pLock;
904 struct flock lock;
905 int s;
906
drhda71ce12004-06-21 18:14:45 +0000907 assert( id->isOpen );
danielk19772b444852004-06-29 07:45:33 +0000908 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", id->h, locktypeName(locktype),
909 locktypeName(id->locktype), locktypeName(pLock->locktype), pLock->cnt
910 ,getpid() );
danielk19779a1d0ab2004-06-01 14:09:28 +0000911
912 /* If there is already a lock of this type or more restrictive on the
913 ** OsFile, do nothing. Don't use the end_lock: exit path, as
914 ** sqlite3OsEnterMutex() hasn't been called yet.
915 */
danielk197713adf8a2004-06-03 16:08:41 +0000916 if( id->locktype>=locktype ){
danielk19772b444852004-06-29 07:45:33 +0000917 TRACE3("LOCK %d %s ok (already held)\n", id->h, locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +0000918 return SQLITE_OK;
919 }
920
drhb3e04342004-06-08 00:47:47 +0000921 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +0000922 */
drhb3e04342004-06-08 00:47:47 +0000923 assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );
924 assert( locktype!=PENDING_LOCK );
925 assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000926
drhb3e04342004-06-08 00:47:47 +0000927 /* This mutex is needed because id->pLock is shared across threads
928 */
929 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +0000930
931 /* If some thread using this PID has a lock via a different OsFile*
932 ** handle that precludes the requested lock, return BUSY.
933 */
danielk197713adf8a2004-06-03 16:08:41 +0000934 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +0000935 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +0000936 ){
937 rc = SQLITE_BUSY;
938 goto end_lock;
939 }
940
941 /* If a SHARED lock is requested, and some thread using this PID already
942 ** has a SHARED or RESERVED lock, then increment reference counts and
943 ** return SQLITE_OK.
944 */
945 if( locktype==SHARED_LOCK &&
946 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
947 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +0000948 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +0000949 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +0000950 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +0000951 pLock->cnt++;
952 id->pOpen->nLock++;
953 goto end_lock;
954 }
955
danielk197713adf8a2004-06-03 16:08:41 +0000956 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000957 lock.l_whence = SEEK_SET;
958
drh3cde3bb2004-06-12 02:17:14 +0000959 /* A PENDING lock is needed before acquiring a SHARED lock and before
960 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
961 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +0000962 */
drh3cde3bb2004-06-12 02:17:14 +0000963 if( locktype==SHARED_LOCK
964 || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)
965 ){
danielk1977489468c2004-06-28 08:25:47 +0000966 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +0000967 lock.l_start = PENDING_BYTE;
drha6abd042004-06-09 17:37:22 +0000968 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000969 if( s ){
970 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
971 goto end_lock;
972 }
drh3cde3bb2004-06-12 02:17:14 +0000973 }
974
975
976 /* If control gets to this point, then actually go ahead and make
977 ** operating system calls for the specified lock.
978 */
979 if( locktype==SHARED_LOCK ){
980 assert( pLock->cnt==0 );
981 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +0000982
drh2ac3ee92004-06-07 16:27:46 +0000983 /* Now get the read-lock */
984 lock.l_start = SHARED_FIRST;
985 lock.l_len = SHARED_SIZE;
drha6abd042004-06-09 17:37:22 +0000986 s = fcntl(id->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +0000987
988 /* Drop the temporary PENDING lock */
989 lock.l_start = PENDING_BYTE;
990 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000991 lock.l_type = F_UNLCK;
drha6abd042004-06-09 17:37:22 +0000992 fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000993 if( s ){
drhbbd42a62004-05-22 17:41:58 +0000994 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
995 }else{
danielk197713adf8a2004-06-03 16:08:41 +0000996 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000997 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +0000998 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +0000999 }
drh3cde3bb2004-06-12 02:17:14 +00001000 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1001 /* We are trying for an exclusive lock but another thread in this
1002 ** same process is still holding a shared lock. */
1003 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001004 }else{
drh3cde3bb2004-06-12 02:17:14 +00001005 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001006 ** assumed that there is a SHARED or greater lock on the file
1007 ** already.
1008 */
danielk197713adf8a2004-06-03 16:08:41 +00001009 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001010 lock.l_type = F_WRLCK;
1011 switch( locktype ){
1012 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001013 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001014 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001015 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001016 lock.l_start = SHARED_FIRST;
1017 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001018 break;
1019 default:
1020 assert(0);
1021 }
drha6abd042004-06-09 17:37:22 +00001022 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001023 if( s ){
1024 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1025 }
drhbbd42a62004-05-22 17:41:58 +00001026 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001027
danielk1977ecb2a962004-06-02 06:30:16 +00001028 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +00001029 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001030 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001031 }else if( locktype==EXCLUSIVE_LOCK ){
1032 id->locktype = PENDING_LOCK;
1033 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001034 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001035
1036end_lock:
drhbbd42a62004-05-22 17:41:58 +00001037 sqlite3OsLeaveMutex();
danielk19772b444852004-06-29 07:45:33 +00001038 TRACE4("LOCK %d %s %s\n", id->h, locktypeName(locktype),
1039 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001040 return rc;
1041}
1042
1043/*
drha6abd042004-06-09 17:37:22 +00001044** Lower the locking level on file descriptor id to locktype. locktype
1045** must be either NO_LOCK or SHARED_LOCK.
1046**
1047** If the locking level of the file descriptor is already at or below
1048** the requested locking level, this routine is a no-op.
1049**
drh9c105bb2004-10-02 20:38:28 +00001050** It is not possible for this routine to fail if the second argument
1051** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1052** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001053*/
drha6abd042004-06-09 17:37:22 +00001054int sqlite3OsUnlock(OsFile *id, int locktype){
1055 struct lockInfo *pLock;
1056 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001057 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001058
drhda71ce12004-06-21 18:14:45 +00001059 assert( id->isOpen );
danielk19772b444852004-06-29 07:45:33 +00001060 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", id->h, locktype, id->locktype,
1061 id->pLock->locktype, id->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001062
1063 assert( locktype<=SHARED_LOCK );
1064 if( id->locktype<=locktype ){
1065 return SQLITE_OK;
1066 }
drhbbd42a62004-05-22 17:41:58 +00001067 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +00001068 pLock = id->pLock;
1069 assert( pLock->cnt!=0 );
1070 if( id->locktype>SHARED_LOCK ){
1071 assert( pLock->locktype==id->locktype );
drh9c105bb2004-10-02 20:38:28 +00001072 if( locktype==SHARED_LOCK ){
1073 lock.l_type = F_RDLCK;
1074 lock.l_whence = SEEK_SET;
1075 lock.l_start = SHARED_FIRST;
1076 lock.l_len = SHARED_SIZE;
1077 if( fcntl(id->h, F_SETLK, &lock)!=0 ){
1078 /* This should never happen */
1079 rc = SQLITE_IOERR;
1080 }
1081 }
drhbbd42a62004-05-22 17:41:58 +00001082 lock.l_type = F_UNLCK;
1083 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001084 lock.l_start = PENDING_BYTE;
1085 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1086 fcntl(id->h, F_SETLK, &lock);
1087 pLock->locktype = SHARED_LOCK;
drhbbd42a62004-05-22 17:41:58 +00001088 }
drha6abd042004-06-09 17:37:22 +00001089 if( locktype==NO_LOCK ){
1090 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001091
drha6abd042004-06-09 17:37:22 +00001092 /* Decrement the shared lock counter. Release the lock using an
1093 ** OS call only when all threads in this same process have released
1094 ** the lock.
1095 */
1096 pLock->cnt--;
1097 if( pLock->cnt==0 ){
1098 lock.l_type = F_UNLCK;
1099 lock.l_whence = SEEK_SET;
1100 lock.l_start = lock.l_len = 0L;
1101 fcntl(id->h, F_SETLK, &lock);
1102 pLock->locktype = NO_LOCK;
1103 }
1104
drhbbd42a62004-05-22 17:41:58 +00001105 /* Decrement the count of locks against this same file. When the
1106 ** count reaches zero, close any other file descriptors whose close
1107 ** was deferred because of outstanding locks.
1108 */
drha6abd042004-06-09 17:37:22 +00001109 pOpen = id->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001110 pOpen->nLock--;
1111 assert( pOpen->nLock>=0 );
1112 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1113 int i;
1114 for(i=0; i<pOpen->nPending; i++){
1115 close(pOpen->aPending[i]);
1116 }
1117 sqliteFree(pOpen->aPending);
1118 pOpen->nPending = 0;
1119 pOpen->aPending = 0;
1120 }
1121 }
1122 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +00001123 id->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001124 return rc;
drhbbd42a62004-05-22 17:41:58 +00001125}
1126
1127/*
danielk1977e3026632004-06-22 11:29:02 +00001128** Close a file.
1129*/
1130int sqlite3OsClose(OsFile *id){
1131 if( !id->isOpen ) return SQLITE_OK;
1132 sqlite3OsUnlock(id, NO_LOCK);
1133 if( id->dirfd>=0 ) close(id->dirfd);
1134 id->dirfd = -1;
1135 sqlite3OsEnterMutex();
1136 if( id->pOpen->nLock ){
1137 /* If there are outstanding locks, do not actually close the file just
1138 ** yet because that would clear those locks. Instead, add the file
1139 ** descriptor to pOpen->aPending. It will be automatically closed when
1140 ** the last lock is cleared.
1141 */
1142 int *aNew;
1143 struct openCnt *pOpen = id->pOpen;
1144 pOpen->nPending++;
1145 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1146 if( aNew==0 ){
1147 /* If a malloc fails, just leak the file descriptor */
1148 }else{
1149 pOpen->aPending = aNew;
1150 pOpen->aPending[pOpen->nPending-1] = id->h;
1151 }
1152 }else{
1153 /* There are no outstanding locks so we can close the file immediately */
1154 close(id->h);
1155 }
1156 releaseLockInfo(id->pLock);
1157 releaseOpenCnt(id->pOpen);
1158 sqlite3OsLeaveMutex();
1159 id->isOpen = 0;
1160 TRACE2("CLOSE %-3d\n", id->h);
1161 OpenCounter(-1);
1162 return SQLITE_OK;
1163}
1164
1165/*
drhbbd42a62004-05-22 17:41:58 +00001166** Get information to seed the random number generator. The seed
1167** is written into the buffer zBuf[256]. The calling function must
1168** supply a sufficiently large buffer.
1169*/
1170int sqlite3OsRandomSeed(char *zBuf){
1171 /* We have to initialize zBuf to prevent valgrind from reporting
1172 ** errors. The reports issued by valgrind are incorrect - we would
1173 ** prefer that the randomness be increased by making use of the
1174 ** uninitialized space in zBuf - but valgrind errors tend to worry
1175 ** some users. Rather than argue, it seems easier just to initialize
1176 ** the whole array and silence valgrind, even if that means less randomness
1177 ** in the random seed.
1178 **
1179 ** When testing, initializing zBuf[] to zero is all we do. That means
1180 ** that we always use the same random number sequence.* This makes the
1181 ** tests repeatable.
1182 */
1183 memset(zBuf, 0, 256);
1184#if !defined(SQLITE_TEST)
1185 {
1186 int pid;
1187 time((time_t*)zBuf);
1188 pid = getpid();
1189 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1190 }
1191#endif
1192 return SQLITE_OK;
1193}
1194
1195/*
1196** Sleep for a little while. Return the amount of time slept.
1197*/
1198int sqlite3OsSleep(int ms){
1199#if defined(HAVE_USLEEP) && HAVE_USLEEP
1200 usleep(ms*1000);
1201 return ms;
1202#else
1203 sleep((ms+999)/1000);
1204 return 1000*((ms+999)/1000);
1205#endif
1206}
1207
1208/*
1209** Static variables used for thread synchronization
1210*/
1211static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001212#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001213static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001214#endif
drhbbd42a62004-05-22 17:41:58 +00001215
1216/*
1217** The following pair of routine implement mutual exclusion for
1218** multi-threaded processes. Only a single thread is allowed to
1219** executed code that is surrounded by EnterMutex() and LeaveMutex().
1220**
1221** SQLite uses only a single Mutex. There is not much critical
1222** code and what little there is executes quickly and without blocking.
1223*/
1224void sqlite3OsEnterMutex(){
1225#ifdef SQLITE_UNIX_THREADS
1226 pthread_mutex_lock(&mutex);
1227#endif
1228 assert( !inMutex );
1229 inMutex = 1;
1230}
1231void sqlite3OsLeaveMutex(){
1232 assert( inMutex );
1233 inMutex = 0;
1234#ifdef SQLITE_UNIX_THREADS
1235 pthread_mutex_unlock(&mutex);
1236#endif
1237}
1238
1239/*
1240** Turn a relative pathname into a full pathname. Return a pointer
1241** to the full pathname stored in space obtained from sqliteMalloc().
1242** The calling function is responsible for freeing this space once it
1243** is no longer needed.
1244*/
1245char *sqlite3OsFullPathname(const char *zRelative){
1246 char *zFull = 0;
1247 if( zRelative[0]=='/' ){
1248 sqlite3SetString(&zFull, zRelative, (char*)0);
1249 }else{
1250 char zBuf[5000];
1251 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1252 (char*)0);
1253 }
1254 return zFull;
1255}
1256
1257/*
1258** The following variable, if set to a non-zero value, becomes the result
1259** returned from sqlite3OsCurrentTime(). This is used for testing.
1260*/
1261#ifdef SQLITE_TEST
1262int sqlite3_current_time = 0;
1263#endif
1264
1265/*
1266** Find the current time (in Universal Coordinated Time). Write the
1267** current time and date as a Julian Day number into *prNow and
1268** return 0. Return 1 if the time and date cannot be found.
1269*/
1270int sqlite3OsCurrentTime(double *prNow){
1271 time_t t;
1272 time(&t);
1273 *prNow = t/86400.0 + 2440587.5;
1274#ifdef SQLITE_TEST
1275 if( sqlite3_current_time ){
1276 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1277 }
1278#endif
1279 return 0;
1280}
1281
drhfd69dd62004-06-29 11:08:19 +00001282#if 0 /* NOT USED */
drhbf9a7e42004-06-15 00:29:03 +00001283/*
1284** Find the time that the file was last modified. Write the
1285** modification time and date as a Julian Day number into *prNow and
1286** return SQLITE_OK. Return SQLITE_ERROR if the modification
1287** time cannot be found.
1288*/
1289int sqlite3OsFileModTime(OsFile *id, double *prNow){
1290 int rc;
1291 struct stat statbuf;
1292 if( fstat(id->h, &statbuf)==0 ){
1293 *prNow = statbuf.st_mtime/86400.0 + 2440587.5;
1294 rc = SQLITE_OK;
1295 }else{
1296 rc = SQLITE_ERROR;
1297 }
1298 return rc;
1299}
drhfd69dd62004-06-29 11:08:19 +00001300#endif /* NOT USED */
drhbf9a7e42004-06-15 00:29:03 +00001301
drhbbd42a62004-05-22 17:41:58 +00001302#endif /* OS_UNIX */