blob: 110dca38da39ac0fe3d6fb23a9b72fa76282b4db [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
danielk197713adf8a2004-06-03 16:08:41 +000064#if defined(THREADSAFE) && defined(__linux__)
65#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.
151*/
152
153/*
154** An instance of the following structure serves as the key used
155** to locate a particular lockInfo structure given its inode. Note
156** that we have to include the process ID as part of the key. On some
157** threading implementations (ex: linux), each thread has a separate
158** process ID.
159*/
160struct lockKey {
161 dev_t dev; /* Device number */
162 ino_t ino; /* Inode number */
163 pid_t pid; /* Process ID */
164};
165
166/*
167** An instance of the following structure is allocated for each open
168** inode on each thread with a different process ID. (Threads have
169** different process IDs on linux, but not on most other unixes.)
170**
171** A single inode can have multiple file descriptors, so each OsFile
172** structure contains a pointer to an instance of this object and this
173** object keeps a count of the number of OsFiles pointing to it.
174*/
175struct lockInfo {
176 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000177 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000178 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000179 int nRef; /* Number of pointers to this structure */
180};
181
182/*
183** An instance of the following structure serves as the key used
184** to locate a particular openCnt structure given its inode. This
185** is the same as the lockKey except that the process ID is omitted.
186*/
187struct openKey {
188 dev_t dev; /* Device number */
189 ino_t ino; /* Inode number */
190};
191
192/*
193** An instance of the following structure is allocated for each open
194** inode. This structure keeps track of the number of locks on that
195** inode. If a close is attempted against an inode that is holding
196** locks, the close is deferred until all locks clear by adding the
197** file descriptor to be closed to the pending list.
198*/
199struct openCnt {
200 struct openKey key; /* The lookup key */
201 int nRef; /* Number of pointers to this structure */
202 int nLock; /* Number of outstanding locks */
203 int nPending; /* Number of pending close() operations */
204 int *aPending; /* Malloced space holding fd's awaiting a close() */
205};
206
207/*
208** These hash table maps inodes and process IDs into lockInfo and openCnt
209** structures. Access to these hash tables must be protected by a mutex.
210*/
211static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
212static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
213
214/*
215** Release a lockInfo structure previously allocated by findLockInfo().
216*/
217static void releaseLockInfo(struct lockInfo *pLock){
218 pLock->nRef--;
219 if( pLock->nRef==0 ){
220 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
221 sqliteFree(pLock);
222 }
223}
224
225/*
226** Release a openCnt structure previously allocated by findLockInfo().
227*/
228static void releaseOpenCnt(struct openCnt *pOpen){
229 pOpen->nRef--;
230 if( pOpen->nRef==0 ){
231 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
232 sqliteFree(pOpen->aPending);
233 sqliteFree(pOpen);
234 }
235}
236
237/*
238** Given a file descriptor, locate lockInfo and openCnt structures that
239** describes that file descriptor. Create a new ones if necessary. The
240** return values might be unset if an error occurs.
241**
242** Return the number of errors.
243*/
244int findLockInfo(
245 int fd, /* The file descriptor used in the key */
246 struct lockInfo **ppLock, /* Return the lockInfo structure here */
247 struct openCnt **ppOpen /* Return the openCnt structure here */
248){
249 int rc;
250 struct lockKey key1;
251 struct openKey key2;
252 struct stat statbuf;
253 struct lockInfo *pLock;
254 struct openCnt *pOpen;
255 rc = fstat(fd, &statbuf);
256 if( rc!=0 ) return 1;
257 memset(&key1, 0, sizeof(key1));
258 key1.dev = statbuf.st_dev;
259 key1.ino = statbuf.st_ino;
260 key1.pid = getpid();
261 memset(&key2, 0, sizeof(key2));
262 key2.dev = statbuf.st_dev;
263 key2.ino = statbuf.st_ino;
264 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
265 if( pLock==0 ){
266 struct lockInfo *pOld;
267 pLock = sqliteMallocRaw( sizeof(*pLock) );
268 if( pLock==0 ) return 1;
269 pLock->key = key1;
270 pLock->nRef = 1;
271 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000272 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000273 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
274 if( pOld!=0 ){
275 assert( pOld==pLock );
276 sqliteFree(pLock);
277 return 1;
278 }
279 }else{
280 pLock->nRef++;
281 }
282 *ppLock = pLock;
283 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
284 if( pOpen==0 ){
285 struct openCnt *pOld;
286 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
287 if( pOpen==0 ){
288 releaseLockInfo(pLock);
289 return 1;
290 }
291 pOpen->key = key2;
292 pOpen->nRef = 1;
293 pOpen->nLock = 0;
294 pOpen->nPending = 0;
295 pOpen->aPending = 0;
296 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
297 if( pOld!=0 ){
298 assert( pOld==pOpen );
299 sqliteFree(pOpen);
300 releaseLockInfo(pLock);
301 return 1;
302 }
303 }else{
304 pOpen->nRef++;
305 }
306 *ppOpen = pOpen;
307 return 0;
308}
309
310/*
311** Delete the named file
312*/
313int sqlite3OsDelete(const char *zFilename){
314 unlink(zFilename);
315 return SQLITE_OK;
316}
317
318/*
319** Return TRUE if the named file exists.
320*/
321int sqlite3OsFileExists(const char *zFilename){
322 return access(zFilename, 0)==0;
323}
324
325/*
326** Attempt to open a file for both reading and writing. If that
327** fails, try opening it read-only. If the file does not exist,
328** try to create it.
329**
330** On success, a handle for the open file is written to *id
331** and *pReadonly is set to 0 if the file was opened for reading and
332** writing or 1 if the file was opened read-only. The function returns
333** SQLITE_OK.
334**
335** On failure, the function returns SQLITE_CANTOPEN and leaves
336** *id and *pReadonly unchanged.
337*/
338int sqlite3OsOpenReadWrite(
339 const char *zFilename,
340 OsFile *id,
341 int *pReadonly
342){
343 int rc;
344 id->dirfd = -1;
345 id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
346 if( id->fd<0 ){
347 id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
348 if( id->fd<0 ){
349 return SQLITE_CANTOPEN;
350 }
351 *pReadonly = 1;
352 }else{
353 *pReadonly = 0;
354 }
355 sqlite3OsEnterMutex();
356 rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
357 sqlite3OsLeaveMutex();
358 if( rc ){
359 close(id->fd);
360 return SQLITE_NOMEM;
361 }
danielk197713adf8a2004-06-03 16:08:41 +0000362 id->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000363 TRACE3("OPEN %-3d %s\n", id->fd, zFilename);
364 OpenCounter(+1);
365 return SQLITE_OK;
366}
367
368
369/*
370** Attempt to open a new file for exclusive access by this process.
371** The file will be opened for both reading and writing. To avoid
372** a potential security problem, we do not allow the file to have
373** previously existed. Nor do we allow the file to be a symbolic
374** link.
375**
376** If delFlag is true, then make arrangements to automatically delete
377** the file when it is closed.
378**
379** On success, write the file handle into *id and return SQLITE_OK.
380**
381** On failure, return SQLITE_CANTOPEN.
382*/
383int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
384 int rc;
385 if( access(zFilename, 0)==0 ){
386 return SQLITE_CANTOPEN;
387 }
388 id->dirfd = -1;
389 id->fd = open(zFilename,
390 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
391 if( id->fd<0 ){
392 return SQLITE_CANTOPEN;
393 }
394 sqlite3OsEnterMutex();
395 rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
396 sqlite3OsLeaveMutex();
397 if( rc ){
398 close(id->fd);
399 unlink(zFilename);
400 return SQLITE_NOMEM;
401 }
danielk197713adf8a2004-06-03 16:08:41 +0000402 id->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000403 if( delFlag ){
404 unlink(zFilename);
405 }
406 TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename);
407 OpenCounter(+1);
408 return SQLITE_OK;
409}
410
411/*
412** Attempt to open a new file for read-only access.
413**
414** On success, write the file handle into *id and return SQLITE_OK.
415**
416** On failure, return SQLITE_CANTOPEN.
417*/
418int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
419 int rc;
420 id->dirfd = -1;
421 id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
422 if( id->fd<0 ){
423 return SQLITE_CANTOPEN;
424 }
425 sqlite3OsEnterMutex();
426 rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
427 sqlite3OsLeaveMutex();
428 if( rc ){
429 close(id->fd);
430 return SQLITE_NOMEM;
431 }
danielk197713adf8a2004-06-03 16:08:41 +0000432 id->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000433 TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename);
434 OpenCounter(+1);
435 return SQLITE_OK;
436}
437
438/*
439** Attempt to open a file descriptor for the directory that contains a
440** file. This file descriptor can be used to fsync() the directory
441** in order to make sure the creation of a new file is actually written
442** to disk.
443**
444** This routine is only meaningful for Unix. It is a no-op under
445** windows since windows does not support hard links.
446**
447** On success, a handle for a previously open file is at *id is
448** updated with the new directory file descriptor and SQLITE_OK is
449** returned.
450**
451** On failure, the function returns SQLITE_CANTOPEN and leaves
452** *id unchanged.
453*/
454int sqlite3OsOpenDirectory(
455 const char *zDirname,
456 OsFile *id
457){
458 if( id->fd<0 ){
459 /* Do not open the directory if the corresponding file is not already
460 ** open. */
461 return SQLITE_CANTOPEN;
462 }
463 assert( id->dirfd<0 );
464 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
465 if( id->dirfd<0 ){
466 return SQLITE_CANTOPEN;
467 }
468 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
469 return SQLITE_OK;
470}
471
472/*
473** Create a temporary file name in zBuf. zBuf must be big enough to
474** hold at least SQLITE_TEMPNAME_SIZE characters.
475*/
476int sqlite3OsTempFileName(char *zBuf){
477 static const char *azDirs[] = {
478 "/var/tmp",
479 "/usr/tmp",
480 "/tmp",
481 ".",
482 };
483 static unsigned char zChars[] =
484 "abcdefghijklmnopqrstuvwxyz"
485 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
486 "0123456789";
487 int i, j;
488 struct stat buf;
489 const char *zDir = ".";
490 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
491 if( stat(azDirs[i], &buf) ) continue;
492 if( !S_ISDIR(buf.st_mode) ) continue;
493 if( access(azDirs[i], 07) ) continue;
494 zDir = azDirs[i];
495 break;
496 }
497 do{
498 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
499 j = strlen(zBuf);
500 sqlite3Randomness(15, &zBuf[j]);
501 for(i=0; i<15; i++, j++){
502 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
503 }
504 zBuf[j] = 0;
505 }while( access(zBuf,0)==0 );
506 return SQLITE_OK;
507}
508
509/*
510** Close a file.
511*/
512int sqlite3OsClose(OsFile *id){
513 sqlite3OsUnlock(id);
514 if( id->dirfd>=0 ) close(id->dirfd);
515 id->dirfd = -1;
516 sqlite3OsEnterMutex();
517 if( id->pOpen->nLock ){
518 /* If there are outstanding locks, do not actually close the file just
519 ** yet because that would clear those locks. Instead, add the file
520 ** descriptor to pOpen->aPending. It will be automatically closed when
521 ** the last lock is cleared.
522 */
523 int *aNew;
524 struct openCnt *pOpen = id->pOpen;
525 pOpen->nPending++;
526 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
527 if( aNew==0 ){
528 /* If a malloc fails, just leak the file descriptor */
529 }else{
530 pOpen->aPending = aNew;
531 pOpen->aPending[pOpen->nPending-1] = id->fd;
532 }
533 }else{
534 /* There are no outstanding locks so we can close the file immediately */
535 close(id->fd);
536 }
537 releaseLockInfo(id->pLock);
538 releaseOpenCnt(id->pOpen);
539 sqlite3OsLeaveMutex();
540 TRACE2("CLOSE %-3d\n", id->fd);
541 OpenCounter(-1);
542 return SQLITE_OK;
543}
544
545/*
546** Read data from a file into a buffer. Return SQLITE_OK if all
547** bytes were read successfully and SQLITE_IOERR if anything goes
548** wrong.
549*/
550int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
551 int got;
552 SimulateIOError(SQLITE_IOERR);
553 TIMER_START;
554 got = read(id->fd, pBuf, amt);
555 TIMER_END;
556 TRACE4("READ %-3d %7d %d\n", id->fd, last_page, elapse);
557 SEEK(0);
558 /* if( got<0 ) got = 0; */
559 if( got==amt ){
560 return SQLITE_OK;
561 }else{
562 return SQLITE_IOERR;
563 }
564}
565
566/*
567** Write data from a buffer into a file. Return SQLITE_OK on success
568** or some other error code on failure.
569*/
570int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
571 int wrote = 0;
572 SimulateIOError(SQLITE_IOERR);
573 TIMER_START;
574 while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){
575 amt -= wrote;
576 pBuf = &((char*)pBuf)[wrote];
577 }
578 TIMER_END;
579 TRACE4("WRITE %-3d %7d %d\n", id->fd, last_page, elapse);
580 SEEK(0);
581 if( amt>0 ){
582 return SQLITE_FULL;
583 }
584 return SQLITE_OK;
585}
586
587/*
588** Move the read/write pointer in a file.
589*/
590int sqlite3OsSeek(OsFile *id, off_t offset){
591 SEEK(offset/1024 + 1);
592 lseek(id->fd, offset, SEEK_SET);
593 return SQLITE_OK;
594}
595
596/*
597** Make sure all writes to a particular file are committed to disk.
598**
599** Under Unix, also make sure that the directory entry for the file
600** has been created by fsync-ing the directory that contains the file.
601** If we do not do this and we encounter a power failure, the directory
602** entry for the journal might not exist after we reboot. The next
603** SQLite to access the file will not know that the journal exists (because
604** the directory entry for the journal was never created) and the transaction
605** will not roll back - possibly leading to database corruption.
606*/
607int sqlite3OsSync(OsFile *id){
608 SimulateIOError(SQLITE_IOERR);
609 TRACE2("SYNC %-3d\n", id->fd);
610 if( fsync(id->fd) ){
611 return SQLITE_IOERR;
612 }else{
613 if( id->dirfd>=0 ){
614 TRACE2("DIRSYNC %-3d\n", id->dirfd);
615 fsync(id->dirfd);
616 close(id->dirfd); /* Only need to sync once, so close the directory */
617 id->dirfd = -1; /* when we are done. */
618 }
619 return SQLITE_OK;
620 }
621}
622
623/*
624** Truncate an open file to a specified size
625*/
626int sqlite3OsTruncate(OsFile *id, off_t nByte){
627 SimulateIOError(SQLITE_IOERR);
628 return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
629}
630
631/*
632** Determine the current size of a file in bytes
633*/
634int sqlite3OsFileSize(OsFile *id, off_t *pSize){
635 struct stat buf;
636 SimulateIOError(SQLITE_IOERR);
637 if( fstat(id->fd, &buf)!=0 ){
638 return SQLITE_IOERR;
639 }
640 *pSize = buf.st_size;
641 return SQLITE_OK;
642}
643
danielk19779a1d0ab2004-06-01 14:09:28 +0000644/*
danielk197713adf8a2004-06-03 16:08:41 +0000645** This routine checks if there is a RESERVED lock held on the specified
646** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000647** non-zero. If the file is unlocked or holds only SHARED locks, then
648** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000649*/
650int sqlite3OsCheckWriteLock(OsFile *id){
651 int r = 0;
652
drh2ac3ee92004-06-07 16:27:46 +0000653 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000654
655 /* Check if a thread in this process holds such a lock */
656 if( id->pLock->locktype>SHARED_LOCK ){
657 r = 1;
658 }
659
drh2ac3ee92004-06-07 16:27:46 +0000660 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000661 */
662 if( !r ){
663 struct flock lock;
664 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000665 lock.l_start = RESERVED_BYTE;
666 lock.l_len = 1;
667 lock.l_type = F_WRLCK;
danielk197713adf8a2004-06-03 16:08:41 +0000668 fcntl(id->fd, F_GETLK, &lock);
669 if( lock.l_type!=F_UNLCK ){
670 r = 1;
671 }
672 }
673
674 sqlite3OsLeaveMutex();
drh2ac3ee92004-06-07 16:27:46 +0000675 TRACE3("TEST WR-LOCK %d %d\n", id->fd, r);
danielk197713adf8a2004-06-03 16:08:41 +0000676
677 return r;
678}
679
680/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000681** Lock the file with the lock specified by parameter locktype - one
682** of the following:
683**
drh2ac3ee92004-06-07 16:27:46 +0000684** (1) SHARED_LOCK
685** (2) RESERVED_LOCK
686** (3) PENDING_LOCK
687** (4) EXCLUSIVE_LOCK
688**
689** Locks are are hierarchical. Getting a lock N implies getting all locks
690** N-1, N-2, N-3, .... So, for example, getting a PENDING lock
691** implies a SHARED and a RESERVED lock. This routine adds locks one
692** at a time until the desired lock is acheived. A locking failure might
693** occur at any point. When a failure occurs intermediate locks are
694** retained. For example, if a SHARED lock is held and this routine
695** is called with EXCLUSIVE, it might obtain a RESERVED and PENDING lock
696** but fail to get the EXCLUSIVE lock. In that case, the file would be
697** left in the PENDING lock state - it does not revert to SHARED.
698**
699** This routine will only increase a lock. The sqlite3OsUnlock() routine
700** erases all locks at once and returns us immediately to locking level 0.
701** It is not possible to lower the locking level one step at a time. You
702** must go straight to locking level 0.
danielk19779a1d0ab2004-06-01 14:09:28 +0000703*/
704int sqlite3OsLock(OsFile *id, int locktype){
705 int rc = SQLITE_OK;
706 struct lockInfo *pLock = id->pLock;
707 struct flock lock;
708 int s;
709
drh2ac3ee92004-06-07 16:27:46 +0000710 TRACE5("LOCK %d %d was %d(%d)\n",
711 id->fd, locktype, id->locktype, pLock->locktype);
danielk19779a1d0ab2004-06-01 14:09:28 +0000712
713 /* If there is already a lock of this type or more restrictive on the
714 ** OsFile, do nothing. Don't use the end_lock: exit path, as
715 ** sqlite3OsEnterMutex() hasn't been called yet.
716 */
danielk197713adf8a2004-06-03 16:08:41 +0000717 if( id->locktype>=locktype ){
danielk19779a1d0ab2004-06-01 14:09:28 +0000718 return SQLITE_OK;
719 }
720
drh2ac3ee92004-06-07 16:27:46 +0000721 /* Make sure locking is sequential. In other words, make sure we have
722 ** SHARED before trying for RESERVED, and that we have RESERVED before
723 ** trying for PENDING, and that we have PENDING before trying for
724 ** EXCLUSIVE.
725 */
726 while( locktype>id->locktype+1 ){
727 rc = sqlite3OsLock(id, id->locktype+1);
728 if( rc!=SQLITE_OK ){
729 return rc;
730 }
731 }
732 assert( locktype==id->locktype+1 );
733
734 sqlite3OsEnterMutex(); /* Needed because pLock is shared across threads */
danielk19779a1d0ab2004-06-01 14:09:28 +0000735
736 /* If some thread using this PID has a lock via a different OsFile*
737 ** handle that precludes the requested lock, return BUSY.
738 */
danielk197713adf8a2004-06-03 16:08:41 +0000739 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +0000740 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
741 || (locktype==EXCLUSIVE_LOCK && pLock->cnt>1)
danielk19779a1d0ab2004-06-01 14:09:28 +0000742 ){
743 rc = SQLITE_BUSY;
744 goto end_lock;
745 }
746
747 /* If a SHARED lock is requested, and some thread using this PID already
748 ** has a SHARED or RESERVED lock, then increment reference counts and
749 ** return SQLITE_OK.
750 */
751 if( locktype==SHARED_LOCK &&
752 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
753 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +0000754 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +0000755 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +0000756 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +0000757 pLock->cnt++;
758 id->pOpen->nLock++;
759 goto end_lock;
760 }
761
danielk197713adf8a2004-06-03 16:08:41 +0000762 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000763 lock.l_whence = SEEK_SET;
764
765 /* If control gets to this point, then actually go ahead and make
766 ** operating system calls for the specified lock.
767 */
768 if( locktype==SHARED_LOCK ){
769 assert( pLock->cnt==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +0000770 assert( pLock->locktype==0 );
771
drh2ac3ee92004-06-07 16:27:46 +0000772 /* Temporarily grab a PENDING lock. This prevents new SHARED locks from
773 ** being formed if a PENDING lock is already held.
danielk19779a1d0ab2004-06-01 14:09:28 +0000774 */
775 lock.l_type = F_RDLCK;
drh2ac3ee92004-06-07 16:27:46 +0000776 lock.l_start = PENDING_BYTE;
drhbbd42a62004-05-22 17:41:58 +0000777 s = fcntl(id->fd, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000778 if( s ){
779 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
780 goto end_lock;
781 }
782
drh2ac3ee92004-06-07 16:27:46 +0000783 /* Now get the read-lock */
784 lock.l_start = SHARED_FIRST;
785 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000786 s = fcntl(id->fd, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +0000787
788 /* Drop the temporary PENDING lock */
789 lock.l_start = PENDING_BYTE;
790 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000791 lock.l_type = F_UNLCK;
792 fcntl(id->fd, F_SETLK, &lock);
793 if( s ){
drhbbd42a62004-05-22 17:41:58 +0000794 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
795 }else{
danielk197713adf8a2004-06-03 16:08:41 +0000796 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000797 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +0000798 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +0000799 }
800 }else{
danielk19779a1d0ab2004-06-01 14:09:28 +0000801 /* The request was for a RESERVED, PENDING or EXCLUSIVE lock. It is
802 ** assumed that there is a SHARED or greater lock on the file
803 ** already.
804 */
danielk197713adf8a2004-06-03 16:08:41 +0000805 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +0000806 lock.l_type = F_WRLCK;
807 switch( locktype ){
808 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000809 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000810 break;
811 case PENDING_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000812 lock.l_start = PENDING_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000813 break;
814 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000815 lock.l_start = SHARED_FIRST;
816 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000817 break;
818 default:
819 assert(0);
820 }
821 s = fcntl(id->fd, F_SETLK, &lock);
822 if( s ){
823 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
824 }
drhbbd42a62004-05-22 17:41:58 +0000825 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000826
danielk1977ecb2a962004-06-02 06:30:16 +0000827 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +0000828 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +0000829 pLock->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +0000830 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000831
832end_lock:
drhbbd42a62004-05-22 17:41:58 +0000833 sqlite3OsLeaveMutex();
drh2ac3ee92004-06-07 16:27:46 +0000834 TRACE4("LOCK %d %d %s\n", id->fd, locktype, rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +0000835 return rc;
836}
837
838/*
839** Unlock the given file descriptor. If the file descriptor was
840** not previously locked, then this routine is a no-op. If this
841** library was compiled with large file support (LFS) but LFS is not
842** available on the host, then an SQLITE_NOLFS is returned.
843*/
844int sqlite3OsUnlock(OsFile *id){
845 int rc;
danielk197713adf8a2004-06-03 16:08:41 +0000846 if( !id->locktype ) return SQLITE_OK;
847 id->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000848 sqlite3OsEnterMutex();
849 assert( id->pLock->cnt!=0 );
850 if( id->pLock->cnt>1 ){
851 id->pLock->cnt--;
852 rc = SQLITE_OK;
853 }else{
854 struct flock lock;
855 int s;
856 lock.l_type = F_UNLCK;
857 lock.l_whence = SEEK_SET;
858 lock.l_start = lock.l_len = 0L;
859 s = fcntl(id->fd, F_SETLK, &lock);
860 if( s!=0 ){
861 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
862 }else{
863 rc = SQLITE_OK;
864 id->pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000865 id->pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000866 }
867 }
danielk1977ecb2a962004-06-02 06:30:16 +0000868
drhbbd42a62004-05-22 17:41:58 +0000869 if( rc==SQLITE_OK ){
870 /* Decrement the count of locks against this same file. When the
871 ** count reaches zero, close any other file descriptors whose close
872 ** was deferred because of outstanding locks.
873 */
874 struct openCnt *pOpen = id->pOpen;
875 pOpen->nLock--;
876 assert( pOpen->nLock>=0 );
877 if( pOpen->nLock==0 && pOpen->nPending>0 ){
878 int i;
879 for(i=0; i<pOpen->nPending; i++){
880 close(pOpen->aPending[i]);
881 }
882 sqliteFree(pOpen->aPending);
883 pOpen->nPending = 0;
884 pOpen->aPending = 0;
885 }
886 }
887 sqlite3OsLeaveMutex();
danielk197713adf8a2004-06-03 16:08:41 +0000888 id->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000889 return rc;
890}
891
892/*
893** Get information to seed the random number generator. The seed
894** is written into the buffer zBuf[256]. The calling function must
895** supply a sufficiently large buffer.
896*/
897int sqlite3OsRandomSeed(char *zBuf){
898 /* We have to initialize zBuf to prevent valgrind from reporting
899 ** errors. The reports issued by valgrind are incorrect - we would
900 ** prefer that the randomness be increased by making use of the
901 ** uninitialized space in zBuf - but valgrind errors tend to worry
902 ** some users. Rather than argue, it seems easier just to initialize
903 ** the whole array and silence valgrind, even if that means less randomness
904 ** in the random seed.
905 **
906 ** When testing, initializing zBuf[] to zero is all we do. That means
907 ** that we always use the same random number sequence.* This makes the
908 ** tests repeatable.
909 */
910 memset(zBuf, 0, 256);
911#if !defined(SQLITE_TEST)
912 {
913 int pid;
914 time((time_t*)zBuf);
915 pid = getpid();
916 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
917 }
918#endif
919 return SQLITE_OK;
920}
921
922/*
923** Sleep for a little while. Return the amount of time slept.
924*/
925int sqlite3OsSleep(int ms){
926#if defined(HAVE_USLEEP) && HAVE_USLEEP
927 usleep(ms*1000);
928 return ms;
929#else
930 sleep((ms+999)/1000);
931 return 1000*((ms+999)/1000);
932#endif
933}
934
935/*
936** Static variables used for thread synchronization
937*/
938static int inMutex = 0;
drh79069752004-05-22 21:30:40 +0000939#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +0000940static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +0000941#endif
drhbbd42a62004-05-22 17:41:58 +0000942
943/*
944** The following pair of routine implement mutual exclusion for
945** multi-threaded processes. Only a single thread is allowed to
946** executed code that is surrounded by EnterMutex() and LeaveMutex().
947**
948** SQLite uses only a single Mutex. There is not much critical
949** code and what little there is executes quickly and without blocking.
950*/
951void sqlite3OsEnterMutex(){
952#ifdef SQLITE_UNIX_THREADS
953 pthread_mutex_lock(&mutex);
954#endif
955 assert( !inMutex );
956 inMutex = 1;
957}
958void sqlite3OsLeaveMutex(){
959 assert( inMutex );
960 inMutex = 0;
961#ifdef SQLITE_UNIX_THREADS
962 pthread_mutex_unlock(&mutex);
963#endif
964}
965
966/*
967** Turn a relative pathname into a full pathname. Return a pointer
968** to the full pathname stored in space obtained from sqliteMalloc().
969** The calling function is responsible for freeing this space once it
970** is no longer needed.
971*/
972char *sqlite3OsFullPathname(const char *zRelative){
973 char *zFull = 0;
974 if( zRelative[0]=='/' ){
975 sqlite3SetString(&zFull, zRelative, (char*)0);
976 }else{
977 char zBuf[5000];
978 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
979 (char*)0);
980 }
981 return zFull;
982}
983
984/*
985** The following variable, if set to a non-zero value, becomes the result
986** returned from sqlite3OsCurrentTime(). This is used for testing.
987*/
988#ifdef SQLITE_TEST
989int sqlite3_current_time = 0;
990#endif
991
992/*
993** Find the current time (in Universal Coordinated Time). Write the
994** current time and date as a Julian Day number into *prNow and
995** return 0. Return 1 if the time and date cannot be found.
996*/
997int sqlite3OsCurrentTime(double *prNow){
998 time_t t;
999 time(&t);
1000 *prNow = t/86400.0 + 2440587.5;
1001#ifdef SQLITE_TEST
1002 if( sqlite3_current_time ){
1003 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1004 }
1005#endif
1006 return 0;
1007}
1008
1009#endif /* OS_UNIX */