⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 os_unix.c

📁 sqlite 嵌入式数据库的源码
💻 C
📖 第 1 页 / 共 3 页
字号:
** still short of its goal.  The following chart shows the allowed** transitions and the inserted intermediate states:****    UNLOCKED -> SHARED**    SHARED -> RESERVED**    SHARED -> (PENDING) -> EXCLUSIVE**    RESERVED -> (PENDING) -> EXCLUSIVE**    PENDING -> EXCLUSIVE**** This routine will only increase a lock.  Use the sqlite3OsUnlock()** routine to lower a locking level.*/int sqlite3OsLock(OsFile *id, int locktype){  /* The following describes the implementation of the various locks and  ** lock transitions in terms of the POSIX advisory shared and exclusive  ** lock primitives (called read-locks and write-locks below, to avoid  ** confusion with SQLite lock names). The algorithms are complicated  ** slightly in order to be compatible with windows systems simultaneously  ** accessing the same database file, in case that is ever required.  **  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved  ** byte', each single bytes at well known offsets, and the 'shared byte  ** range', a range of 510 bytes at a well known offset.  **  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending  ** byte'.  If this is successful, a random byte from the 'shared byte  ** range' is read-locked and the lock on the 'pending byte' released.  **  ** A process may only obtain a RESERVED lock after it has a SHARED lock.  ** A RESERVED lock is implemented by grabbing a write-lock on the  ** 'reserved byte'.   **  ** A process may only obtain a PENDING lock after it has obtained a  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock  ** on the 'pending byte'. This ensures that no new SHARED locks can be  ** obtained, but existing SHARED locks are allowed to persist. A process  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.  ** This property is used by the algorithm for rolling back a journal file  ** after a crash.  **  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is  ** implemented by obtaining a write-lock on the entire 'shared byte  ** range'. Since all other locks require a read-lock on one of the bytes  ** within this range, this ensures that no other locks are held on the  ** database.   **  ** The reason a single byte cannot be used instead of the 'shared byte  ** range' is that some versions of windows do not support read-locks. By  ** locking a random byte from a range, concurrent SHARED locks may exist  ** even if the locking primitive used is always a write-lock.  */  int rc = SQLITE_OK;  struct lockInfo *pLock = id->pLock;  struct flock lock;  int s;  assert( id->isOpen );  TRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", id->h, locktypeName(locktype),       locktypeName(id->locktype), locktypeName(pLock->locktype), pLock->cnt      ,getpid() );  /* If there is already a lock of this type or more restrictive on the  ** OsFile, do nothing. Don't use the end_lock: exit path, as  ** sqlite3OsEnterMutex() hasn't been called yet.  */  if( id->locktype>=locktype ){    TRACE3("LOCK    %d %s ok (already held)\n", id->h, locktypeName(locktype));    return SQLITE_OK;  }  /* Make sure the locking sequence is correct  */  assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );  assert( locktype!=PENDING_LOCK );  assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );  /* This mutex is needed because id->pLock is shared across threads  */  sqlite3OsEnterMutex();  /* If some thread using this PID has a lock via a different OsFile*  ** handle that precludes the requested lock, return BUSY.  */  if( (id->locktype!=pLock->locktype &&           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))  ){    rc = SQLITE_BUSY;    goto end_lock;  }  /* If a SHARED lock is requested, and some thread using this PID already  ** has a SHARED or RESERVED lock, then increment reference counts and  ** return SQLITE_OK.  */  if( locktype==SHARED_LOCK &&       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){    assert( locktype==SHARED_LOCK );    assert( id->locktype==0 );    assert( pLock->cnt>0 );    id->locktype = SHARED_LOCK;    pLock->cnt++;    id->pOpen->nLock++;    goto end_lock;  }  lock.l_len = 1L;  lock.l_whence = SEEK_SET;  /* A PENDING lock is needed before acquiring a SHARED lock and before  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will  ** be released.  */  if( locktype==SHARED_LOCK       || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)  ){    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);    lock.l_start = PENDING_BYTE;    s = fcntl(id->h, F_SETLK, &lock);    if( s ){      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;      goto end_lock;    }  }  /* If control gets to this point, then actually go ahead and make  ** operating system calls for the specified lock.  */  if( locktype==SHARED_LOCK ){    assert( pLock->cnt==0 );    assert( pLock->locktype==0 );    /* Now get the read-lock */    lock.l_start = SHARED_FIRST;    lock.l_len = SHARED_SIZE;    s = fcntl(id->h, F_SETLK, &lock);    /* Drop the temporary PENDING lock */    lock.l_start = PENDING_BYTE;    lock.l_len = 1L;    lock.l_type = F_UNLCK;    fcntl(id->h, F_SETLK, &lock);    if( s ){      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;    }else{      id->locktype = SHARED_LOCK;      id->pOpen->nLock++;      pLock->cnt = 1;    }  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){    /* We are trying for an exclusive lock but another thread in this    ** same process is still holding a shared lock. */    rc = SQLITE_BUSY;  }else{    /* The request was for a RESERVED or EXCLUSIVE lock.  It is    ** assumed that there is a SHARED or greater lock on the file    ** already.    */    assert( 0!=id->locktype );    lock.l_type = F_WRLCK;    switch( locktype ){      case RESERVED_LOCK:        lock.l_start = RESERVED_BYTE;        break;      case EXCLUSIVE_LOCK:        lock.l_start = SHARED_FIRST;        lock.l_len = SHARED_SIZE;        break;      default:        assert(0);    }    s = fcntl(id->h, F_SETLK, &lock);    if( s ){      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;    }  }    if( rc==SQLITE_OK ){    id->locktype = locktype;    pLock->locktype = locktype;  }else if( locktype==EXCLUSIVE_LOCK ){    id->locktype = PENDING_LOCK;    pLock->locktype = PENDING_LOCK;  }end_lock:  sqlite3OsLeaveMutex();  TRACE4("LOCK    %d %s %s\n", id->h, locktypeName(locktype),       rc==SQLITE_OK ? "ok" : "failed");  return rc;}/*** Lower the locking level on file descriptor id to locktype.  locktype** must be either NO_LOCK or SHARED_LOCK.**** If the locking level of the file descriptor is already at or below** the requested locking level, this routine is a no-op.**** It is not possible for this routine to fail if the second argument** is NO_LOCK.  If the second argument is SHARED_LOCK, this routine** might return SQLITE_IOERR instead of SQLITE_OK.*/int sqlite3OsUnlock(OsFile *id, int locktype){  struct lockInfo *pLock;  struct flock lock;  int rc = SQLITE_OK;  assert( id->isOpen );  TRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", id->h, locktype, id->locktype,       id->pLock->locktype, id->pLock->cnt, getpid());  assert( locktype<=SHARED_LOCK );  if( id->locktype<=locktype ){    return SQLITE_OK;  }  sqlite3OsEnterMutex();  pLock = id->pLock;  assert( pLock->cnt!=0 );  if( id->locktype>SHARED_LOCK ){    assert( pLock->locktype==id->locktype );    if( locktype==SHARED_LOCK ){      lock.l_type = F_RDLCK;      lock.l_whence = SEEK_SET;      lock.l_start = SHARED_FIRST;      lock.l_len = SHARED_SIZE;      if( fcntl(id->h, F_SETLK, &lock)!=0 ){        /* This should never happen */        rc = SQLITE_IOERR;      }    }    lock.l_type = F_UNLCK;    lock.l_whence = SEEK_SET;    lock.l_start = PENDING_BYTE;    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );    fcntl(id->h, F_SETLK, &lock);    pLock->locktype = SHARED_LOCK;  }  if( locktype==NO_LOCK ){    struct openCnt *pOpen;    /* Decrement the shared lock counter.  Release the lock using an    ** OS call only when all threads in this same process have released    ** the lock.    */    pLock->cnt--;    if( pLock->cnt==0 ){      lock.l_type = F_UNLCK;      lock.l_whence = SEEK_SET;      lock.l_start = lock.l_len = 0L;      fcntl(id->h, F_SETLK, &lock);      pLock->locktype = NO_LOCK;    }    /* Decrement the count of locks against this same file.  When the    ** count reaches zero, close any other file descriptors whose close    ** was deferred because of outstanding locks.    */    pOpen = id->pOpen;    pOpen->nLock--;    assert( pOpen->nLock>=0 );    if( pOpen->nLock==0 && pOpen->nPending>0 ){      int i;      for(i=0; i<pOpen->nPending; i++){        close(pOpen->aPending[i]);      }      sqliteFree(pOpen->aPending);      pOpen->nPending = 0;      pOpen->aPending = 0;    }  }  sqlite3OsLeaveMutex();  id->locktype = locktype;  return rc;}/*** Close a file.*/int sqlite3OsClose(OsFile *id){  if( !id->isOpen ) return SQLITE_OK;  sqlite3OsUnlock(id, NO_LOCK);  if( id->dirfd>=0 ) close(id->dirfd);  id->dirfd = -1;  sqlite3OsEnterMutex();  if( id->pOpen->nLock ){    /* If there are outstanding locks, do not actually close the file just    ** yet because that would clear those locks.  Instead, add the file    ** descriptor to pOpen->aPending.  It will be automatically closed when    ** the last lock is cleared.    */    int *aNew;    struct openCnt *pOpen = id->pOpen;    pOpen->nPending++;    aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );    if( aNew==0 ){      /* If a malloc fails, just leak the file descriptor */    }else{      pOpen->aPending = aNew;      pOpen->aPending[pOpen->nPending-1] = id->h;    }  }else{    /* There are no outstanding locks so we can close the file immediately */    close(id->h);  }  releaseLockInfo(id->pLock);  releaseOpenCnt(id->pOpen);  sqlite3OsLeaveMutex();  id->isOpen = 0;  TRACE2("CLOSE   %-3d\n", id->h);  OpenCounter(-1);  return SQLITE_OK;}/*** Turn a relative pathname into a full pathname.  Return a pointer** to the full pathname stored in space obtained from sqliteMalloc().** The calling function is responsible for freeing this space once it** is no longer needed.*/char *sqlite3OsFullPathname(const char *zRelative){  char *zFull = 0;  if( zRelative[0]=='/' ){    sqlite3SetString(&zFull, zRelative, (char*)0);  }else{    char zBuf[5000];    zBuf[0] = 0;    sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,                    (char*)0);  }  return zFull;}#endif /* SQLITE_OMIT_DISKIO *//***************************************************************************** Everything above deals with file I/O.  Everything that follows deals** with other miscellanous aspects of the operating system interface****************************************************************************//*** Get information to seed the random number generator.  The seed** is written into the buffer zBuf[256].  The calling function must** supply a sufficiently large buffer.*/int sqlite3OsRandomSeed(char *zBuf){  /* We have to initialize zBuf to prevent valgrind from reporting  ** errors.  The reports issued by valgrind are incorrect - we would  ** prefer that the randomness be increased by making use of the  ** uninitialized space in zBuf - but valgrind errors tend to worry  ** some users.  Rather than argue, it seems easier just to initialize  ** the whole array and silence valgrind, even if that means less randomness  ** in the random seed.  **  ** When testing, initializing zBuf[] to zero is all we do.  That means  ** that we always use the same random number sequence.* This makes the  ** tests repeatable.  */  memset(zBuf, 0, 256);#if !defined(SQLITE_TEST)  {    int pid, fd;    fd = open("/dev/urandom", O_RDONLY);    if( fd<0 ){      time((time_t*)zBuf);      pid = getpid();      memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));    }else{      read(fd, zBuf, 256);      close(fd);    }  }#endif  return SQLITE_OK;}/*** Sleep for a little while.  Return the amount of time slept.*/int sqlite3OsSleep(int ms){#if defined(HAVE_USLEEP) && HAVE_USLEEP  usleep(ms*1000);  return ms;#else  sleep((ms+999)/1000);  return 1000*((ms+999)/1000);#endif}/*** Static variables used for thread synchronization*/static int inMutex = 0;#ifdef SQLITE_UNIX_THREADSstatic pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;#endif/*** The following pair of routine implement mutual exclusion for** multi-threaded processes.  Only a single thread is allowed to** executed code that is surrounded by EnterMutex() and LeaveMutex().**** SQLite uses only a single Mutex.  There is not much critical** code and what little there is executes quickly and without blocking.*/void sqlite3OsEnterMutex(){#ifdef SQLITE_UNIX_THREADS  pthread_mutex_lock(&mutex);#endif  assert( !inMutex );  inMutex = 1;}void sqlite3OsLeaveMutex(){  assert( inMutex );  inMutex = 0;#ifdef SQLITE_UNIX_THREADS  pthread_mutex_unlock(&mutex);#endif}/*** The following variable, if set to a non-zero value, becomes the result** returned from sqlite3OsCurrentTime().  This is used for testing.*/#ifdef SQLITE_TESTint sqlite3_current_time = 0;#endif/*** Find the current time (in Universal Coordinated Time).  Write the** current time and date as a Julian Day number into *prNow and** return 0.  Return 1 if the time and date cannot be found.*/int sqlite3OsCurrentTime(double *prNow){  time_t t;  time(&t);  *prNow = t/86400.0 + 2440587.5;#ifdef SQLITE_TEST  if( sqlite3_current_time ){    *prNow = sqlite3_current_time/86400.0 + 2440587.5;  }#endif  return 0;}#endif /* OS_UNIX */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -