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