blob: 3ba8b5b3170d38fb68efc7a35dacd0506d5d6c3c [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
64
65/*
66** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
67** section 6.5.2.2 lines 483 through 490 specify that when a process
68** sets or clears a lock, that operation overrides any prior locks set
69** by the same process. It does not explicitly say so, but this implies
70** that it overrides locks set by the same process using a different
71** file descriptor. Consider this test case:
72**
73** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
74** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
75**
76** Suppose ./file1 and ./file2 are really the same file (because
77** one is a hard or symbolic link to the other) then if you set
78** an exclusive lock on fd1, then try to get an exclusive lock
79** on fd2, it works. I would have expected the second lock to
80** fail since there was already a lock on the file due to fd1.
81** But not so. Since both locks came from the same process, the
82** second overrides the first, even though they were on different
83** file descriptors opened on different file names.
84**
85** Bummer. If you ask me, this is broken. Badly broken. It means
86** that we cannot use POSIX locks to synchronize file access among
87** competing threads of the same process. POSIX locks will work fine
88** to synchronize access for threads in separate processes, but not
89** threads within the same process.
90**
91** To work around the problem, SQLite has to manage file locks internally
92** on its own. Whenever a new database is opened, we have to find the
93** specific inode of the database file (the inode is determined by the
94** st_dev and st_ino fields of the stat structure that fstat() fills in)
95** and check for locks already existing on that inode. When locks are
96** created or removed, we have to look at our own internal record of the
97** locks to see if another thread has previously set a lock on that same
98** inode.
99**
100** The OsFile structure for POSIX is no longer just an integer file
101** descriptor. It is now a structure that holds the integer file
102** descriptor and a pointer to a structure that describes the internal
103** locks on the corresponding inode. There is one locking structure
104** per inode, so if the same inode is opened twice, both OsFile structures
105** point to the same locking structure. The locking structure keeps
106** a reference count (so we will know when to delete it) and a "cnt"
107** field that tells us its internal lock status. cnt==0 means the
108** file is unlocked. cnt==-1 means the file has an exclusive lock.
109** cnt>0 means there are cnt shared locks on the file.
110**
111** Any attempt to lock or unlock a file first checks the locking
112** structure. The fcntl() system call is only invoked to set a
113** POSIX lock if the internal lock structure transitions between
114** a locked and an unlocked state.
115**
116** 2004-Jan-11:
117** More recent discoveries about POSIX advisory locks. (The more
118** I discover, the more I realize the a POSIX advisory locks are
119** an abomination.)
120**
121** If you close a file descriptor that points to a file that has locks,
122** all locks on that file that are owned by the current process are
123** released. To work around this problem, each OsFile structure contains
124** a pointer to an openCnt structure. There is one openCnt structure
125** per open inode, which means that multiple OsFiles can point to a single
126** openCnt. When an attempt is made to close an OsFile, if there are
127** other OsFiles open on the same inode that are holding locks, the call
128** to close() the file descriptor is deferred until all of the locks clear.
129** The openCnt structure keeps a list of file descriptors that need to
130** be closed and that list is walked (and cleared) when the last lock
131** clears.
132**
133** First, under Linux threads, because each thread has a separate
134** process ID, lock operations in one thread do not override locks
135** to the same file in other threads. Linux threads behave like
136** separate processes in this respect. But, if you close a file
137** descriptor in linux threads, all locks are cleared, even locks
138** on other threads and even though the other threads have different
139** process IDs. Linux threads is inconsistent in this respect.
140** (I'm beginning to think that linux threads is an abomination too.)
141** The consequence of this all is that the hash table for the lockInfo
142** structure has to include the process id as part of its key because
143** locks in different threads are treated as distinct. But the
144** openCnt structure should not include the process id in its
145** key because close() clears lock on all threads, not just the current
146** thread. Were it not for this goofiness in linux threads, we could
147** combine the lockInfo and openCnt structures into a single structure.
148*/
149
150/*
151** An instance of the following structure serves as the key used
152** to locate a particular lockInfo structure given its inode. Note
153** that we have to include the process ID as part of the key. On some
154** threading implementations (ex: linux), each thread has a separate
155** process ID.
156*/
157struct lockKey {
158 dev_t dev; /* Device number */
159 ino_t ino; /* Inode number */
160 pid_t pid; /* Process ID */
161};
162
163/*
164** An instance of the following structure is allocated for each open
165** inode on each thread with a different process ID. (Threads have
166** different process IDs on linux, but not on most other unixes.)
167**
168** A single inode can have multiple file descriptors, so each OsFile
169** structure contains a pointer to an instance of this object and this
170** object keeps a count of the number of OsFiles pointing to it.
171*/
172struct lockInfo {
173 struct lockKey key; /* The lookup key */
174 int cnt; /* 0: unlocked. -1: write lock. 1...: read lock. */
danielk19779a1d0ab2004-06-01 14:09:28 +0000175 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000176 int nRef; /* Number of pointers to this structure */
177};
178
179/*
180** An instance of the following structure serves as the key used
181** to locate a particular openCnt structure given its inode. This
182** is the same as the lockKey except that the process ID is omitted.
183*/
184struct openKey {
185 dev_t dev; /* Device number */
186 ino_t ino; /* Inode number */
187};
188
189/*
190** An instance of the following structure is allocated for each open
191** inode. This structure keeps track of the number of locks on that
192** inode. If a close is attempted against an inode that is holding
193** locks, the close is deferred until all locks clear by adding the
194** file descriptor to be closed to the pending list.
195*/
196struct openCnt {
197 struct openKey key; /* The lookup key */
198 int nRef; /* Number of pointers to this structure */
199 int nLock; /* Number of outstanding locks */
200 int nPending; /* Number of pending close() operations */
201 int *aPending; /* Malloced space holding fd's awaiting a close() */
202};
203
204/*
205** These hash table maps inodes and process IDs into lockInfo and openCnt
206** structures. Access to these hash tables must be protected by a mutex.
207*/
208static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
209static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
210
211/*
212** Release a lockInfo structure previously allocated by findLockInfo().
213*/
214static void releaseLockInfo(struct lockInfo *pLock){
215 pLock->nRef--;
216 if( pLock->nRef==0 ){
217 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
218 sqliteFree(pLock);
219 }
220}
221
222/*
223** Release a openCnt structure previously allocated by findLockInfo().
224*/
225static void releaseOpenCnt(struct openCnt *pOpen){
226 pOpen->nRef--;
227 if( pOpen->nRef==0 ){
228 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
229 sqliteFree(pOpen->aPending);
230 sqliteFree(pOpen);
231 }
232}
233
234/*
235** Given a file descriptor, locate lockInfo and openCnt structures that
236** describes that file descriptor. Create a new ones if necessary. The
237** return values might be unset if an error occurs.
238**
239** Return the number of errors.
240*/
241int findLockInfo(
242 int fd, /* The file descriptor used in the key */
243 struct lockInfo **ppLock, /* Return the lockInfo structure here */
244 struct openCnt **ppOpen /* Return the openCnt structure here */
245){
246 int rc;
247 struct lockKey key1;
248 struct openKey key2;
249 struct stat statbuf;
250 struct lockInfo *pLock;
251 struct openCnt *pOpen;
252 rc = fstat(fd, &statbuf);
253 if( rc!=0 ) return 1;
254 memset(&key1, 0, sizeof(key1));
255 key1.dev = statbuf.st_dev;
256 key1.ino = statbuf.st_ino;
257 key1.pid = getpid();
258 memset(&key2, 0, sizeof(key2));
259 key2.dev = statbuf.st_dev;
260 key2.ino = statbuf.st_ino;
261 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
262 if( pLock==0 ){
263 struct lockInfo *pOld;
264 pLock = sqliteMallocRaw( sizeof(*pLock) );
265 if( pLock==0 ) return 1;
266 pLock->key = key1;
267 pLock->nRef = 1;
268 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000269 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000270 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
271 if( pOld!=0 ){
272 assert( pOld==pLock );
273 sqliteFree(pLock);
274 return 1;
275 }
276 }else{
277 pLock->nRef++;
278 }
279 *ppLock = pLock;
280 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
281 if( pOpen==0 ){
282 struct openCnt *pOld;
283 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
284 if( pOpen==0 ){
285 releaseLockInfo(pLock);
286 return 1;
287 }
288 pOpen->key = key2;
289 pOpen->nRef = 1;
290 pOpen->nLock = 0;
291 pOpen->nPending = 0;
292 pOpen->aPending = 0;
293 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
294 if( pOld!=0 ){
295 assert( pOld==pOpen );
296 sqliteFree(pOpen);
297 releaseLockInfo(pLock);
298 return 1;
299 }
300 }else{
301 pOpen->nRef++;
302 }
303 *ppOpen = pOpen;
304 return 0;
305}
306
307/*
308** Delete the named file
309*/
310int sqlite3OsDelete(const char *zFilename){
311 unlink(zFilename);
312 return SQLITE_OK;
313}
314
315/*
316** Return TRUE if the named file exists.
317*/
318int sqlite3OsFileExists(const char *zFilename){
319 return access(zFilename, 0)==0;
320}
321
322/*
323** Attempt to open a file for both reading and writing. If that
324** fails, try opening it read-only. If the file does not exist,
325** try to create it.
326**
327** On success, a handle for the open file is written to *id
328** and *pReadonly is set to 0 if the file was opened for reading and
329** writing or 1 if the file was opened read-only. The function returns
330** SQLITE_OK.
331**
332** On failure, the function returns SQLITE_CANTOPEN and leaves
333** *id and *pReadonly unchanged.
334*/
335int sqlite3OsOpenReadWrite(
336 const char *zFilename,
337 OsFile *id,
338 int *pReadonly
339){
340 int rc;
341 id->dirfd = -1;
342 id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
343 if( id->fd<0 ){
344 id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
345 if( id->fd<0 ){
346 return SQLITE_CANTOPEN;
347 }
348 *pReadonly = 1;
349 }else{
350 *pReadonly = 0;
351 }
352 sqlite3OsEnterMutex();
353 rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
354 sqlite3OsLeaveMutex();
355 if( rc ){
356 close(id->fd);
357 return SQLITE_NOMEM;
358 }
359 id->locked = 0;
360 TRACE3("OPEN %-3d %s\n", id->fd, zFilename);
361 OpenCounter(+1);
362 return SQLITE_OK;
363}
364
365
366/*
367** Attempt to open a new file for exclusive access by this process.
368** The file will be opened for both reading and writing. To avoid
369** a potential security problem, we do not allow the file to have
370** previously existed. Nor do we allow the file to be a symbolic
371** link.
372**
373** If delFlag is true, then make arrangements to automatically delete
374** the file when it is closed.
375**
376** On success, write the file handle into *id and return SQLITE_OK.
377**
378** On failure, return SQLITE_CANTOPEN.
379*/
380int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
381 int rc;
382 if( access(zFilename, 0)==0 ){
383 return SQLITE_CANTOPEN;
384 }
385 id->dirfd = -1;
386 id->fd = open(zFilename,
387 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
388 if( id->fd<0 ){
389 return SQLITE_CANTOPEN;
390 }
391 sqlite3OsEnterMutex();
392 rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
393 sqlite3OsLeaveMutex();
394 if( rc ){
395 close(id->fd);
396 unlink(zFilename);
397 return SQLITE_NOMEM;
398 }
399 id->locked = 0;
400 if( delFlag ){
401 unlink(zFilename);
402 }
403 TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename);
404 OpenCounter(+1);
405 return SQLITE_OK;
406}
407
408/*
409** Attempt to open a new file for read-only access.
410**
411** On success, write the file handle into *id and return SQLITE_OK.
412**
413** On failure, return SQLITE_CANTOPEN.
414*/
415int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
416 int rc;
417 id->dirfd = -1;
418 id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
419 if( id->fd<0 ){
420 return SQLITE_CANTOPEN;
421 }
422 sqlite3OsEnterMutex();
423 rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
424 sqlite3OsLeaveMutex();
425 if( rc ){
426 close(id->fd);
427 return SQLITE_NOMEM;
428 }
429 id->locked = 0;
430 TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename);
431 OpenCounter(+1);
432 return SQLITE_OK;
433}
434
435/*
436** Attempt to open a file descriptor for the directory that contains a
437** file. This file descriptor can be used to fsync() the directory
438** in order to make sure the creation of a new file is actually written
439** to disk.
440**
441** This routine is only meaningful for Unix. It is a no-op under
442** windows since windows does not support hard links.
443**
444** On success, a handle for a previously open file is at *id is
445** updated with the new directory file descriptor and SQLITE_OK is
446** returned.
447**
448** On failure, the function returns SQLITE_CANTOPEN and leaves
449** *id unchanged.
450*/
451int sqlite3OsOpenDirectory(
452 const char *zDirname,
453 OsFile *id
454){
455 if( id->fd<0 ){
456 /* Do not open the directory if the corresponding file is not already
457 ** open. */
458 return SQLITE_CANTOPEN;
459 }
460 assert( id->dirfd<0 );
461 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
462 if( id->dirfd<0 ){
463 return SQLITE_CANTOPEN;
464 }
465 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
466 return SQLITE_OK;
467}
468
469/*
470** Create a temporary file name in zBuf. zBuf must be big enough to
471** hold at least SQLITE_TEMPNAME_SIZE characters.
472*/
473int sqlite3OsTempFileName(char *zBuf){
474 static const char *azDirs[] = {
475 "/var/tmp",
476 "/usr/tmp",
477 "/tmp",
478 ".",
479 };
480 static unsigned char zChars[] =
481 "abcdefghijklmnopqrstuvwxyz"
482 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
483 "0123456789";
484 int i, j;
485 struct stat buf;
486 const char *zDir = ".";
487 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
488 if( stat(azDirs[i], &buf) ) continue;
489 if( !S_ISDIR(buf.st_mode) ) continue;
490 if( access(azDirs[i], 07) ) continue;
491 zDir = azDirs[i];
492 break;
493 }
494 do{
495 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
496 j = strlen(zBuf);
497 sqlite3Randomness(15, &zBuf[j]);
498 for(i=0; i<15; i++, j++){
499 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
500 }
501 zBuf[j] = 0;
502 }while( access(zBuf,0)==0 );
503 return SQLITE_OK;
504}
505
506/*
507** Close a file.
508*/
509int sqlite3OsClose(OsFile *id){
510 sqlite3OsUnlock(id);
511 if( id->dirfd>=0 ) close(id->dirfd);
512 id->dirfd = -1;
513 sqlite3OsEnterMutex();
514 if( id->pOpen->nLock ){
515 /* If there are outstanding locks, do not actually close the file just
516 ** yet because that would clear those locks. Instead, add the file
517 ** descriptor to pOpen->aPending. It will be automatically closed when
518 ** the last lock is cleared.
519 */
520 int *aNew;
521 struct openCnt *pOpen = id->pOpen;
522 pOpen->nPending++;
523 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
524 if( aNew==0 ){
525 /* If a malloc fails, just leak the file descriptor */
526 }else{
527 pOpen->aPending = aNew;
528 pOpen->aPending[pOpen->nPending-1] = id->fd;
529 }
530 }else{
531 /* There are no outstanding locks so we can close the file immediately */
532 close(id->fd);
533 }
534 releaseLockInfo(id->pLock);
535 releaseOpenCnt(id->pOpen);
536 sqlite3OsLeaveMutex();
537 TRACE2("CLOSE %-3d\n", id->fd);
538 OpenCounter(-1);
539 return SQLITE_OK;
540}
541
542/*
543** Read data from a file into a buffer. Return SQLITE_OK if all
544** bytes were read successfully and SQLITE_IOERR if anything goes
545** wrong.
546*/
547int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
548 int got;
549 SimulateIOError(SQLITE_IOERR);
550 TIMER_START;
551 got = read(id->fd, pBuf, amt);
552 TIMER_END;
553 TRACE4("READ %-3d %7d %d\n", id->fd, last_page, elapse);
554 SEEK(0);
555 /* if( got<0 ) got = 0; */
556 if( got==amt ){
557 return SQLITE_OK;
558 }else{
559 return SQLITE_IOERR;
560 }
561}
562
563/*
564** Write data from a buffer into a file. Return SQLITE_OK on success
565** or some other error code on failure.
566*/
567int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
568 int wrote = 0;
569 SimulateIOError(SQLITE_IOERR);
570 TIMER_START;
571 while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){
572 amt -= wrote;
573 pBuf = &((char*)pBuf)[wrote];
574 }
575 TIMER_END;
576 TRACE4("WRITE %-3d %7d %d\n", id->fd, last_page, elapse);
577 SEEK(0);
578 if( amt>0 ){
579 return SQLITE_FULL;
580 }
581 return SQLITE_OK;
582}
583
584/*
585** Move the read/write pointer in a file.
586*/
587int sqlite3OsSeek(OsFile *id, off_t offset){
588 SEEK(offset/1024 + 1);
589 lseek(id->fd, offset, SEEK_SET);
590 return SQLITE_OK;
591}
592
593/*
594** Make sure all writes to a particular file are committed to disk.
595**
596** Under Unix, also make sure that the directory entry for the file
597** has been created by fsync-ing the directory that contains the file.
598** If we do not do this and we encounter a power failure, the directory
599** entry for the journal might not exist after we reboot. The next
600** SQLite to access the file will not know that the journal exists (because
601** the directory entry for the journal was never created) and the transaction
602** will not roll back - possibly leading to database corruption.
603*/
604int sqlite3OsSync(OsFile *id){
605 SimulateIOError(SQLITE_IOERR);
606 TRACE2("SYNC %-3d\n", id->fd);
607 if( fsync(id->fd) ){
608 return SQLITE_IOERR;
609 }else{
610 if( id->dirfd>=0 ){
611 TRACE2("DIRSYNC %-3d\n", id->dirfd);
612 fsync(id->dirfd);
613 close(id->dirfd); /* Only need to sync once, so close the directory */
614 id->dirfd = -1; /* when we are done. */
615 }
616 return SQLITE_OK;
617 }
618}
619
620/*
621** Truncate an open file to a specified size
622*/
623int sqlite3OsTruncate(OsFile *id, off_t nByte){
624 SimulateIOError(SQLITE_IOERR);
625 return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
626}
627
628/*
629** Determine the current size of a file in bytes
630*/
631int sqlite3OsFileSize(OsFile *id, off_t *pSize){
632 struct stat buf;
633 SimulateIOError(SQLITE_IOERR);
634 if( fstat(id->fd, &buf)!=0 ){
635 return SQLITE_IOERR;
636 }
637 *pSize = buf.st_size;
638 return SQLITE_OK;
639}
640
641
642/*
643** Change the status of the lock on the file "id" to be a readlock.
644** If the file was write locked, then this reduces the lock to a read.
645** If the file was read locked, then this acquires a new read lock.
646**
647** Return SQLITE_OK on success and SQLITE_BUSY on failure. If this
648** library was compiled with large file support (LFS) but LFS is not
649** available on the host, then an SQLITE_NOLFS is returned.
650*/
651int sqlite3OsReadLock(OsFile *id){
652 int rc;
danielk19779a1d0ab2004-06-01 14:09:28 +0000653 return sqlite3OsLock(id, SHARED_LOCK);
drhbbd42a62004-05-22 17:41:58 +0000654}
655
656/*
657** Change the lock status to be an exclusive or write lock. Return
658** SQLITE_OK on success and SQLITE_BUSY on a failure. If this
659** library was compiled with large file support (LFS) but LFS is not
660** available on the host, then an SQLITE_NOLFS is returned.
661*/
662int sqlite3OsWriteLock(OsFile *id){
663 int rc;
danielk19779a1d0ab2004-06-01 14:09:28 +0000664 return sqlite3OsLock(id, EXCLUSIVE_LOCK);
665}
666
667/*
668** Lock the file with the lock specified by parameter locktype - one
669** of the following:
670**
671** SHARED_LOCK
672** RESERVED_LOCK
673** PENDING_LOCK
674** EXCLUSIVE_LOCK
675*/
676int sqlite3OsLock(OsFile *id, int locktype){
677 int rc = SQLITE_OK;
678 struct lockInfo *pLock = id->pLock;
679 struct flock lock;
680 int s;
681
682 /* It is an error to request any kind of lock before a shared lock */
683 if( locktype>SHARED_LOCK && id->locked==0 ){
684 rc = sqlite3OsLock(id, SHARED_LOCK);
685 if( rc!=SQLITE_OK ) return rc;
686 }
687 assert( locktype==SHARED_LOCK || id->locked!=0 );
688
689 /* If there is already a lock of this type or more restrictive on the
690 ** OsFile, do nothing. Don't use the end_lock: exit path, as
691 ** sqlite3OsEnterMutex() hasn't been called yet.
692 */
693 if( id->locked>=locktype ){
694 return SQLITE_OK;
695 }
696
drhbbd42a62004-05-22 17:41:58 +0000697 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +0000698
699 /* If some thread using this PID has a lock via a different OsFile*
700 ** handle that precludes the requested lock, return BUSY.
701 */
702 if( (id->locked!=pLock->locktype &&
703 (pLock->locktype>RESERVED_LOCK || locktype!=SHARED_LOCK)) ||
704 (locktype>RESERVED_LOCK && pLock->cnt>1)
705 ){
706 rc = SQLITE_BUSY;
707 goto end_lock;
708 }
709
710 /* If a SHARED lock is requested, and some thread using this PID already
711 ** has a SHARED or RESERVED lock, then increment reference counts and
712 ** return SQLITE_OK.
713 */
714 if( locktype==SHARED_LOCK &&
715 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
716 assert( locktype==SHARED_LOCK );
717 assert( id->locked==0 );
718 id->locked = SHARED_LOCK;
719 pLock->cnt++;
720 id->pOpen->nLock++;
721 goto end_lock;
722 }
723
724 lock.l_len = 1L;
725 lock.l_whence = SEEK_SET;
726
727 /* If control gets to this point, then actually go ahead and make
728 ** operating system calls for the specified lock.
729 */
730 if( locktype==SHARED_LOCK ){
731 assert( pLock->cnt==0 );
732 assert( id->pOpen->nLock==0 );
733 assert( pLock->locktype==0 );
734
735 /* Grab a read-lock on byte 2. This ensures that no other process
736 ** has a PENDING lock.
737 */
738 lock.l_type = F_RDLCK;
739 lock.l_start = 2;
drhbbd42a62004-05-22 17:41:58 +0000740 s = fcntl(id->fd, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000741 if( s ){
742 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
743 goto end_lock;
744 }
745
746 /* Now get a read-lock on byte 0 and renege on the byte 2 lock. */
747 lock.l_start = 0;
748 s = fcntl(id->fd, F_SETLK, &lock);
749 lock.l_start = 2;
750 lock.l_type = F_UNLCK;
751 fcntl(id->fd, F_SETLK, &lock);
752 if( s ){
drhbbd42a62004-05-22 17:41:58 +0000753 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
754 }else{
danielk19779a1d0ab2004-06-01 14:09:28 +0000755 id->locked = SHARED_LOCK;
756 id->pOpen->nLock = 1;
757 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +0000758 }
759 }else{
danielk19779a1d0ab2004-06-01 14:09:28 +0000760 /* The request was for a RESERVED, PENDING or EXCLUSIVE lock. It is
761 ** assumed that there is a SHARED or greater lock on the file
762 ** already.
763 */
764 assert( 0!=id->locked );
765 lock.l_type = F_WRLCK;
766 switch( locktype ){
767 case RESERVED_LOCK:
768 lock.l_start = 1;
769 break;
770 case PENDING_LOCK:
771 lock.l_start = 2;
772 break;
773 case EXCLUSIVE_LOCK:
774 lock.l_start = 0;
775 break;
776 default:
777 assert(0);
778 }
779 s = fcntl(id->fd, F_SETLK, &lock);
780 if( s ){
781 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
782 }
drhbbd42a62004-05-22 17:41:58 +0000783 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000784
785 id->locked = locktype;
786 pLock->locktype = locktype;
787 assert(pLock->locktype==RESERVED_LOCK||(id->pOpen->nLock==1&&pLock->cnt==1));
788
789end_lock:
drhbbd42a62004-05-22 17:41:58 +0000790 sqlite3OsLeaveMutex();
791 return rc;
792}
793
794/*
795** Unlock the given file descriptor. If the file descriptor was
796** not previously locked, then this routine is a no-op. If this
797** library was compiled with large file support (LFS) but LFS is not
798** available on the host, then an SQLITE_NOLFS is returned.
799*/
800int sqlite3OsUnlock(OsFile *id){
801 int rc;
802 if( !id->locked ) return SQLITE_OK;
803 sqlite3OsEnterMutex();
804 assert( id->pLock->cnt!=0 );
805 if( id->pLock->cnt>1 ){
danielk19779a1d0ab2004-06-01 14:09:28 +0000806 id->locked = 0;
drhbbd42a62004-05-22 17:41:58 +0000807 id->pLock->cnt--;
808 rc = SQLITE_OK;
809 }else{
810 struct flock lock;
811 int s;
812 lock.l_type = F_UNLCK;
813 lock.l_whence = SEEK_SET;
814 lock.l_start = lock.l_len = 0L;
815 s = fcntl(id->fd, F_SETLK, &lock);
816 if( s!=0 ){
817 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
818 }else{
819 rc = SQLITE_OK;
820 id->pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000821 id->pLock->locktype = 0;
822 id->locked = 0;
drhbbd42a62004-05-22 17:41:58 +0000823 }
824 }
825 if( rc==SQLITE_OK ){
826 /* Decrement the count of locks against this same file. When the
827 ** count reaches zero, close any other file descriptors whose close
828 ** was deferred because of outstanding locks.
829 */
830 struct openCnt *pOpen = id->pOpen;
831 pOpen->nLock--;
832 assert( pOpen->nLock>=0 );
833 if( pOpen->nLock==0 && pOpen->nPending>0 ){
834 int i;
835 for(i=0; i<pOpen->nPending; i++){
836 close(pOpen->aPending[i]);
837 }
838 sqliteFree(pOpen->aPending);
839 pOpen->nPending = 0;
840 pOpen->aPending = 0;
841 }
842 }
843 sqlite3OsLeaveMutex();
844 id->locked = 0;
845 return rc;
846}
847
848/*
849** Get information to seed the random number generator. The seed
850** is written into the buffer zBuf[256]. The calling function must
851** supply a sufficiently large buffer.
852*/
853int sqlite3OsRandomSeed(char *zBuf){
854 /* We have to initialize zBuf to prevent valgrind from reporting
855 ** errors. The reports issued by valgrind are incorrect - we would
856 ** prefer that the randomness be increased by making use of the
857 ** uninitialized space in zBuf - but valgrind errors tend to worry
858 ** some users. Rather than argue, it seems easier just to initialize
859 ** the whole array and silence valgrind, even if that means less randomness
860 ** in the random seed.
861 **
862 ** When testing, initializing zBuf[] to zero is all we do. That means
863 ** that we always use the same random number sequence.* This makes the
864 ** tests repeatable.
865 */
866 memset(zBuf, 0, 256);
867#if !defined(SQLITE_TEST)
868 {
869 int pid;
870 time((time_t*)zBuf);
871 pid = getpid();
872 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
873 }
874#endif
875 return SQLITE_OK;
876}
877
878/*
879** Sleep for a little while. Return the amount of time slept.
880*/
881int sqlite3OsSleep(int ms){
882#if defined(HAVE_USLEEP) && HAVE_USLEEP
883 usleep(ms*1000);
884 return ms;
885#else
886 sleep((ms+999)/1000);
887 return 1000*((ms+999)/1000);
888#endif
889}
890
891/*
892** Static variables used for thread synchronization
893*/
894static int inMutex = 0;
drh79069752004-05-22 21:30:40 +0000895#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +0000896static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +0000897#endif
drhbbd42a62004-05-22 17:41:58 +0000898
899/*
900** The following pair of routine implement mutual exclusion for
901** multi-threaded processes. Only a single thread is allowed to
902** executed code that is surrounded by EnterMutex() and LeaveMutex().
903**
904** SQLite uses only a single Mutex. There is not much critical
905** code and what little there is executes quickly and without blocking.
906*/
907void sqlite3OsEnterMutex(){
908#ifdef SQLITE_UNIX_THREADS
909 pthread_mutex_lock(&mutex);
910#endif
911 assert( !inMutex );
912 inMutex = 1;
913}
914void sqlite3OsLeaveMutex(){
915 assert( inMutex );
916 inMutex = 0;
917#ifdef SQLITE_UNIX_THREADS
918 pthread_mutex_unlock(&mutex);
919#endif
920}
921
922/*
923** Turn a relative pathname into a full pathname. Return a pointer
924** to the full pathname stored in space obtained from sqliteMalloc().
925** The calling function is responsible for freeing this space once it
926** is no longer needed.
927*/
928char *sqlite3OsFullPathname(const char *zRelative){
929 char *zFull = 0;
930 if( zRelative[0]=='/' ){
931 sqlite3SetString(&zFull, zRelative, (char*)0);
932 }else{
933 char zBuf[5000];
934 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
935 (char*)0);
936 }
937 return zFull;
938}
939
940/*
941** The following variable, if set to a non-zero value, becomes the result
942** returned from sqlite3OsCurrentTime(). This is used for testing.
943*/
944#ifdef SQLITE_TEST
945int sqlite3_current_time = 0;
946#endif
947
948/*
949** Find the current time (in Universal Coordinated Time). Write the
950** current time and date as a Julian Day number into *prNow and
951** return 0. Return 1 if the time and date cannot be found.
952*/
953int sqlite3OsCurrentTime(double *prNow){
954 time_t t;
955 time(&t);
956 *prNow = t/86400.0 + 2440587.5;
957#ifdef SQLITE_TEST
958 if( sqlite3_current_time ){
959 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
960 }
961#endif
962 return 0;
963}
964
965#endif /* OS_UNIX */