blob: 11e718290b00b893f86667d3f18aaea2e6270758 [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*/
15#include "os.h" /* Must be first to enable large file support */
16#if OS_UNIX /* This file is used on unix only */
17#include "sqliteInt.h"
18
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
37/*
38** The DJGPP compiler environment looks mostly like Unix, but it
39** lacks the fcntl() system call. So redefine fcntl() to be something
40** that always succeeds. This means that locking does not occur under
41** DJGPP. But its DOS - what did you expect?
42*/
43#ifdef __DJGPP__
44# define fcntl(A,B,C) 0
45#endif
46
47/*
48** Macros used to determine whether or not to use threads. The
49** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
50** Posix threads and SQLITE_W32_THREADS is defined if we are
51** synchronizing using Win32 threads.
52*/
53#if defined(THREADSAFE) && THREADSAFE
54# include <pthread.h>
55# define SQLITE_UNIX_THREADS 1
56#endif
57
58
59/*
60** Include code that is common to all os_*.c files
61*/
62#include "os_common.h"
63
drh0bb132b2004-07-20 14:06:51 +000064#if defined(THREADSAFE) && THREADSAFE && defined(__linux__)
danielk197713adf8a2004-06-03 16:08:41 +000065#define getpid pthread_self
66#endif
67
drhbbd42a62004-05-22 17:41:58 +000068/*
69** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
70** section 6.5.2.2 lines 483 through 490 specify that when a process
71** sets or clears a lock, that operation overrides any prior locks set
72** by the same process. It does not explicitly say so, but this implies
73** that it overrides locks set by the same process using a different
74** file descriptor. Consider this test case:
75**
76** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
77** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
78**
79** Suppose ./file1 and ./file2 are really the same file (because
80** one is a hard or symbolic link to the other) then if you set
81** an exclusive lock on fd1, then try to get an exclusive lock
82** on fd2, it works. I would have expected the second lock to
83** fail since there was already a lock on the file due to fd1.
84** But not so. Since both locks came from the same process, the
85** second overrides the first, even though they were on different
86** file descriptors opened on different file names.
87**
88** Bummer. If you ask me, this is broken. Badly broken. It means
89** that we cannot use POSIX locks to synchronize file access among
90** competing threads of the same process. POSIX locks will work fine
91** to synchronize access for threads in separate processes, but not
92** threads within the same process.
93**
94** To work around the problem, SQLite has to manage file locks internally
95** on its own. Whenever a new database is opened, we have to find the
96** specific inode of the database file (the inode is determined by the
97** st_dev and st_ino fields of the stat structure that fstat() fills in)
98** and check for locks already existing on that inode. When locks are
99** created or removed, we have to look at our own internal record of the
100** locks to see if another thread has previously set a lock on that same
101** inode.
102**
103** The OsFile structure for POSIX is no longer just an integer file
104** descriptor. It is now a structure that holds the integer file
105** descriptor and a pointer to a structure that describes the internal
106** locks on the corresponding inode. There is one locking structure
107** per inode, so if the same inode is opened twice, both OsFile structures
108** point to the same locking structure. The locking structure keeps
109** a reference count (so we will know when to delete it) and a "cnt"
110** field that tells us its internal lock status. cnt==0 means the
111** file is unlocked. cnt==-1 means the file has an exclusive lock.
112** cnt>0 means there are cnt shared locks on the file.
113**
114** Any attempt to lock or unlock a file first checks the locking
115** structure. The fcntl() system call is only invoked to set a
116** POSIX lock if the internal lock structure transitions between
117** a locked and an unlocked state.
118**
119** 2004-Jan-11:
120** More recent discoveries about POSIX advisory locks. (The more
121** I discover, the more I realize the a POSIX advisory locks are
122** an abomination.)
123**
124** If you close a file descriptor that points to a file that has locks,
125** all locks on that file that are owned by the current process are
126** released. To work around this problem, each OsFile structure contains
127** a pointer to an openCnt structure. There is one openCnt structure
128** per open inode, which means that multiple OsFiles can point to a single
129** openCnt. When an attempt is made to close an OsFile, if there are
130** other OsFiles open on the same inode that are holding locks, the call
131** to close() the file descriptor is deferred until all of the locks clear.
132** The openCnt structure keeps a list of file descriptors that need to
133** be closed and that list is walked (and cleared) when the last lock
134** clears.
135**
136** First, under Linux threads, because each thread has a separate
137** process ID, lock operations in one thread do not override locks
138** to the same file in other threads. Linux threads behave like
139** separate processes in this respect. But, if you close a file
140** descriptor in linux threads, all locks are cleared, even locks
141** on other threads and even though the other threads have different
142** process IDs. Linux threads is inconsistent in this respect.
143** (I'm beginning to think that linux threads is an abomination too.)
144** The consequence of this all is that the hash table for the lockInfo
145** structure has to include the process id as part of its key because
146** locks in different threads are treated as distinct. But the
147** openCnt structure should not include the process id in its
148** key because close() clears lock on all threads, not just the current
149** thread. Were it not for this goofiness in linux threads, we could
150** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000151**
152** 2004-Jun-28:
153** On some versions of linux, threads can override each others locks.
154** On others not. Sometimes you can change the behavior on the same
155** system by setting the LD_ASSUME_KERNEL environment variable. The
156** POSIX standard is silent as to which behavior is correct, as far
157** as I can tell, so other versions of unix might show the same
158** inconsistency. There is no little doubt in my mind that posix
159** advisory locks and linux threads are profoundly broken.
160**
161** To work around the inconsistencies, we have to test at runtime
162** whether or not threads can override each others locks. This test
163** is run once, the first time any lock is attempted. A static
164** variable is set to record the results of this test for future
165** use.
drhbbd42a62004-05-22 17:41:58 +0000166*/
167
168/*
169** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000170** to locate a particular lockInfo structure given its inode.
171**
172** If threads cannot override each others locks, then we set the
173** lockKey.tid field to the thread ID. If threads can override
174** each others locks then tid is always set to zero. tid is also
175** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000176*/
177struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000178 dev_t dev; /* Device number */
179 ino_t ino; /* Inode number */
180#ifdef SQLITE_UNIX_THREADS
181 pthread_t tid; /* Thread ID or zero if threads cannot override each other */
182#endif
drhbbd42a62004-05-22 17:41:58 +0000183};
184
185/*
186** An instance of the following structure is allocated for each open
187** inode on each thread with a different process ID. (Threads have
188** different process IDs on linux, but not on most other unixes.)
189**
190** A single inode can have multiple file descriptors, so each OsFile
191** structure contains a pointer to an instance of this object and this
192** object keeps a count of the number of OsFiles pointing to it.
193*/
194struct lockInfo {
195 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000196 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000197 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000198 int nRef; /* Number of pointers to this structure */
199};
200
201/*
202** An instance of the following structure serves as the key used
203** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000204** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000205*/
206struct openKey {
207 dev_t dev; /* Device number */
208 ino_t ino; /* Inode number */
209};
210
211/*
212** An instance of the following structure is allocated for each open
213** inode. This structure keeps track of the number of locks on that
214** inode. If a close is attempted against an inode that is holding
215** locks, the close is deferred until all locks clear by adding the
216** file descriptor to be closed to the pending list.
217*/
218struct openCnt {
219 struct openKey key; /* The lookup key */
220 int nRef; /* Number of pointers to this structure */
221 int nLock; /* Number of outstanding locks */
222 int nPending; /* Number of pending close() operations */
223 int *aPending; /* Malloced space holding fd's awaiting a close() */
224};
225
226/*
227** These hash table maps inodes and process IDs into lockInfo and openCnt
228** structures. Access to these hash tables must be protected by a mutex.
229*/
230static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
231static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
232
drh5fdae772004-06-29 03:29:00 +0000233
234#ifdef SQLITE_UNIX_THREADS
235/*
236** This variable records whether or not threads can override each others
237** locks.
238**
239** 0: No. Threads cannot override each others locks.
240** 1: Yes. Threads can override each others locks.
241** -1: We don't know yet.
242*/
243static int threadsOverrideEachOthersLocks = -1;
244
245/*
246** This structure holds information passed into individual test
247** threads by the testThreadLockingBehavior() routine.
248*/
249struct threadTestData {
250 int fd; /* File to be locked */
251 struct flock lock; /* The locking operation */
252 int result; /* Result of the locking operation */
253};
254
255/*
256** The testThreadLockingBehavior() routine launches two separate
257** threads on this routine. This routine attempts to lock a file
258** descriptor then returns. The success or failure of that attempt
259** allows the testThreadLockingBehavior() procedure to determine
260** whether or not threads can override each others locks.
261*/
262static void *threadLockingTest(void *pArg){
263 struct threadTestData *pData = (struct threadTestData*)pArg;
264 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
265 return pArg;
266}
267
268/*
269** This procedure attempts to determine whether or not threads
270** can override each others locks then sets the
271** threadsOverrideEachOthersLocks variable appropriately.
272*/
273static void testThreadLockingBehavior(fd_orig){
274 int fd;
275 struct threadTestData d[2];
276 pthread_t t[2];
277
278 fd = dup(fd_orig);
279 if( fd<0 ) return;
280 memset(d, 0, sizeof(d));
281 d[0].fd = fd;
282 d[0].lock.l_type = F_RDLCK;
283 d[0].lock.l_len = 1;
284 d[0].lock.l_start = 0;
285 d[0].lock.l_whence = SEEK_SET;
286 d[1] = d[0];
287 d[1].lock.l_type = F_WRLCK;
288 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
289 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
290 pthread_join(t[0], 0);
291 pthread_join(t[1], 0);
292 close(fd);
293 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
294}
295#endif /* SQLITE_UNIX_THREADS */
296
drhbbd42a62004-05-22 17:41:58 +0000297/*
298** Release a lockInfo structure previously allocated by findLockInfo().
299*/
300static void releaseLockInfo(struct lockInfo *pLock){
301 pLock->nRef--;
302 if( pLock->nRef==0 ){
303 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
304 sqliteFree(pLock);
305 }
306}
307
308/*
309** Release a openCnt structure previously allocated by findLockInfo().
310*/
311static void releaseOpenCnt(struct openCnt *pOpen){
312 pOpen->nRef--;
313 if( pOpen->nRef==0 ){
314 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
315 sqliteFree(pOpen->aPending);
316 sqliteFree(pOpen);
317 }
318}
319
320/*
321** Given a file descriptor, locate lockInfo and openCnt structures that
322** describes that file descriptor. Create a new ones if necessary. The
323** return values might be unset if an error occurs.
324**
325** Return the number of errors.
326*/
drh38f82712004-06-18 17:10:16 +0000327static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000328 int fd, /* The file descriptor used in the key */
329 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000330 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000331){
332 int rc;
333 struct lockKey key1;
334 struct openKey key2;
335 struct stat statbuf;
336 struct lockInfo *pLock;
337 struct openCnt *pOpen;
338 rc = fstat(fd, &statbuf);
339 if( rc!=0 ) return 1;
340 memset(&key1, 0, sizeof(key1));
341 key1.dev = statbuf.st_dev;
342 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000343#ifdef SQLITE_UNIX_THREADS
344 if( threadsOverrideEachOthersLocks<0 ){
345 testThreadLockingBehavior(fd);
346 }
347 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
348#endif
drhbbd42a62004-05-22 17:41:58 +0000349 memset(&key2, 0, sizeof(key2));
350 key2.dev = statbuf.st_dev;
351 key2.ino = statbuf.st_ino;
352 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
353 if( pLock==0 ){
354 struct lockInfo *pOld;
355 pLock = sqliteMallocRaw( sizeof(*pLock) );
356 if( pLock==0 ) return 1;
357 pLock->key = key1;
358 pLock->nRef = 1;
359 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000360 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000361 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
362 if( pOld!=0 ){
363 assert( pOld==pLock );
364 sqliteFree(pLock);
365 return 1;
366 }
367 }else{
368 pLock->nRef++;
369 }
370 *ppLock = pLock;
371 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
372 if( pOpen==0 ){
373 struct openCnt *pOld;
374 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
375 if( pOpen==0 ){
376 releaseLockInfo(pLock);
377 return 1;
378 }
379 pOpen->key = key2;
380 pOpen->nRef = 1;
381 pOpen->nLock = 0;
382 pOpen->nPending = 0;
383 pOpen->aPending = 0;
384 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
385 if( pOld!=0 ){
386 assert( pOld==pOpen );
387 sqliteFree(pOpen);
388 releaseLockInfo(pLock);
389 return 1;
390 }
391 }else{
392 pOpen->nRef++;
393 }
394 *ppOpen = pOpen;
395 return 0;
396}
397
398/*
399** Delete the named file
400*/
401int sqlite3OsDelete(const char *zFilename){
402 unlink(zFilename);
403 return SQLITE_OK;
404}
405
406/*
407** Return TRUE if the named file exists.
408*/
409int sqlite3OsFileExists(const char *zFilename){
410 return access(zFilename, 0)==0;
411}
412
413/*
414** Attempt to open a file for both reading and writing. If that
415** fails, try opening it read-only. If the file does not exist,
416** try to create it.
417**
418** On success, a handle for the open file is written to *id
419** and *pReadonly is set to 0 if the file was opened for reading and
420** writing or 1 if the file was opened read-only. The function returns
421** SQLITE_OK.
422**
423** On failure, the function returns SQLITE_CANTOPEN and leaves
424** *id and *pReadonly unchanged.
425*/
426int sqlite3OsOpenReadWrite(
427 const char *zFilename,
428 OsFile *id,
429 int *pReadonly
430){
431 int rc;
drhda71ce12004-06-21 18:14:45 +0000432 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000433 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000434 id->h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
435 if( id->h<0 ){
drh6458e392004-07-20 01:14:13 +0000436#ifdef EISDIR
437 if( errno==EISDIR ){
438 return SQLITE_CANTOPEN;
439 }
440#endif
drha6abd042004-06-09 17:37:22 +0000441 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
442 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000443 return SQLITE_CANTOPEN;
444 }
445 *pReadonly = 1;
446 }else{
447 *pReadonly = 0;
448 }
449 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000450 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000451 sqlite3OsLeaveMutex();
452 if( rc ){
drha6abd042004-06-09 17:37:22 +0000453 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000454 return SQLITE_NOMEM;
455 }
danielk197713adf8a2004-06-03 16:08:41 +0000456 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000457 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000458 TRACE3("OPEN %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000459 OpenCounter(+1);
460 return SQLITE_OK;
461}
462
463
464/*
465** Attempt to open a new file for exclusive access by this process.
466** The file will be opened for both reading and writing. To avoid
467** a potential security problem, we do not allow the file to have
468** previously existed. Nor do we allow the file to be a symbolic
469** link.
470**
471** If delFlag is true, then make arrangements to automatically delete
472** the file when it is closed.
473**
474** On success, write the file handle into *id and return SQLITE_OK.
475**
476** On failure, return SQLITE_CANTOPEN.
477*/
478int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
479 int rc;
drhda71ce12004-06-21 18:14:45 +0000480 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000481 if( access(zFilename, 0)==0 ){
482 return SQLITE_CANTOPEN;
483 }
484 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000485 id->h = open(zFilename,
drhbbd42a62004-05-22 17:41:58 +0000486 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
drha6abd042004-06-09 17:37:22 +0000487 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000488 return SQLITE_CANTOPEN;
489 }
490 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000491 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000492 sqlite3OsLeaveMutex();
493 if( rc ){
drha6abd042004-06-09 17:37:22 +0000494 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000495 unlink(zFilename);
496 return SQLITE_NOMEM;
497 }
danielk197713adf8a2004-06-03 16:08:41 +0000498 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000499 id->isOpen = 1;
drhbbd42a62004-05-22 17:41:58 +0000500 if( delFlag ){
501 unlink(zFilename);
502 }
drha6abd042004-06-09 17:37:22 +0000503 TRACE3("OPEN-EX %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000504 OpenCounter(+1);
505 return SQLITE_OK;
506}
507
508/*
509** Attempt to open a new file for read-only access.
510**
511** On success, write the file handle into *id and return SQLITE_OK.
512**
513** On failure, return SQLITE_CANTOPEN.
514*/
515int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
516 int rc;
drhda71ce12004-06-21 18:14:45 +0000517 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000518 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000519 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
520 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000521 return SQLITE_CANTOPEN;
522 }
523 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000524 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000525 sqlite3OsLeaveMutex();
526 if( rc ){
drha6abd042004-06-09 17:37:22 +0000527 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000528 return SQLITE_NOMEM;
529 }
danielk197713adf8a2004-06-03 16:08:41 +0000530 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000531 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000532 TRACE3("OPEN-RO %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000533 OpenCounter(+1);
534 return SQLITE_OK;
535}
536
537/*
538** Attempt to open a file descriptor for the directory that contains a
539** file. This file descriptor can be used to fsync() the directory
540** in order to make sure the creation of a new file is actually written
541** to disk.
542**
543** This routine is only meaningful for Unix. It is a no-op under
544** windows since windows does not support hard links.
545**
546** On success, a handle for a previously open file is at *id is
547** updated with the new directory file descriptor and SQLITE_OK is
548** returned.
549**
550** On failure, the function returns SQLITE_CANTOPEN and leaves
551** *id unchanged.
552*/
553int sqlite3OsOpenDirectory(
554 const char *zDirname,
555 OsFile *id
556){
drhda71ce12004-06-21 18:14:45 +0000557 if( !id->isOpen ){
drhbbd42a62004-05-22 17:41:58 +0000558 /* Do not open the directory if the corresponding file is not already
559 ** open. */
560 return SQLITE_CANTOPEN;
561 }
562 assert( id->dirfd<0 );
563 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
564 if( id->dirfd<0 ){
565 return SQLITE_CANTOPEN;
566 }
567 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
568 return SQLITE_OK;
569}
570
571/*
drhab3f9fe2004-08-14 17:10:10 +0000572** If the following global variable points to a string which is the
573** name of a directory, then that directory will be used to store
574** temporary files.
575*/
576const char *sqlite_temp_directory = 0;
577
578/*
drhbbd42a62004-05-22 17:41:58 +0000579** Create a temporary file name in zBuf. zBuf must be big enough to
580** hold at least SQLITE_TEMPNAME_SIZE characters.
581*/
582int sqlite3OsTempFileName(char *zBuf){
583 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000584 0,
drhbbd42a62004-05-22 17:41:58 +0000585 "/var/tmp",
586 "/usr/tmp",
587 "/tmp",
588 ".",
589 };
590 static unsigned char zChars[] =
591 "abcdefghijklmnopqrstuvwxyz"
592 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
593 "0123456789";
594 int i, j;
595 struct stat buf;
596 const char *zDir = ".";
drhab3f9fe2004-08-14 17:10:10 +0000597 azDirs[0] = sqlite_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000598 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000599 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000600 if( stat(azDirs[i], &buf) ) continue;
601 if( !S_ISDIR(buf.st_mode) ) continue;
602 if( access(azDirs[i], 07) ) continue;
603 zDir = azDirs[i];
604 break;
605 }
606 do{
607 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
608 j = strlen(zBuf);
609 sqlite3Randomness(15, &zBuf[j]);
610 for(i=0; i<15; i++, j++){
611 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
612 }
613 zBuf[j] = 0;
614 }while( access(zBuf,0)==0 );
615 return SQLITE_OK;
616}
617
618/*
drhbbd42a62004-05-22 17:41:58 +0000619** Read data from a file into a buffer. Return SQLITE_OK if all
620** bytes were read successfully and SQLITE_IOERR if anything goes
621** wrong.
622*/
623int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
624 int got;
drhda71ce12004-06-21 18:14:45 +0000625 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000626 SimulateIOError(SQLITE_IOERR);
627 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000628 got = read(id->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000629 TIMER_END;
drha9600bc2004-08-04 14:44:33 +0000630 TRACE4("READ %-3d %7d %d\n", id->h, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000631 SEEK(0);
632 /* if( got<0 ) got = 0; */
633 if( got==amt ){
634 return SQLITE_OK;
635 }else{
636 return SQLITE_IOERR;
637 }
638}
639
640/*
641** Write data from a buffer into a file. Return SQLITE_OK on success
642** or some other error code on failure.
643*/
644int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
645 int wrote = 0;
drhda71ce12004-06-21 18:14:45 +0000646 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000647 SimulateIOError(SQLITE_IOERR);
648 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000649 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000650 amt -= wrote;
651 pBuf = &((char*)pBuf)[wrote];
652 }
653 TIMER_END;
drha9600bc2004-08-04 14:44:33 +0000654 TRACE4("WRITE %-3d %7d %d\n", id->h, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000655 SEEK(0);
656 if( amt>0 ){
657 return SQLITE_FULL;
658 }
659 return SQLITE_OK;
660}
661
662/*
663** Move the read/write pointer in a file.
664*/
665int sqlite3OsSeek(OsFile *id, off_t offset){
drhda71ce12004-06-21 18:14:45 +0000666 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000667 SEEK(offset/1024 + 1);
drha6abd042004-06-09 17:37:22 +0000668 lseek(id->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000669 return SQLITE_OK;
670}
671
672/*
drhdd809b02004-07-17 21:44:57 +0000673** The fsync() system call does not work as advertised on many
674** unix systems. The following procedure is an attempt to make
675** it work better.
676*/
677static int full_fsync(int fd){
678 int rc;
679#ifdef F_FULLFSYNC
680 rc = fcntl(fd, F_FULLFSYNC, 0);
681 if( rc ) rc = fsync(fd);
682#else
683 rc = fsync(fd);
684#endif
685 return rc;
686}
687
688/*
drhbbd42a62004-05-22 17:41:58 +0000689** Make sure all writes to a particular file are committed to disk.
690**
691** Under Unix, also make sure that the directory entry for the file
692** has been created by fsync-ing the directory that contains the file.
693** If we do not do this and we encounter a power failure, the directory
694** entry for the journal might not exist after we reboot. The next
695** SQLite to access the file will not know that the journal exists (because
696** the directory entry for the journal was never created) and the transaction
697** will not roll back - possibly leading to database corruption.
698*/
699int sqlite3OsSync(OsFile *id){
drhda71ce12004-06-21 18:14:45 +0000700 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000701 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000702 TRACE2("SYNC %-3d\n", id->h);
drhdd809b02004-07-17 21:44:57 +0000703 if( full_fsync(id->h) ){
drhbbd42a62004-05-22 17:41:58 +0000704 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000705 }
drha2854222004-06-17 19:04:17 +0000706 if( id->dirfd>=0 ){
707 TRACE2("DIRSYNC %-3d\n", id->dirfd);
drhdd809b02004-07-17 21:44:57 +0000708 full_fsync(id->dirfd);
drha2854222004-06-17 19:04:17 +0000709 close(id->dirfd); /* Only need to sync once, so close the directory */
710 id->dirfd = -1; /* when we are done. */
711 }
drha2854222004-06-17 19:04:17 +0000712 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000713}
714
715/*
danielk1977962398d2004-06-14 09:35:16 +0000716** Sync the directory zDirname. This is a no-op on operating systems other
717** than UNIX.
718*/
719int sqlite3OsSyncDirectory(const char *zDirname){
720 int fd;
721 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000722 SimulateIOError(SQLITE_IOERR);
danielk1977962398d2004-06-14 09:35:16 +0000723 fd = open(zDirname, O_RDONLY|O_BINARY, 0644);
danielk1977369f27e2004-06-15 11:40:04 +0000724 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000725 if( fd<0 ){
726 return SQLITE_CANTOPEN;
727 }
728 r = fsync(fd);
729 close(fd);
730 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
731}
732
733/*
drhbbd42a62004-05-22 17:41:58 +0000734** Truncate an open file to a specified size
735*/
736int sqlite3OsTruncate(OsFile *id, off_t nByte){
drhda71ce12004-06-21 18:14:45 +0000737 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000738 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000739 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000740}
741
742/*
743** Determine the current size of a file in bytes
744*/
745int sqlite3OsFileSize(OsFile *id, off_t *pSize){
746 struct stat buf;
drhda71ce12004-06-21 18:14:45 +0000747 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000748 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000749 if( fstat(id->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +0000750 return SQLITE_IOERR;
751 }
752 *pSize = buf.st_size;
753 return SQLITE_OK;
754}
755
danielk19779a1d0ab2004-06-01 14:09:28 +0000756/*
danielk197713adf8a2004-06-03 16:08:41 +0000757** This routine checks if there is a RESERVED lock held on the specified
758** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000759** non-zero. If the file is unlocked or holds only SHARED locks, then
760** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000761*/
drha6abd042004-06-09 17:37:22 +0000762int sqlite3OsCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +0000763 int r = 0;
764
drhda71ce12004-06-21 18:14:45 +0000765 assert( id->isOpen );
drh2ac3ee92004-06-07 16:27:46 +0000766 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000767
768 /* Check if a thread in this process holds such a lock */
769 if( id->pLock->locktype>SHARED_LOCK ){
770 r = 1;
771 }
772
drh2ac3ee92004-06-07 16:27:46 +0000773 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000774 */
775 if( !r ){
776 struct flock lock;
777 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000778 lock.l_start = RESERVED_BYTE;
779 lock.l_len = 1;
780 lock.l_type = F_WRLCK;
drha6abd042004-06-09 17:37:22 +0000781 fcntl(id->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +0000782 if( lock.l_type!=F_UNLCK ){
783 r = 1;
784 }
785 }
786
787 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000788 TRACE3("TEST WR-LOCK %d %d\n", id->h, r);
danielk197713adf8a2004-06-03 16:08:41 +0000789
790 return r;
791}
792
danielk19772b444852004-06-29 07:45:33 +0000793#ifdef SQLITE_DEBUG
794/*
795** Helper function for printing out trace information from debugging
796** binaries. This returns the string represetation of the supplied
797** integer lock-type.
798*/
799static const char * locktypeName(int locktype){
800 switch( locktype ){
801 case NO_LOCK: return "NONE";
802 case SHARED_LOCK: return "SHARED";
803 case RESERVED_LOCK: return "RESERVED";
804 case PENDING_LOCK: return "PENDING";
805 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
806 }
807 return "ERROR";
808}
809#endif
810
danielk197713adf8a2004-06-03 16:08:41 +0000811/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000812** Lock the file with the lock specified by parameter locktype - one
813** of the following:
814**
drh2ac3ee92004-06-07 16:27:46 +0000815** (1) SHARED_LOCK
816** (2) RESERVED_LOCK
817** (3) PENDING_LOCK
818** (4) EXCLUSIVE_LOCK
819**
drhb3e04342004-06-08 00:47:47 +0000820** Sometimes when requesting one lock state, additional lock states
821** are inserted in between. The locking might fail on one of the later
822** transitions leaving the lock state different from what it started but
823** still short of its goal. The following chart shows the allowed
824** transitions and the inserted intermediate states:
825**
826** UNLOCKED -> SHARED
827** SHARED -> RESERVED
828** SHARED -> (PENDING) -> EXCLUSIVE
829** RESERVED -> (PENDING) -> EXCLUSIVE
830** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000831**
drha6abd042004-06-09 17:37:22 +0000832** This routine will only increase a lock. Use the sqlite3OsUnlock()
833** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000834*/
835int sqlite3OsLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +0000836 /* The following describes the implementation of the various locks and
837 ** lock transitions in terms of the POSIX advisory shared and exclusive
838 ** lock primitives (called read-locks and write-locks below, to avoid
839 ** confusion with SQLite lock names). The algorithms are complicated
840 ** slightly in order to be compatible with windows systems simultaneously
841 ** accessing the same database file, in case that is ever required.
842 **
843 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
844 ** byte', each single bytes at well known offsets, and the 'shared byte
845 ** range', a range of 510 bytes at a well known offset.
846 **
847 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
848 ** byte'. If this is successful, a random byte from the 'shared byte
849 ** range' is read-locked and the lock on the 'pending byte' released.
850 **
danielk197790ba3bd2004-06-25 08:32:25 +0000851 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
852 ** A RESERVED lock is implemented by grabbing a write-lock on the
853 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000854 **
855 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000856 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
857 ** on the 'pending byte'. This ensures that no new SHARED locks can be
858 ** obtained, but existing SHARED locks are allowed to persist. A process
859 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
860 ** This property is used by the algorithm for rolling back a journal file
861 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000862 **
danielk197790ba3bd2004-06-25 08:32:25 +0000863 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
864 ** implemented by obtaining a write-lock on the entire 'shared byte
865 ** range'. Since all other locks require a read-lock on one of the bytes
866 ** within this range, this ensures that no other locks are held on the
867 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000868 **
869 ** The reason a single byte cannot be used instead of the 'shared byte
870 ** range' is that some versions of windows do not support read-locks. By
871 ** locking a random byte from a range, concurrent SHARED locks may exist
872 ** even if the locking primitive used is always a write-lock.
873 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000874 int rc = SQLITE_OK;
875 struct lockInfo *pLock = id->pLock;
876 struct flock lock;
877 int s;
878
drhda71ce12004-06-21 18:14:45 +0000879 assert( id->isOpen );
danielk19772b444852004-06-29 07:45:33 +0000880 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", id->h, locktypeName(locktype),
881 locktypeName(id->locktype), locktypeName(pLock->locktype), pLock->cnt
882 ,getpid() );
danielk19779a1d0ab2004-06-01 14:09:28 +0000883
884 /* If there is already a lock of this type or more restrictive on the
885 ** OsFile, do nothing. Don't use the end_lock: exit path, as
886 ** sqlite3OsEnterMutex() hasn't been called yet.
887 */
danielk197713adf8a2004-06-03 16:08:41 +0000888 if( id->locktype>=locktype ){
danielk19772b444852004-06-29 07:45:33 +0000889 TRACE3("LOCK %d %s ok (already held)\n", id->h, locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +0000890 return SQLITE_OK;
891 }
892
drhb3e04342004-06-08 00:47:47 +0000893 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +0000894 */
drhb3e04342004-06-08 00:47:47 +0000895 assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );
896 assert( locktype!=PENDING_LOCK );
897 assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000898
drhb3e04342004-06-08 00:47:47 +0000899 /* This mutex is needed because id->pLock is shared across threads
900 */
901 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +0000902
903 /* If some thread using this PID has a lock via a different OsFile*
904 ** handle that precludes the requested lock, return BUSY.
905 */
danielk197713adf8a2004-06-03 16:08:41 +0000906 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +0000907 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +0000908 ){
909 rc = SQLITE_BUSY;
910 goto end_lock;
911 }
912
913 /* If a SHARED lock is requested, and some thread using this PID already
914 ** has a SHARED or RESERVED lock, then increment reference counts and
915 ** return SQLITE_OK.
916 */
917 if( locktype==SHARED_LOCK &&
918 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
919 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +0000920 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +0000921 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +0000922 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +0000923 pLock->cnt++;
924 id->pOpen->nLock++;
925 goto end_lock;
926 }
927
danielk197713adf8a2004-06-03 16:08:41 +0000928 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000929 lock.l_whence = SEEK_SET;
930
drh3cde3bb2004-06-12 02:17:14 +0000931 /* A PENDING lock is needed before acquiring a SHARED lock and before
932 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
933 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +0000934 */
drh3cde3bb2004-06-12 02:17:14 +0000935 if( locktype==SHARED_LOCK
936 || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)
937 ){
danielk1977489468c2004-06-28 08:25:47 +0000938 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +0000939 lock.l_start = PENDING_BYTE;
drha6abd042004-06-09 17:37:22 +0000940 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000941 if( s ){
942 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
943 goto end_lock;
944 }
drh3cde3bb2004-06-12 02:17:14 +0000945 }
946
947
948 /* If control gets to this point, then actually go ahead and make
949 ** operating system calls for the specified lock.
950 */
951 if( locktype==SHARED_LOCK ){
952 assert( pLock->cnt==0 );
953 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +0000954
drh2ac3ee92004-06-07 16:27:46 +0000955 /* Now get the read-lock */
956 lock.l_start = SHARED_FIRST;
957 lock.l_len = SHARED_SIZE;
drha6abd042004-06-09 17:37:22 +0000958 s = fcntl(id->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +0000959
960 /* Drop the temporary PENDING lock */
961 lock.l_start = PENDING_BYTE;
962 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000963 lock.l_type = F_UNLCK;
drha6abd042004-06-09 17:37:22 +0000964 fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000965 if( s ){
drhbbd42a62004-05-22 17:41:58 +0000966 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
967 }else{
danielk197713adf8a2004-06-03 16:08:41 +0000968 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000969 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +0000970 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +0000971 }
drh3cde3bb2004-06-12 02:17:14 +0000972 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
973 /* We are trying for an exclusive lock but another thread in this
974 ** same process is still holding a shared lock. */
975 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +0000976 }else{
drh3cde3bb2004-06-12 02:17:14 +0000977 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +0000978 ** assumed that there is a SHARED or greater lock on the file
979 ** already.
980 */
danielk197713adf8a2004-06-03 16:08:41 +0000981 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +0000982 lock.l_type = F_WRLCK;
983 switch( locktype ){
984 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000985 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000986 break;
danielk19779a1d0ab2004-06-01 14:09:28 +0000987 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000988 lock.l_start = SHARED_FIRST;
989 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000990 break;
991 default:
992 assert(0);
993 }
drha6abd042004-06-09 17:37:22 +0000994 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000995 if( s ){
996 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
997 }
drhbbd42a62004-05-22 17:41:58 +0000998 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000999
danielk1977ecb2a962004-06-02 06:30:16 +00001000 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +00001001 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001002 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001003 }else if( locktype==EXCLUSIVE_LOCK ){
1004 id->locktype = PENDING_LOCK;
1005 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001006 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001007
1008end_lock:
drhbbd42a62004-05-22 17:41:58 +00001009 sqlite3OsLeaveMutex();
danielk19772b444852004-06-29 07:45:33 +00001010 TRACE4("LOCK %d %s %s\n", id->h, locktypeName(locktype),
1011 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001012 return rc;
1013}
1014
1015/*
drha6abd042004-06-09 17:37:22 +00001016** Lower the locking level on file descriptor id to locktype. locktype
1017** must be either NO_LOCK or SHARED_LOCK.
1018**
1019** If the locking level of the file descriptor is already at or below
1020** the requested locking level, this routine is a no-op.
1021**
1022** It is not possible for this routine to fail.
drhbbd42a62004-05-22 17:41:58 +00001023*/
drha6abd042004-06-09 17:37:22 +00001024int sqlite3OsUnlock(OsFile *id, int locktype){
1025 struct lockInfo *pLock;
1026 struct flock lock;
1027
drhda71ce12004-06-21 18:14:45 +00001028 assert( id->isOpen );
danielk19772b444852004-06-29 07:45:33 +00001029 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", id->h, locktype, id->locktype,
1030 id->pLock->locktype, id->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001031
1032 assert( locktype<=SHARED_LOCK );
1033 if( id->locktype<=locktype ){
1034 return SQLITE_OK;
1035 }
drhbbd42a62004-05-22 17:41:58 +00001036 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +00001037 pLock = id->pLock;
1038 assert( pLock->cnt!=0 );
1039 if( id->locktype>SHARED_LOCK ){
1040 assert( pLock->locktype==id->locktype );
drhbbd42a62004-05-22 17:41:58 +00001041 lock.l_type = F_UNLCK;
1042 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001043 lock.l_start = PENDING_BYTE;
1044 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1045 fcntl(id->h, F_SETLK, &lock);
1046 pLock->locktype = SHARED_LOCK;
drhbbd42a62004-05-22 17:41:58 +00001047 }
drha6abd042004-06-09 17:37:22 +00001048 if( locktype==NO_LOCK ){
1049 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001050
drha6abd042004-06-09 17:37:22 +00001051 /* Decrement the shared lock counter. Release the lock using an
1052 ** OS call only when all threads in this same process have released
1053 ** the lock.
1054 */
1055 pLock->cnt--;
1056 if( pLock->cnt==0 ){
1057 lock.l_type = F_UNLCK;
1058 lock.l_whence = SEEK_SET;
1059 lock.l_start = lock.l_len = 0L;
1060 fcntl(id->h, F_SETLK, &lock);
1061 pLock->locktype = NO_LOCK;
1062 }
1063
drhbbd42a62004-05-22 17:41:58 +00001064 /* Decrement the count of locks against this same file. When the
1065 ** count reaches zero, close any other file descriptors whose close
1066 ** was deferred because of outstanding locks.
1067 */
drha6abd042004-06-09 17:37:22 +00001068 pOpen = id->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001069 pOpen->nLock--;
1070 assert( pOpen->nLock>=0 );
1071 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1072 int i;
1073 for(i=0; i<pOpen->nPending; i++){
1074 close(pOpen->aPending[i]);
1075 }
1076 sqliteFree(pOpen->aPending);
1077 pOpen->nPending = 0;
1078 pOpen->aPending = 0;
1079 }
1080 }
1081 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +00001082 id->locktype = locktype;
1083 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001084}
1085
1086/*
danielk1977e3026632004-06-22 11:29:02 +00001087** Close a file.
1088*/
1089int sqlite3OsClose(OsFile *id){
1090 if( !id->isOpen ) return SQLITE_OK;
1091 sqlite3OsUnlock(id, NO_LOCK);
1092 if( id->dirfd>=0 ) close(id->dirfd);
1093 id->dirfd = -1;
1094 sqlite3OsEnterMutex();
1095 if( id->pOpen->nLock ){
1096 /* If there are outstanding locks, do not actually close the file just
1097 ** yet because that would clear those locks. Instead, add the file
1098 ** descriptor to pOpen->aPending. It will be automatically closed when
1099 ** the last lock is cleared.
1100 */
1101 int *aNew;
1102 struct openCnt *pOpen = id->pOpen;
1103 pOpen->nPending++;
1104 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1105 if( aNew==0 ){
1106 /* If a malloc fails, just leak the file descriptor */
1107 }else{
1108 pOpen->aPending = aNew;
1109 pOpen->aPending[pOpen->nPending-1] = id->h;
1110 }
1111 }else{
1112 /* There are no outstanding locks so we can close the file immediately */
1113 close(id->h);
1114 }
1115 releaseLockInfo(id->pLock);
1116 releaseOpenCnt(id->pOpen);
1117 sqlite3OsLeaveMutex();
1118 id->isOpen = 0;
1119 TRACE2("CLOSE %-3d\n", id->h);
1120 OpenCounter(-1);
1121 return SQLITE_OK;
1122}
1123
1124/*
drhbbd42a62004-05-22 17:41:58 +00001125** Get information to seed the random number generator. The seed
1126** is written into the buffer zBuf[256]. The calling function must
1127** supply a sufficiently large buffer.
1128*/
1129int sqlite3OsRandomSeed(char *zBuf){
1130 /* We have to initialize zBuf to prevent valgrind from reporting
1131 ** errors. The reports issued by valgrind are incorrect - we would
1132 ** prefer that the randomness be increased by making use of the
1133 ** uninitialized space in zBuf - but valgrind errors tend to worry
1134 ** some users. Rather than argue, it seems easier just to initialize
1135 ** the whole array and silence valgrind, even if that means less randomness
1136 ** in the random seed.
1137 **
1138 ** When testing, initializing zBuf[] to zero is all we do. That means
1139 ** that we always use the same random number sequence.* This makes the
1140 ** tests repeatable.
1141 */
1142 memset(zBuf, 0, 256);
1143#if !defined(SQLITE_TEST)
1144 {
1145 int pid;
1146 time((time_t*)zBuf);
1147 pid = getpid();
1148 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1149 }
1150#endif
1151 return SQLITE_OK;
1152}
1153
1154/*
1155** Sleep for a little while. Return the amount of time slept.
1156*/
1157int sqlite3OsSleep(int ms){
1158#if defined(HAVE_USLEEP) && HAVE_USLEEP
1159 usleep(ms*1000);
1160 return ms;
1161#else
1162 sleep((ms+999)/1000);
1163 return 1000*((ms+999)/1000);
1164#endif
1165}
1166
1167/*
1168** Static variables used for thread synchronization
1169*/
1170static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001171#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001172static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001173#endif
drhbbd42a62004-05-22 17:41:58 +00001174
1175/*
1176** The following pair of routine implement mutual exclusion for
1177** multi-threaded processes. Only a single thread is allowed to
1178** executed code that is surrounded by EnterMutex() and LeaveMutex().
1179**
1180** SQLite uses only a single Mutex. There is not much critical
1181** code and what little there is executes quickly and without blocking.
1182*/
1183void sqlite3OsEnterMutex(){
1184#ifdef SQLITE_UNIX_THREADS
1185 pthread_mutex_lock(&mutex);
1186#endif
1187 assert( !inMutex );
1188 inMutex = 1;
1189}
1190void sqlite3OsLeaveMutex(){
1191 assert( inMutex );
1192 inMutex = 0;
1193#ifdef SQLITE_UNIX_THREADS
1194 pthread_mutex_unlock(&mutex);
1195#endif
1196}
1197
1198/*
1199** Turn a relative pathname into a full pathname. Return a pointer
1200** to the full pathname stored in space obtained from sqliteMalloc().
1201** The calling function is responsible for freeing this space once it
1202** is no longer needed.
1203*/
1204char *sqlite3OsFullPathname(const char *zRelative){
1205 char *zFull = 0;
1206 if( zRelative[0]=='/' ){
1207 sqlite3SetString(&zFull, zRelative, (char*)0);
1208 }else{
1209 char zBuf[5000];
1210 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1211 (char*)0);
1212 }
1213 return zFull;
1214}
1215
1216/*
1217** The following variable, if set to a non-zero value, becomes the result
1218** returned from sqlite3OsCurrentTime(). This is used for testing.
1219*/
1220#ifdef SQLITE_TEST
1221int sqlite3_current_time = 0;
1222#endif
1223
1224/*
1225** Find the current time (in Universal Coordinated Time). Write the
1226** current time and date as a Julian Day number into *prNow and
1227** return 0. Return 1 if the time and date cannot be found.
1228*/
1229int sqlite3OsCurrentTime(double *prNow){
1230 time_t t;
1231 time(&t);
1232 *prNow = t/86400.0 + 2440587.5;
1233#ifdef SQLITE_TEST
1234 if( sqlite3_current_time ){
1235 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1236 }
1237#endif
1238 return 0;
1239}
1240
drhfd69dd62004-06-29 11:08:19 +00001241#if 0 /* NOT USED */
drhbf9a7e42004-06-15 00:29:03 +00001242/*
1243** Find the time that the file was last modified. Write the
1244** modification time and date as a Julian Day number into *prNow and
1245** return SQLITE_OK. Return SQLITE_ERROR if the modification
1246** time cannot be found.
1247*/
1248int sqlite3OsFileModTime(OsFile *id, double *prNow){
1249 int rc;
1250 struct stat statbuf;
1251 if( fstat(id->h, &statbuf)==0 ){
1252 *prNow = statbuf.st_mtime/86400.0 + 2440587.5;
1253 rc = SQLITE_OK;
1254 }else{
1255 rc = SQLITE_ERROR;
1256 }
1257 return rc;
1258}
drhfd69dd62004-06-29 11:08:19 +00001259#endif /* NOT USED */
drhbf9a7e42004-06-15 00:29:03 +00001260
drhbbd42a62004-05-22 17:41:58 +00001261#endif /* OS_UNIX */