persistentstorage/sqlite3api/SQLite/pager.c
changeset 0 08ec8eefde2f
equal deleted inserted replaced
-1:000000000000 0:08ec8eefde2f
       
     1 /*
       
     2 ** 2001 September 15
       
     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 ** This is the implementation of the page cache subsystem or "pager".
       
    13 ** 
       
    14 ** The pager is used to access a database disk file.  It implements
       
    15 ** atomic commit and rollback through the use of a journal file that
       
    16 ** is separate from the database file.  The pager also implements file
       
    17 ** locking to prevent two processes from writing the same database
       
    18 ** file simultaneously, or one process from reading the database while
       
    19 ** another is writing.
       
    20 **
       
    21 ** @(#) $Id: pager.c,v 1.496 2008/09/29 11:49:48 danielk1977 Exp $
       
    22 */
       
    23 #ifndef SQLITE_OMIT_DISKIO
       
    24 #include "sqliteInt.h"
       
    25 
       
    26 /*
       
    27 ** Macros for troubleshooting.  Normally turned off
       
    28 */
       
    29 #if 0
       
    30 #define sqlite3DebugPrintf printf
       
    31 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
       
    32 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
       
    33 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
       
    34 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
       
    35 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
       
    36 #else
       
    37 #define PAGERTRACE1(X)
       
    38 #define PAGERTRACE2(X,Y)
       
    39 #define PAGERTRACE3(X,Y,Z)
       
    40 #define PAGERTRACE4(X,Y,Z,W)
       
    41 #define PAGERTRACE5(X,Y,Z,W,V)
       
    42 #endif
       
    43 
       
    44 /*
       
    45 ** The following two macros are used within the PAGERTRACEX() macros above
       
    46 ** to print out file-descriptors. 
       
    47 **
       
    48 ** PAGERID() takes a pointer to a Pager struct as its argument. The
       
    49 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
       
    50 ** struct as its argument.
       
    51 */
       
    52 #define PAGERID(p) ((int)(p->fd))
       
    53 #define FILEHANDLEID(fd) ((int)fd)
       
    54 
       
    55 /*
       
    56 ** The page cache as a whole is always in one of the following
       
    57 ** states:
       
    58 **
       
    59 **   PAGER_UNLOCK        The page cache is not currently reading or 
       
    60 **                       writing the database file.  There is no
       
    61 **                       data held in memory.  This is the initial
       
    62 **                       state.
       
    63 **
       
    64 **   PAGER_SHARED        The page cache is reading the database.
       
    65 **                       Writing is not permitted.  There can be
       
    66 **                       multiple readers accessing the same database
       
    67 **                       file at the same time.
       
    68 **
       
    69 **   PAGER_RESERVED      This process has reserved the database for writing
       
    70 **                       but has not yet made any changes.  Only one process
       
    71 **                       at a time can reserve the database.  The original
       
    72 **                       database file has not been modified so other
       
    73 **                       processes may still be reading the on-disk
       
    74 **                       database file.
       
    75 **
       
    76 **   PAGER_EXCLUSIVE     The page cache is writing the database.
       
    77 **                       Access is exclusive.  No other processes or
       
    78 **                       threads can be reading or writing while one
       
    79 **                       process is writing.
       
    80 **
       
    81 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
       
    82 **                       after all dirty pages have been written to the
       
    83 **                       database file and the file has been synced to
       
    84 **                       disk. All that remains to do is to remove or
       
    85 **                       truncate the journal file and the transaction 
       
    86 **                       will be committed.
       
    87 **
       
    88 ** The page cache comes up in PAGER_UNLOCK.  The first time a
       
    89 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
       
    90 ** After all pages have been released using sqlite_page_unref(),
       
    91 ** the state transitions back to PAGER_UNLOCK.  The first time
       
    92 ** that sqlite3PagerWrite() is called, the state transitions to
       
    93 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
       
    94 ** called on an outstanding page which means that the pager must
       
    95 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
       
    96 ** PAGER_RESERVED means that there is an open rollback journal.
       
    97 ** The transition to PAGER_EXCLUSIVE occurs before any changes
       
    98 ** are made to the database file, though writes to the rollback
       
    99 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
       
   100 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
       
   101 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
       
   102 */
       
   103 #define PAGER_UNLOCK      0
       
   104 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
       
   105 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
       
   106 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
       
   107 #define PAGER_SYNCED      5
       
   108 
       
   109 /*
       
   110 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
       
   111 ** then failed attempts to get a reserved lock will invoke the busy callback.
       
   112 ** This is off by default.  To see why, consider the following scenario:
       
   113 ** 
       
   114 ** Suppose thread A already has a shared lock and wants a reserved lock.
       
   115 ** Thread B already has a reserved lock and wants an exclusive lock.  If
       
   116 ** both threads are using their busy callbacks, it might be a long time
       
   117 ** be for one of the threads give up and allows the other to proceed.
       
   118 ** But if the thread trying to get the reserved lock gives up quickly
       
   119 ** (if it never invokes its busy callback) then the contention will be
       
   120 ** resolved quickly.
       
   121 */
       
   122 #ifndef SQLITE_BUSY_RESERVED_LOCK
       
   123 # define SQLITE_BUSY_RESERVED_LOCK 0
       
   124 #endif
       
   125 
       
   126 /*
       
   127 ** This macro rounds values up so that if the value is an address it
       
   128 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
       
   129 */
       
   130 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
       
   131 
       
   132 /*
       
   133 ** A macro used for invoking the codec if there is one
       
   134 */
       
   135 #ifdef SQLITE_HAS_CODEC
       
   136 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
       
   137 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
       
   138 #else
       
   139 # define CODEC1(P,D,N,X) /* NO-OP */
       
   140 # define CODEC2(P,D,N,X) ((char*)D)
       
   141 #endif
       
   142 
       
   143 /*
       
   144 ** A open page cache is an instance of the following structure.
       
   145 **
       
   146 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
       
   147 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
       
   148 ** and is returned as the result of every major pager API call.  The
       
   149 ** SQLITE_FULL return code is slightly different. It persists only until the
       
   150 ** next successful rollback is performed on the pager cache. Also,
       
   151 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
       
   152 ** APIs, they may still be used successfully.
       
   153 */
       
   154 struct Pager {
       
   155   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
       
   156   u8 journalOpen;             /* True if journal file descriptors is valid */
       
   157   u8 journalStarted;          /* True if header of journal is synced */
       
   158   u8 useJournal;              /* Use a rollback journal on this file */
       
   159   u8 noReadlock;              /* Do not bother to obtain readlocks */
       
   160   u8 stmtOpen;                /* True if the statement subjournal is open */
       
   161   u8 stmtInUse;               /* True we are in a statement subtransaction */
       
   162   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
       
   163   u8 noSync;                  /* Do not sync the journal if true */
       
   164   u8 fullSync;                /* Do extra syncs of the journal for robustness */
       
   165   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
       
   166   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
       
   167   u8 tempFile;                /* zFilename is a temporary file */
       
   168   u8 readOnly;                /* True for a read-only database */
       
   169   u8 needSync;                /* True if an fsync() is needed on the journal */
       
   170   u8 dirtyCache;              /* True if cached pages have changed */
       
   171   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
       
   172   u8 memDb;                   /* True to inhibit all file I/O */
       
   173   u8 setMaster;               /* True if a m-j name has been written to jrnl */
       
   174   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
       
   175   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
       
   176   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
       
   177   u8 dbModified;              /* True if there are any changes to the Db */
       
   178   u8 changeCountDone;         /* Set after incrementing the change-counter */
       
   179   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
       
   180   int errCode;                /* One of several kinds of errors */
       
   181   int dbSize;                 /* Number of pages in the file */
       
   182   int origDbSize;             /* dbSize before the current change */
       
   183   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
       
   184   int nRec;                   /* Number of pages written to the journal */
       
   185   u32 cksumInit;              /* Quasi-random value added to every checksum */
       
   186   int stmtNRec;               /* Number of records in stmt subjournal */
       
   187   int nExtra;                 /* Add this many bytes to each in-memory page */
       
   188   int pageSize;               /* Number of bytes in a page */
       
   189   int nPage;                  /* Total number of in-memory pages */
       
   190   int mxPage;                 /* Maximum number of pages to hold in cache */
       
   191   Pgno mxPgno;                /* Maximum allowed size of the database */
       
   192   Bitvec *pInJournal;         /* One bit for each page in the database file */
       
   193   Bitvec *pInStmt;            /* One bit for each page in the database */
       
   194   Bitvec *pAlwaysRollback;    /* One bit for each page marked always-rollback */
       
   195   char *zFilename;            /* Name of the database file */
       
   196   char *zJournal;             /* Name of the journal file */
       
   197   char *zDirectory;           /* Directory hold database and journal files */
       
   198   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
       
   199   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
       
   200   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
       
   201   i64 journalOff;             /* Current byte offset in the journal file */
       
   202   i64 journalHdr;             /* Byte offset to previous journal header */
       
   203   i64 stmtHdrOff;             /* First journal header written this statement */
       
   204   i64 stmtCksum;              /* cksumInit when statement was started */
       
   205   i64 stmtJSize;              /* Size of journal at stmt_begin() */
       
   206   int sectorSize;             /* Assumed sector size during rollback */
       
   207 #ifdef SQLITE_TEST
       
   208   int nHit, nMiss;            /* Cache hits and missing */
       
   209   int nRead, nWrite;          /* Database pages read/written */
       
   210 #endif
       
   211   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
       
   212 #ifdef SQLITE_HAS_CODEC
       
   213   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
       
   214   void *pCodecArg;            /* First argument to xCodec() */
       
   215 #endif
       
   216   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
       
   217   char dbFileVers[16];        /* Changes whenever database file changes */
       
   218   i64 journalSizeLimit;       /* Size limit for persistent journal files */
       
   219   PCache *pPCache;            /* Pointer to page cache object */
       
   220 };
       
   221 
       
   222 /*
       
   223 ** The following global variables hold counters used for
       
   224 ** testing purposes only.  These variables do not exist in
       
   225 ** a non-testing build.  These variables are not thread-safe.
       
   226 */
       
   227 #ifdef SQLITE_TEST
       
   228 int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
       
   229 int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
       
   230 int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
       
   231 # define PAGER_INCR(v)  v++
       
   232 #else
       
   233 # define PAGER_INCR(v)
       
   234 #endif
       
   235 
       
   236 
       
   237 
       
   238 /*
       
   239 ** Journal files begin with the following magic string.  The data
       
   240 ** was obtained from /dev/random.  It is used only as a sanity check.
       
   241 **
       
   242 ** Since version 2.8.0, the journal format contains additional sanity
       
   243 ** checking information.  If the power fails while the journal is begin
       
   244 ** written, semi-random garbage data might appear in the journal
       
   245 ** file after power is restored.  If an attempt is then made
       
   246 ** to roll the journal back, the database could be corrupted.  The additional
       
   247 ** sanity checking data is an attempt to discover the garbage in the
       
   248 ** journal and ignore it.
       
   249 **
       
   250 ** The sanity checking information for the new journal format consists
       
   251 ** of a 32-bit checksum on each page of data.  The checksum covers both
       
   252 ** the page number and the pPager->pageSize bytes of data for the page.
       
   253 ** This cksum is initialized to a 32-bit random value that appears in the
       
   254 ** journal file right after the header.  The random initializer is important,
       
   255 ** because garbage data that appears at the end of a journal is likely
       
   256 ** data that was once in other files that have now been deleted.  If the
       
   257 ** garbage data came from an obsolete journal file, the checksums might
       
   258 ** be correct.  But by initializing the checksum to random value which
       
   259 ** is different for every journal, we minimize that risk.
       
   260 */
       
   261 static const unsigned char aJournalMagic[] = {
       
   262   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
       
   263 };
       
   264 
       
   265 /*
       
   266 ** The size of the header and of each page in the journal is determined
       
   267 ** by the following macros.
       
   268 */
       
   269 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
       
   270 
       
   271 /*
       
   272 ** The journal header size for this pager. In the future, this could be
       
   273 ** set to some value read from the disk controller. The important
       
   274 ** characteristic is that it is the same size as a disk sector.
       
   275 */
       
   276 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
       
   277 
       
   278 /*
       
   279 ** The macro MEMDB is true if we are dealing with an in-memory database.
       
   280 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
       
   281 ** the value of MEMDB will be a constant and the compiler will optimize
       
   282 ** out code that would never execute.
       
   283 */
       
   284 #ifdef SQLITE_OMIT_MEMORYDB
       
   285 # define MEMDB 0
       
   286 #else
       
   287 # define MEMDB pPager->memDb
       
   288 #endif
       
   289 
       
   290 /*
       
   291 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
       
   292 ** reserved for working around a windows/posix incompatibility). It is
       
   293 ** used in the journal to signify that the remainder of the journal file 
       
   294 ** is devoted to storing a master journal name - there are no more pages to
       
   295 ** roll back. See comments for function writeMasterJournal() for details.
       
   296 */
       
   297 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
       
   298 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
       
   299 
       
   300 /*
       
   301 ** The maximum legal page number is (2^31 - 1).
       
   302 */
       
   303 #define PAGER_MAX_PGNO 2147483647
       
   304 
       
   305 /*
       
   306 ** Return true if page *pPg has already been written to the statement
       
   307 ** journal (or statement snapshot has been created, if *pPg is part
       
   308 ** of an in-memory database).
       
   309 */
       
   310 static int pageInStatement(PgHdr *pPg){
       
   311   Pager *pPager = pPg->pPager;
       
   312   if( MEMDB ){
       
   313     return pPg->apSave[1]!=0;
       
   314   }else{
       
   315     return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
       
   316   }
       
   317 }
       
   318 
       
   319 /*
       
   320 ** Read a 32-bit integer from the given file descriptor.  Store the integer
       
   321 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
       
   322 ** error code is something goes wrong.
       
   323 **
       
   324 ** All values are stored on disk as big-endian.
       
   325 */
       
   326 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
       
   327   unsigned char ac[4];
       
   328   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
       
   329   if( rc==SQLITE_OK ){
       
   330     *pRes = sqlite3Get4byte(ac);
       
   331   }
       
   332   return rc;
       
   333 }
       
   334 
       
   335 /*
       
   336 ** Write a 32-bit integer into a string buffer in big-endian byte order.
       
   337 */
       
   338 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
       
   339 
       
   340 /*
       
   341 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
       
   342 ** on success or an error code is something goes wrong.
       
   343 */
       
   344 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
       
   345   char ac[4];
       
   346   put32bits(ac, val);
       
   347   return sqlite3OsWrite(fd, ac, 4, offset);
       
   348 }
       
   349 
       
   350 /*
       
   351 ** If file pFd is open, call sqlite3OsUnlock() on it.
       
   352 */
       
   353 static int osUnlock(sqlite3_file *pFd, int eLock){
       
   354   if( !pFd->pMethods ){
       
   355     return SQLITE_OK;
       
   356   }
       
   357   return sqlite3OsUnlock(pFd, eLock);
       
   358 }
       
   359 
       
   360 /*
       
   361 ** This function determines whether or not the atomic-write optimization
       
   362 ** can be used with this pager. The optimization can be used if:
       
   363 **
       
   364 **  (a) the value returned by OsDeviceCharacteristics() indicates that
       
   365 **      a database page may be written atomically, and
       
   366 **  (b) the value returned by OsSectorSize() is less than or equal
       
   367 **      to the page size.
       
   368 **
       
   369 ** If the optimization cannot be used, 0 is returned. If it can be used,
       
   370 ** then the value returned is the size of the journal file when it
       
   371 ** contains rollback data for exactly one page.
       
   372 */
       
   373 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
       
   374 static int jrnlBufferSize(Pager *pPager){
       
   375   int dc;           /* Device characteristics */
       
   376   int nSector;      /* Sector size */
       
   377   int szPage;        /* Page size */
       
   378   sqlite3_file *fd = pPager->fd;
       
   379 
       
   380   if( fd->pMethods ){
       
   381     dc = sqlite3OsDeviceCharacteristics(fd);
       
   382     nSector = sqlite3OsSectorSize(fd);
       
   383     szPage = pPager->pageSize;
       
   384   }
       
   385 
       
   386   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
       
   387   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
       
   388 
       
   389   if( !fd->pMethods || 
       
   390        (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
       
   391     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
       
   392   }
       
   393   return 0;
       
   394 }
       
   395 #endif
       
   396 
       
   397 /*
       
   398 ** This function should be called when an error occurs within the pager
       
   399 ** code. The first argument is a pointer to the pager structure, the
       
   400 ** second the error-code about to be returned by a pager API function. 
       
   401 ** The value returned is a copy of the second argument to this function. 
       
   402 **
       
   403 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
       
   404 ** the error becomes persistent. Until the persisten error is cleared,
       
   405 ** subsequent API calls on this Pager will immediately return the same 
       
   406 ** error code.
       
   407 **
       
   408 ** A persistent error indicates that the contents of the pager-cache 
       
   409 ** cannot be trusted. This state can be cleared by completely discarding 
       
   410 ** the contents of the pager-cache. If a transaction was active when
       
   411 ** the persistent error occured, then the rollback journal may need
       
   412 ** to be replayed.
       
   413 */
       
   414 static void pager_unlock(Pager *pPager);
       
   415 static int pager_error(Pager *pPager, int rc){
       
   416   int rc2 = rc & 0xff;
       
   417   assert(
       
   418        pPager->errCode==SQLITE_FULL ||
       
   419        pPager->errCode==SQLITE_OK ||
       
   420        (pPager->errCode & 0xff)==SQLITE_IOERR
       
   421   );
       
   422   if(
       
   423     rc2==SQLITE_FULL ||
       
   424     rc2==SQLITE_IOERR ||
       
   425     rc2==SQLITE_CORRUPT
       
   426   ){
       
   427     pPager->errCode = rc;
       
   428     if( pPager->state==PAGER_UNLOCK 
       
   429      && sqlite3PcacheRefCount(pPager->pPCache)==0 
       
   430     ){
       
   431       /* If the pager is already unlocked, call pager_unlock() now to
       
   432       ** clear the error state and ensure that the pager-cache is 
       
   433       ** completely empty.
       
   434       */
       
   435       pager_unlock(pPager);
       
   436     }
       
   437   }
       
   438   return rc;
       
   439 }
       
   440 
       
   441 /*
       
   442 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
       
   443 ** on the cache using a hash function.  This is used for testing
       
   444 ** and debugging only.
       
   445 */
       
   446 #ifdef SQLITE_CHECK_PAGES
       
   447 /*
       
   448 ** Return a 32-bit hash of the page data for pPage.
       
   449 */
       
   450 static u32 pager_datahash(int nByte, unsigned char *pData){
       
   451   u32 hash = 0;
       
   452   int i;
       
   453   for(i=0; i<nByte; i++){
       
   454     hash = (hash*1039) + pData[i];
       
   455   }
       
   456   return hash;
       
   457 }
       
   458 static u32 pager_pagehash(PgHdr *pPage){
       
   459   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
       
   460 }
       
   461 static u32 pager_set_pagehash(PgHdr *pPage){
       
   462   pPage->pageHash = pager_pagehash(pPage);
       
   463 }
       
   464 
       
   465 /*
       
   466 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
       
   467 ** is defined, and NDEBUG is not defined, an assert() statement checks
       
   468 ** that the page is either dirty or still matches the calculated page-hash.
       
   469 */
       
   470 #define CHECK_PAGE(x) checkPage(x)
       
   471 static void checkPage(PgHdr *pPg){
       
   472   Pager *pPager = pPg->pPager;
       
   473   assert( !pPg->pageHash || pPager->errCode || MEMDB 
       
   474       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
       
   475 }
       
   476 
       
   477 #else
       
   478 #define pager_datahash(X,Y)  0
       
   479 #define pager_pagehash(X)  0
       
   480 #define CHECK_PAGE(x)
       
   481 #endif  /* SQLITE_CHECK_PAGES */
       
   482 
       
   483 /*
       
   484 ** When this is called the journal file for pager pPager must be open.
       
   485 ** The master journal file name is read from the end of the file and 
       
   486 ** written into memory supplied by the caller. 
       
   487 **
       
   488 ** zMaster must point to a buffer of at least nMaster bytes allocated by
       
   489 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
       
   490 ** enough space to write the master journal name). If the master journal
       
   491 ** name in the journal is longer than nMaster bytes (including a
       
   492 ** nul-terminator), then this is handled as if no master journal name
       
   493 ** were present in the journal.
       
   494 **
       
   495 ** If no master journal file name is present zMaster[0] is set to 0 and
       
   496 ** SQLITE_OK returned.
       
   497 */
       
   498 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
       
   499   int rc;
       
   500   u32 len;
       
   501   i64 szJ;
       
   502   u32 cksum;
       
   503   u32 u;                   /* Unsigned loop counter */
       
   504   unsigned char aMagic[8]; /* A buffer to hold the magic header */
       
   505 
       
   506   zMaster[0] = '\0';
       
   507 
       
   508   rc = sqlite3OsFileSize(pJrnl, &szJ);
       
   509   if( rc!=SQLITE_OK || szJ<16 ) return rc;
       
   510 
       
   511   rc = read32bits(pJrnl, szJ-16, &len);
       
   512   if( rc!=SQLITE_OK ) return rc;
       
   513 
       
   514   if( len>=nMaster ){
       
   515     return SQLITE_OK;
       
   516   }
       
   517 
       
   518   rc = read32bits(pJrnl, szJ-12, &cksum);
       
   519   if( rc!=SQLITE_OK ) return rc;
       
   520 
       
   521   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
       
   522   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
       
   523 
       
   524   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
       
   525   if( rc!=SQLITE_OK ){
       
   526     return rc;
       
   527   }
       
   528   zMaster[len] = '\0';
       
   529 
       
   530   /* See if the checksum matches the master journal name */
       
   531   for(u=0; u<len; u++){
       
   532     cksum -= zMaster[u];
       
   533    }
       
   534   if( cksum ){
       
   535     /* If the checksum doesn't add up, then one or more of the disk sectors
       
   536     ** containing the master journal filename is corrupted. This means
       
   537     ** definitely roll back, so just return SQLITE_OK and report a (nul)
       
   538     ** master-journal filename.
       
   539     */
       
   540     zMaster[0] = '\0';
       
   541   }
       
   542    
       
   543   return SQLITE_OK;
       
   544 }
       
   545 
       
   546 /*
       
   547 ** Seek the journal file descriptor to the next sector boundary where a
       
   548 ** journal header may be read or written. Pager.journalOff is updated with
       
   549 ** the new seek offset.
       
   550 **
       
   551 ** i.e for a sector size of 512:
       
   552 **
       
   553 ** Input Offset              Output Offset
       
   554 ** ---------------------------------------
       
   555 ** 0                         0
       
   556 ** 512                       512
       
   557 ** 100                       512
       
   558 ** 2000                      2048
       
   559 ** 
       
   560 */
       
   561 static void seekJournalHdr(Pager *pPager){
       
   562   i64 offset = 0;
       
   563   i64 c = pPager->journalOff;
       
   564   if( c ){
       
   565     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
       
   566   }
       
   567   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
       
   568   assert( offset>=c );
       
   569   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
       
   570   pPager->journalOff = offset;
       
   571 }
       
   572 
       
   573 /*
       
   574 ** Write zeros over the header of the journal file.  This has the
       
   575 ** effect of invalidating the journal file and committing the
       
   576 ** transaction.
       
   577 */
       
   578 static int zeroJournalHdr(Pager *pPager, int doTruncate){
       
   579   int rc = SQLITE_OK;
       
   580   static const char zeroHdr[28] = {0};
       
   581 
       
   582   if( pPager->journalOff ){
       
   583     i64 iLimit = pPager->journalSizeLimit;
       
   584 
       
   585     IOTRACE(("JZEROHDR %p\n", pPager))
       
   586     if( doTruncate || iLimit==0 ){
       
   587       rc = sqlite3OsTruncate(pPager->jfd, 0);
       
   588     }else{
       
   589       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
       
   590     }
       
   591     if( rc==SQLITE_OK && !pPager->noSync ){
       
   592       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
       
   593     }
       
   594 
       
   595     /* At this point the transaction is committed but the write lock 
       
   596     ** is still held on the file. If there is a size limit configured for 
       
   597     ** the persistent journal and the journal file currently consumes more
       
   598     ** space than that limit allows for, truncate it now. There is no need
       
   599     ** to sync the file following this operation.
       
   600     */
       
   601     if( rc==SQLITE_OK && iLimit>0 ){
       
   602       i64 sz;
       
   603       rc = sqlite3OsFileSize(pPager->jfd, &sz);
       
   604       if( rc==SQLITE_OK && sz>iLimit ){
       
   605         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
       
   606       }
       
   607     }
       
   608   }
       
   609   return rc;
       
   610 }
       
   611 
       
   612 /*
       
   613 ** The journal file must be open when this routine is called. A journal
       
   614 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
       
   615 ** current location.
       
   616 **
       
   617 ** The format for the journal header is as follows:
       
   618 ** - 8 bytes: Magic identifying journal format.
       
   619 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
       
   620 ** - 4 bytes: Random number used for page hash.
       
   621 ** - 4 bytes: Initial database page count.
       
   622 ** - 4 bytes: Sector size used by the process that wrote this journal.
       
   623 ** - 4 bytes: Database page size.
       
   624 ** 
       
   625 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
       
   626 */
       
   627 static int writeJournalHdr(Pager *pPager){
       
   628   int rc = SQLITE_OK;
       
   629   char *zHeader = pPager->pTmpSpace;
       
   630   int nHeader = pPager->pageSize;
       
   631   int nWrite;
       
   632 
       
   633   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
       
   634     nHeader = JOURNAL_HDR_SZ(pPager);
       
   635   }
       
   636 
       
   637   if( pPager->stmtHdrOff==0 ){
       
   638     pPager->stmtHdrOff = pPager->journalOff;
       
   639   }
       
   640 
       
   641   seekJournalHdr(pPager);
       
   642   pPager->journalHdr = pPager->journalOff;
       
   643 
       
   644   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
       
   645 
       
   646   /* 
       
   647   ** Write the nRec Field - the number of page records that follow this
       
   648   ** journal header. Normally, zero is written to this value at this time.
       
   649   ** After the records are added to the journal (and the journal synced, 
       
   650   ** if in full-sync mode), the zero is overwritten with the true number
       
   651   ** of records (see syncJournal()).
       
   652   **
       
   653   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
       
   654   ** reading the journal this value tells SQLite to assume that the
       
   655   ** rest of the journal file contains valid page records. This assumption
       
   656   ** is dangerous, as if a failure occured whilst writing to the journal
       
   657   ** file it may contain some garbage data. There are two scenarios
       
   658   ** where this risk can be ignored:
       
   659   **
       
   660   **   * When the pager is in no-sync mode. Corruption can follow a
       
   661   **     power failure in this case anyway.
       
   662   **
       
   663   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
       
   664   **     that garbage data is never appended to the journal file.
       
   665   */
       
   666   assert(pPager->fd->pMethods||pPager->noSync);
       
   667   if( (pPager->noSync) 
       
   668    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
       
   669   ){
       
   670     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
       
   671   }else{
       
   672     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
       
   673   }
       
   674 
       
   675   /* The random check-hash initialiser */ 
       
   676   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
       
   677   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
       
   678   /* The initial database size */
       
   679   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
       
   680   /* The assumed sector size for this process */
       
   681   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
       
   682   if( pPager->journalHdr==0 ){
       
   683     /* The page size */
       
   684     put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
       
   685   }
       
   686 
       
   687   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
       
   688     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
       
   689     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
       
   690     pPager->journalOff += nHeader;
       
   691   }
       
   692 
       
   693   return rc;
       
   694 }
       
   695 
       
   696 /*
       
   697 ** The journal file must be open when this is called. A journal header file
       
   698 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
       
   699 ** file. See comments above function writeJournalHdr() for a description of
       
   700 ** the journal header format.
       
   701 **
       
   702 ** If the header is read successfully, *nRec is set to the number of
       
   703 ** page records following this header and *dbSize is set to the size of the
       
   704 ** database before the transaction began, in pages. Also, pPager->cksumInit
       
   705 ** is set to the value read from the journal header. SQLITE_OK is returned
       
   706 ** in this case.
       
   707 **
       
   708 ** If the journal header file appears to be corrupted, SQLITE_DONE is
       
   709 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
       
   710 ** cannot be read from the journal file an error code is returned.
       
   711 */
       
   712 static int readJournalHdr(
       
   713   Pager *pPager, 
       
   714   i64 journalSize,
       
   715   u32 *pNRec, 
       
   716   u32 *pDbSize
       
   717 ){
       
   718   int rc;
       
   719   unsigned char aMagic[8]; /* A buffer to hold the magic header */
       
   720   i64 jrnlOff;
       
   721   int iPageSize;
       
   722 
       
   723   seekJournalHdr(pPager);
       
   724   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
       
   725     return SQLITE_DONE;
       
   726   }
       
   727   jrnlOff = pPager->journalOff;
       
   728 
       
   729   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
       
   730   if( rc ) return rc;
       
   731   jrnlOff += sizeof(aMagic);
       
   732 
       
   733   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
       
   734     return SQLITE_DONE;
       
   735   }
       
   736 
       
   737   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
       
   738   if( rc ) return rc;
       
   739 
       
   740   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
       
   741   if( rc ) return rc;
       
   742 
       
   743   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
       
   744   if( rc ) return rc;
       
   745 
       
   746   rc = read32bits(pPager->jfd, jrnlOff+16, (u32 *)&iPageSize);
       
   747   if( rc==SQLITE_OK 
       
   748    && iPageSize>=512 
       
   749    && iPageSize<=SQLITE_MAX_PAGE_SIZE 
       
   750    && ((iPageSize-1)&iPageSize)==0 
       
   751   ){
       
   752     u16 pagesize = iPageSize;
       
   753     rc = sqlite3PagerSetPagesize(pPager, &pagesize);
       
   754   }
       
   755   if( rc ) return rc;
       
   756 
       
   757   /* Update the assumed sector-size to match the value used by 
       
   758   ** the process that created this journal. If this journal was
       
   759   ** created by a process other than this one, then this routine
       
   760   ** is being called from within pager_playback(). The local value
       
   761   ** of Pager.sectorSize is restored at the end of that routine.
       
   762   */
       
   763   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
       
   764   if( rc ) return rc;
       
   765 
       
   766   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
       
   767   return SQLITE_OK;
       
   768 }
       
   769 
       
   770 
       
   771 /*
       
   772 ** Write the supplied master journal name into the journal file for pager
       
   773 ** pPager at the current location. The master journal name must be the last
       
   774 ** thing written to a journal file. If the pager is in full-sync mode, the
       
   775 ** journal file descriptor is advanced to the next sector boundary before
       
   776 ** anything is written. The format is:
       
   777 **
       
   778 ** + 4 bytes: PAGER_MJ_PGNO.
       
   779 ** + N bytes: length of master journal name.
       
   780 ** + 4 bytes: N
       
   781 ** + 4 bytes: Master journal name checksum.
       
   782 ** + 8 bytes: aJournalMagic[].
       
   783 **
       
   784 ** The master journal page checksum is the sum of the bytes in the master
       
   785 ** journal name.
       
   786 **
       
   787 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
       
   788 ** this call is a no-op.
       
   789 */
       
   790 static int writeMasterJournal(Pager *pPager, const char *zMaster){
       
   791   int rc;
       
   792   int len; 
       
   793   int i; 
       
   794   i64 jrnlOff;
       
   795   i64 jrnlSize;
       
   796   u32 cksum = 0;
       
   797   char zBuf[sizeof(aJournalMagic)+2*4];
       
   798 
       
   799   if( !zMaster || pPager->setMaster) return SQLITE_OK;
       
   800   pPager->setMaster = 1;
       
   801 
       
   802   len = strlen(zMaster);
       
   803   for(i=0; i<len; i++){
       
   804     cksum += zMaster[i];
       
   805   }
       
   806 
       
   807   /* If in full-sync mode, advance to the next disk sector before writing
       
   808   ** the master journal name. This is in case the previous page written to
       
   809   ** the journal has already been synced.
       
   810   */
       
   811   if( pPager->fullSync ){
       
   812     seekJournalHdr(pPager);
       
   813   }
       
   814   jrnlOff = pPager->journalOff;
       
   815   pPager->journalOff += (len+20);
       
   816 
       
   817   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
       
   818   if( rc!=SQLITE_OK ) return rc;
       
   819   jrnlOff += 4;
       
   820 
       
   821   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
       
   822   if( rc!=SQLITE_OK ) return rc;
       
   823   jrnlOff += len;
       
   824 
       
   825   put32bits(zBuf, len);
       
   826   put32bits(&zBuf[4], cksum);
       
   827   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
       
   828   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
       
   829   jrnlOff += 8+sizeof(aJournalMagic);
       
   830   pPager->needSync = !pPager->noSync;
       
   831 
       
   832   /* If the pager is in peristent-journal mode, then the physical 
       
   833   ** journal-file may extend past the end of the master-journal name
       
   834   ** and 8 bytes of magic data just written to the file. This is 
       
   835   ** dangerous because the code to rollback a hot-journal file
       
   836   ** will not be able to find the master-journal name to determine 
       
   837   ** whether or not the journal is hot. 
       
   838   **
       
   839   ** Easiest thing to do in this scenario is to truncate the journal 
       
   840   ** file to the required size.
       
   841   */ 
       
   842   if( (rc==SQLITE_OK)
       
   843    && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
       
   844    && jrnlSize>jrnlOff
       
   845   ){
       
   846     rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
       
   847   }
       
   848   return rc;
       
   849 }
       
   850 
       
   851 /*
       
   852 ** Find a page in the hash table given its page number.  Return
       
   853 ** a pointer to the page or NULL if not found.
       
   854 */
       
   855 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
       
   856   PgHdr *p;
       
   857   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
       
   858   return p;
       
   859 }
       
   860 
       
   861 /*
       
   862 ** Clear the in-memory cache.  This routine
       
   863 ** sets the state of the pager back to what it was when it was first
       
   864 ** opened.  Any outstanding pages are invalidated and subsequent attempts
       
   865 ** to access those pages will likely result in a coredump.
       
   866 */
       
   867 static void pager_reset(Pager *pPager){
       
   868   if( pPager->errCode ) return;
       
   869   sqlite3PcacheClear(pPager->pPCache);
       
   870 }
       
   871 
       
   872 /*
       
   873 ** Unlock the database file. 
       
   874 **
       
   875 ** If the pager is currently in error state, discard the contents of 
       
   876 ** the cache and reset the Pager structure internal state. If there is
       
   877 ** an open journal-file, then the next time a shared-lock is obtained
       
   878 ** on the pager file (by this or any other process), it will be
       
   879 ** treated as a hot-journal and rolled back.
       
   880 */
       
   881 static void pager_unlock(Pager *pPager){
       
   882   if( !pPager->exclusiveMode ){
       
   883     if( !MEMDB ){
       
   884       int rc = osUnlock(pPager->fd, NO_LOCK);
       
   885       if( rc ) pPager->errCode = rc;
       
   886       pPager->dbSize = -1;
       
   887       IOTRACE(("UNLOCK %p\n", pPager))
       
   888 
       
   889       /* Always close the journal file when dropping the database lock.
       
   890       ** Otherwise, another connection with journal_mode=delete might
       
   891       ** delete the file out from under us.
       
   892       */
       
   893       if( pPager->journalOpen ){
       
   894         sqlite3OsClose(pPager->jfd);
       
   895         pPager->journalOpen = 0;
       
   896         sqlite3BitvecDestroy(pPager->pInJournal);
       
   897         pPager->pInJournal = 0;
       
   898         sqlite3BitvecDestroy(pPager->pAlwaysRollback);
       
   899         pPager->pAlwaysRollback = 0;
       
   900       }
       
   901 
       
   902       /* If Pager.errCode is set, the contents of the pager cache cannot be
       
   903       ** trusted. Now that the pager file is unlocked, the contents of the
       
   904       ** cache can be discarded and the error code safely cleared.
       
   905       */
       
   906       if( pPager->errCode ){
       
   907         if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
       
   908         pager_reset(pPager);
       
   909         if( pPager->stmtOpen ){
       
   910           sqlite3OsClose(pPager->stfd);
       
   911           sqlite3BitvecDestroy(pPager->pInStmt);
       
   912           pPager->pInStmt = 0;
       
   913         }
       
   914         pPager->stmtOpen = 0;
       
   915         pPager->stmtInUse = 0;
       
   916         pPager->journalOff = 0;
       
   917         pPager->journalStarted = 0;
       
   918         pPager->stmtAutoopen = 0;
       
   919         pPager->origDbSize = 0;
       
   920       }
       
   921     }
       
   922 
       
   923     if( !MEMDB || pPager->errCode==SQLITE_OK ){
       
   924       pPager->state = PAGER_UNLOCK;
       
   925       pPager->changeCountDone = 0;
       
   926     }
       
   927   }
       
   928 }
       
   929 
       
   930 /*
       
   931 ** Execute a rollback if a transaction is active and unlock the 
       
   932 ** database file. If the pager has already entered the error state, 
       
   933 ** do not attempt the rollback.
       
   934 */
       
   935 static void pagerUnlockAndRollback(Pager *p){
       
   936   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
       
   937     sqlite3BeginBenignMalloc();
       
   938     sqlite3PagerRollback(p);
       
   939     sqlite3EndBenignMalloc();
       
   940   }
       
   941   pager_unlock(p);
       
   942 }
       
   943 
       
   944 /*
       
   945 ** This routine ends a transaction.  A transaction is ended by either
       
   946 ** a COMMIT or a ROLLBACK.
       
   947 **
       
   948 ** When this routine is called, the pager has the journal file open and
       
   949 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
       
   950 ** the database lock and acquires a SHARED lock in its place if that is
       
   951 ** the appropriate thing to do.  Release locks usually is appropriate,
       
   952 ** unless we are in exclusive access mode or unless this is a 
       
   953 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
       
   954 **
       
   955 ** The journal file is either deleted or truncated.
       
   956 **
       
   957 ** TODO: Consider keeping the journal file open for temporary databases.
       
   958 ** This might give a performance improvement on windows where opening
       
   959 ** a file is an expensive operation.
       
   960 */
       
   961 static int pager_end_transaction(Pager *pPager, int hasMaster){
       
   962   int rc = SQLITE_OK;
       
   963   int rc2 = SQLITE_OK;
       
   964   assert( !MEMDB );
       
   965   if( pPager->state<PAGER_RESERVED ){
       
   966     return SQLITE_OK;
       
   967   }
       
   968   sqlite3PagerStmtCommit(pPager);
       
   969   if( pPager->stmtOpen && !pPager->exclusiveMode ){
       
   970     sqlite3OsClose(pPager->stfd);
       
   971     pPager->stmtOpen = 0;
       
   972   }
       
   973   if( pPager->journalOpen ){
       
   974     if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE
       
   975          && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){
       
   976       pPager->journalOff = 0;
       
   977       pPager->journalStarted = 0;
       
   978     }else if( pPager->exclusiveMode 
       
   979      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
       
   980     ){
       
   981       rc = zeroJournalHdr(pPager, hasMaster);
       
   982       pager_error(pPager, rc);
       
   983       pPager->journalOff = 0;
       
   984       pPager->journalStarted = 0;
       
   985     }else{
       
   986       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
       
   987       sqlite3OsClose(pPager->jfd);
       
   988       pPager->journalOpen = 0;
       
   989       if( rc==SQLITE_OK && !pPager->tempFile ){
       
   990         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
       
   991       }
       
   992     }
       
   993     sqlite3BitvecDestroy(pPager->pInJournal);
       
   994     pPager->pInJournal = 0;
       
   995     sqlite3BitvecDestroy(pPager->pAlwaysRollback);
       
   996     pPager->pAlwaysRollback = 0;
       
   997     sqlite3PcacheCleanAll(pPager->pPCache);
       
   998 #ifdef SQLITE_CHECK_PAGES
       
   999     sqlite3PcacheIterate(pPager->pPCache, pager_set_pagehash);
       
  1000 #endif
       
  1001     sqlite3PcacheClearFlags(pPager->pPCache,
       
  1002        PGHDR_IN_JOURNAL | PGHDR_NEED_SYNC
       
  1003     );
       
  1004     pPager->dirtyCache = 0;
       
  1005     pPager->nRec = 0;
       
  1006   }else{
       
  1007     assert( pPager->pInJournal==0 );
       
  1008   }
       
  1009 
       
  1010   if( !pPager->exclusiveMode ){
       
  1011     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
       
  1012     pPager->state = PAGER_SHARED;
       
  1013   }else if( pPager->state==PAGER_SYNCED ){
       
  1014     pPager->state = PAGER_EXCLUSIVE;
       
  1015   }
       
  1016   pPager->origDbSize = 0;
       
  1017   pPager->setMaster = 0;
       
  1018   pPager->needSync = 0;
       
  1019   /* lruListSetFirstSynced(pPager); */
       
  1020   pPager->dbSize = -1;
       
  1021   pPager->dbModified = 0;
       
  1022 
       
  1023   return (rc==SQLITE_OK?rc2:rc);
       
  1024 }
       
  1025 
       
  1026 /*
       
  1027 ** Compute and return a checksum for the page of data.
       
  1028 **
       
  1029 ** This is not a real checksum.  It is really just the sum of the 
       
  1030 ** random initial value and the page number.  We experimented with
       
  1031 ** a checksum of the entire data, but that was found to be too slow.
       
  1032 **
       
  1033 ** Note that the page number is stored at the beginning of data and
       
  1034 ** the checksum is stored at the end.  This is important.  If journal
       
  1035 ** corruption occurs due to a power failure, the most likely scenario
       
  1036 ** is that one end or the other of the record will be changed.  It is
       
  1037 ** much less likely that the two ends of the journal record will be
       
  1038 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
       
  1039 ** though fast and simple, catches the mostly likely kind of corruption.
       
  1040 **
       
  1041 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
       
  1042 ** checksum.  That way if a single page spans 3 or more disk sectors and
       
  1043 ** only the middle sector is corrupt, we will still have a reasonable
       
  1044 ** chance of failing the checksum and thus detecting the problem.
       
  1045 */
       
  1046 static u32 pager_cksum(Pager *pPager, const u8 *aData){
       
  1047   u32 cksum = pPager->cksumInit;
       
  1048   int i = pPager->pageSize-200;
       
  1049   while( i>0 ){
       
  1050     cksum += aData[i];
       
  1051     i -= 200;
       
  1052   }
       
  1053   return cksum;
       
  1054 }
       
  1055 
       
  1056 /* Forward declaration */
       
  1057 static void makeClean(PgHdr*);
       
  1058 
       
  1059 /*
       
  1060 ** Read a single page from the journal file opened on file descriptor
       
  1061 ** jfd.  Playback this one page.
       
  1062 **
       
  1063 ** The isMainJrnl flag is true if this is the main rollback journal and
       
  1064 ** false for the statement journal.  The main rollback journal uses
       
  1065 ** checksums - the statement journal does not.
       
  1066 */
       
  1067 static int pager_playback_one_page(
       
  1068   Pager *pPager,       /* The pager being played back */
       
  1069   sqlite3_file *jfd,   /* The file that is the journal being rolled back */
       
  1070   i64 offset,          /* Offset of the page within the journal */
       
  1071   int isMainJrnl       /* True for main rollback journal. False for Stmt jrnl */
       
  1072 ){
       
  1073   int rc;
       
  1074   PgHdr *pPg;                   /* An existing page in the cache */
       
  1075   Pgno pgno;                    /* The page number of a page in journal */
       
  1076   u32 cksum;                    /* Checksum used for sanity checking */
       
  1077   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
       
  1078 
       
  1079   /* isMainJrnl should be true for the main journal and false for
       
  1080   ** statement journals.  Verify that this is always the case
       
  1081   */
       
  1082   assert( jfd == (isMainJrnl ? pPager->jfd : pPager->stfd) );
       
  1083   assert( aData );
       
  1084 
       
  1085   rc = read32bits(jfd, offset, &pgno);
       
  1086   if( rc!=SQLITE_OK ) return rc;
       
  1087   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
       
  1088   if( rc!=SQLITE_OK ) return rc;
       
  1089   pPager->journalOff += pPager->pageSize + 4;
       
  1090 
       
  1091   /* Sanity checking on the page.  This is more important that I originally
       
  1092   ** thought.  If a power failure occurs while the journal is being written,
       
  1093   ** it could cause invalid data to be written into the journal.  We need to
       
  1094   ** detect this invalid data (with high probability) and ignore it.
       
  1095   */
       
  1096   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
       
  1097     return SQLITE_DONE;
       
  1098   }
       
  1099   if( pgno>(unsigned)pPager->dbSize ){
       
  1100     return SQLITE_OK;
       
  1101   }
       
  1102   if( isMainJrnl ){
       
  1103     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
       
  1104     if( rc ) return rc;
       
  1105     pPager->journalOff += 4;
       
  1106     if( pager_cksum(pPager, aData)!=cksum ){
       
  1107       return SQLITE_DONE;
       
  1108     }
       
  1109   }
       
  1110 
       
  1111   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
       
  1112 
       
  1113   /* If the pager is in RESERVED state, then there must be a copy of this
       
  1114   ** page in the pager cache. In this case just update the pager cache,
       
  1115   ** not the database file. The page is left marked dirty in this case.
       
  1116   **
       
  1117   ** An exception to the above rule: If the database is in no-sync mode
       
  1118   ** and a page is moved during an incremental vacuum then the page may
       
  1119   ** not be in the pager cache. Later: if a malloc() or IO error occurs
       
  1120   ** during a Movepage() call, then the page may not be in the cache
       
  1121   ** either. So the condition described in the above paragraph is not
       
  1122   ** assert()able.
       
  1123   **
       
  1124   ** If in EXCLUSIVE state, then we update the pager cache if it exists
       
  1125   ** and the main file. The page is then marked not dirty.
       
  1126   **
       
  1127   ** Ticket #1171:  The statement journal might contain page content that is
       
  1128   ** different from the page content at the start of the transaction.
       
  1129   ** This occurs when a page is changed prior to the start of a statement
       
  1130   ** then changed again within the statement.  When rolling back such a
       
  1131   ** statement we must not write to the original database unless we know
       
  1132   ** for certain that original page contents are synced into the main rollback
       
  1133   ** journal.  Otherwise, a power loss might leave modified data in the
       
  1134   ** database file without an entry in the rollback journal that can
       
  1135   ** restore the database to its original form.  Two conditions must be
       
  1136   ** met before writing to the database files. (1) the database must be
       
  1137   ** locked.  (2) we know that the original page content is fully synced
       
  1138   ** in the main journal either because the page is not in cache or else
       
  1139   ** the page is marked as needSync==0.
       
  1140   **
       
  1141   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
       
  1142   ** is possible to fail a statement on a database that does not yet exist.
       
  1143   ** Do not attempt to write if database file has never been opened.
       
  1144   */
       
  1145   pPg = pager_lookup(pPager, pgno);
       
  1146   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
       
  1147                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
       
  1148   if( (pPager->state>=PAGER_EXCLUSIVE)
       
  1149    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
       
  1150    && (pPager->fd->pMethods)
       
  1151   ){
       
  1152     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
       
  1153     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
       
  1154   }
       
  1155   if( pPg ){
       
  1156     /* No page should ever be explicitly rolled back that is in use, except
       
  1157     ** for page 1 which is held in use in order to keep the lock on the
       
  1158     ** database active. However such a page may be rolled back as a result
       
  1159     ** of an internal error resulting in an automatic call to
       
  1160     ** sqlite3PagerRollback().
       
  1161     */
       
  1162     void *pData;
       
  1163     pData = pPg->pData;
       
  1164     memcpy(pData, aData, pPager->pageSize);
       
  1165     if( pPager->xReiniter ){
       
  1166       pPager->xReiniter(pPg);
       
  1167     }
       
  1168     if( isMainJrnl ) makeClean(pPg);
       
  1169 #ifdef SQLITE_CHECK_PAGES
       
  1170     pPg->pageHash = pager_pagehash(pPg);
       
  1171 #endif
       
  1172     /* If this was page 1, then restore the value of Pager.dbFileVers.
       
  1173     ** Do this before any decoding. */
       
  1174     if( pgno==1 ){
       
  1175       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
       
  1176     }
       
  1177 
       
  1178     /* Decode the page just read from disk */
       
  1179     CODEC1(pPager, pData, pPg->pgno, 3);
       
  1180     sqlite3PcacheRelease(pPg);
       
  1181   }
       
  1182   return rc;
       
  1183 }
       
  1184 
       
  1185 /*
       
  1186 ** Parameter zMaster is the name of a master journal file. A single journal
       
  1187 ** file that referred to the master journal file has just been rolled back.
       
  1188 ** This routine checks if it is possible to delete the master journal file,
       
  1189 ** and does so if it is.
       
  1190 **
       
  1191 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
       
  1192 ** available for use within this function.
       
  1193 **
       
  1194 **
       
  1195 ** The master journal file contains the names of all child journals.
       
  1196 ** To tell if a master journal can be deleted, check to each of the
       
  1197 ** children.  If all children are either missing or do not refer to
       
  1198 ** a different master journal, then this master journal can be deleted.
       
  1199 */
       
  1200 static int pager_delmaster(Pager *pPager, const char *zMaster){
       
  1201   sqlite3_vfs *pVfs = pPager->pVfs;
       
  1202   int rc;
       
  1203   int master_open = 0;
       
  1204   sqlite3_file *pMaster;
       
  1205   sqlite3_file *pJournal;
       
  1206   char *zMasterJournal = 0; /* Contents of master journal file */
       
  1207   i64 nMasterJournal;       /* Size of master journal file */
       
  1208 
       
  1209   /* Open the master journal file exclusively in case some other process
       
  1210   ** is running this routine also. Not that it makes too much difference.
       
  1211   */
       
  1212   pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
       
  1213   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
       
  1214   if( !pMaster ){
       
  1215     rc = SQLITE_NOMEM;
       
  1216   }else{
       
  1217     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
       
  1218     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
       
  1219   }
       
  1220   if( rc!=SQLITE_OK ) goto delmaster_out;
       
  1221   master_open = 1;
       
  1222 
       
  1223   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
       
  1224   if( rc!=SQLITE_OK ) goto delmaster_out;
       
  1225 
       
  1226   if( nMasterJournal>0 ){
       
  1227     char *zJournal;
       
  1228     char *zMasterPtr = 0;
       
  1229     int nMasterPtr = pPager->pVfs->mxPathname+1;
       
  1230 
       
  1231     /* Load the entire master journal file into space obtained from
       
  1232     ** sqlite3_malloc() and pointed to by zMasterJournal. 
       
  1233     */
       
  1234     zMasterJournal = (char *)sqlite3Malloc(nMasterJournal + nMasterPtr);
       
  1235     if( !zMasterJournal ){
       
  1236       rc = SQLITE_NOMEM;
       
  1237       goto delmaster_out;
       
  1238     }
       
  1239     zMasterPtr = &zMasterJournal[nMasterJournal];
       
  1240     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
       
  1241     if( rc!=SQLITE_OK ) goto delmaster_out;
       
  1242 
       
  1243     zJournal = zMasterJournal;
       
  1244     while( (zJournal-zMasterJournal)<nMasterJournal ){
       
  1245       int exists;
       
  1246       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
       
  1247       if( rc!=SQLITE_OK ){
       
  1248         goto delmaster_out;
       
  1249       }
       
  1250       if( exists ){
       
  1251         /* One of the journals pointed to by the master journal exists.
       
  1252         ** Open it and check if it points at the master journal. If
       
  1253         ** so, return without deleting the master journal file.
       
  1254         */
       
  1255         int c;
       
  1256         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
       
  1257         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
       
  1258         if( rc!=SQLITE_OK ){
       
  1259           goto delmaster_out;
       
  1260         }
       
  1261 
       
  1262         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
       
  1263         sqlite3OsClose(pJournal);
       
  1264         if( rc!=SQLITE_OK ){
       
  1265           goto delmaster_out;
       
  1266         }
       
  1267 
       
  1268         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
       
  1269         if( c ){
       
  1270           /* We have a match. Do not delete the master journal file. */
       
  1271           goto delmaster_out;
       
  1272         }
       
  1273       }
       
  1274       zJournal += (strlen(zJournal)+1);
       
  1275     }
       
  1276   }
       
  1277   
       
  1278   rc = sqlite3OsDelete(pVfs, zMaster, 0);
       
  1279 
       
  1280 delmaster_out:
       
  1281   if( zMasterJournal ){
       
  1282     sqlite3_free(zMasterJournal);
       
  1283   }  
       
  1284   if( master_open ){
       
  1285     sqlite3OsClose(pMaster);
       
  1286   }
       
  1287   sqlite3_free(pMaster);
       
  1288   return rc;
       
  1289 }
       
  1290 
       
  1291 
       
  1292 static void pager_truncate_cache(Pager *pPager);
       
  1293 
       
  1294 /*
       
  1295 ** Truncate the main file of the given pager to the number of pages
       
  1296 ** indicated. Also truncate the cached representation of the file.
       
  1297 **
       
  1298 ** Might might be the case that the file on disk is smaller than nPage.
       
  1299 ** This can happen, for example, if we are in the middle of a transaction
       
  1300 ** which has extended the file size and the new pages are still all held
       
  1301 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
       
  1302 ** operating system implementations can get confused if you try to
       
  1303 ** truncate a file to some size that is larger than it currently is,
       
  1304 ** so detect this case and write a single zero byte to the end of the new
       
  1305 ** file instead.
       
  1306 */
       
  1307 static int pager_truncate(Pager *pPager, int nPage){
       
  1308   int rc = SQLITE_OK;
       
  1309   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
       
  1310     i64 currentSize, newSize;
       
  1311     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
       
  1312     newSize = pPager->pageSize*(i64)nPage;
       
  1313     if( rc==SQLITE_OK && currentSize!=newSize ){
       
  1314       if( currentSize>newSize ){
       
  1315         rc = sqlite3OsTruncate(pPager->fd, newSize);
       
  1316       }else{
       
  1317         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
       
  1318       }
       
  1319     }
       
  1320   }
       
  1321   if( rc==SQLITE_OK ){
       
  1322     pPager->dbSize = nPage;
       
  1323     pager_truncate_cache(pPager);
       
  1324   }
       
  1325   return rc;
       
  1326 }
       
  1327 
       
  1328 /*
       
  1329 ** Set the sectorSize for the given pager.
       
  1330 **
       
  1331 ** The sector size is at least as big as the sector size reported
       
  1332 ** by sqlite3OsSectorSize().  The minimum sector size is 512.
       
  1333 */
       
  1334 static void setSectorSize(Pager *pPager){
       
  1335   assert(pPager->fd->pMethods||pPager->tempFile);
       
  1336   if( !pPager->tempFile ){
       
  1337     /* Sector size doesn't matter for temporary files. Also, the file
       
  1338     ** may not have been opened yet, in whcih case the OsSectorSize()
       
  1339     ** call will segfault.
       
  1340     */
       
  1341     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
       
  1342   }
       
  1343   if( pPager->sectorSize<512 ){
       
  1344     pPager->sectorSize = 512;
       
  1345   }
       
  1346 }
       
  1347 
       
  1348 /*
       
  1349 ** Playback the journal and thus restore the database file to
       
  1350 ** the state it was in before we started making changes.  
       
  1351 **
       
  1352 ** The journal file format is as follows: 
       
  1353 **
       
  1354 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
       
  1355 **  (2)  4 byte big-endian integer which is the number of valid page records
       
  1356 **       in the journal.  If this value is 0xffffffff, then compute the
       
  1357 **       number of page records from the journal size.
       
  1358 **  (3)  4 byte big-endian integer which is the initial value for the 
       
  1359 **       sanity checksum.
       
  1360 **  (4)  4 byte integer which is the number of pages to truncate the
       
  1361 **       database to during a rollback.
       
  1362 **  (5)  4 byte big-endian integer which is the sector size.  The header
       
  1363 **       is this many bytes in size.
       
  1364 **  (6)  4 byte big-endian integer which is the page case.
       
  1365 **  (7)  4 byte integer which is the number of bytes in the master journal
       
  1366 **       name.  The value may be zero (indicate that there is no master
       
  1367 **       journal.)
       
  1368 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
       
  1369 **       and might be shorter than the value read from (5).  If the first byte
       
  1370 **       of the name is \000 then there is no master journal.  The master
       
  1371 **       journal name is stored in UTF-8.
       
  1372 **  (9)  Zero or more pages instances, each as follows:
       
  1373 **        +  4 byte page number.
       
  1374 **        +  pPager->pageSize bytes of data.
       
  1375 **        +  4 byte checksum
       
  1376 **
       
  1377 ** When we speak of the journal header, we mean the first 8 items above.
       
  1378 ** Each entry in the journal is an instance of the 9th item.
       
  1379 **
       
  1380 ** Call the value from the second bullet "nRec".  nRec is the number of
       
  1381 ** valid page entries in the journal.  In most cases, you can compute the
       
  1382 ** value of nRec from the size of the journal file.  But if a power
       
  1383 ** failure occurred while the journal was being written, it could be the
       
  1384 ** case that the size of the journal file had already been increased but
       
  1385 ** the extra entries had not yet made it safely to disk.  In such a case,
       
  1386 ** the value of nRec computed from the file size would be too large.  For
       
  1387 ** that reason, we always use the nRec value in the header.
       
  1388 **
       
  1389 ** If the nRec value is 0xffffffff it means that nRec should be computed
       
  1390 ** from the file size.  This value is used when the user selects the
       
  1391 ** no-sync option for the journal.  A power failure could lead to corruption
       
  1392 ** in this case.  But for things like temporary table (which will be
       
  1393 ** deleted when the power is restored) we don't care.  
       
  1394 **
       
  1395 ** If the file opened as the journal file is not a well-formed
       
  1396 ** journal file then all pages up to the first corrupted page are rolled
       
  1397 ** back (or no pages if the journal header is corrupted). The journal file
       
  1398 ** is then deleted and SQLITE_OK returned, just as if no corruption had
       
  1399 ** been encountered.
       
  1400 **
       
  1401 ** If an I/O or malloc() error occurs, the journal-file is not deleted
       
  1402 ** and an error code is returned.
       
  1403 */
       
  1404 static int pager_playback(Pager *pPager, int isHot){
       
  1405   sqlite3_vfs *pVfs = pPager->pVfs;
       
  1406   i64 szJ;                 /* Size of the journal file in bytes */
       
  1407   u32 nRec;                /* Number of Records in the journal */
       
  1408   u32 u;                   /* Unsigned loop counter */
       
  1409   Pgno mxPg = 0;           /* Size of the original file in pages */
       
  1410   int rc;                  /* Result code of a subroutine */
       
  1411   int res = 1;             /* Value returned by sqlite3OsAccess() */
       
  1412   char *zMaster = 0;       /* Name of master journal file if any */
       
  1413 
       
  1414   /* Figure out how many records are in the journal.  Abort early if
       
  1415   ** the journal is empty.
       
  1416   */
       
  1417   assert( pPager->journalOpen );
       
  1418   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
       
  1419   if( rc!=SQLITE_OK || szJ==0 ){
       
  1420     goto end_playback;
       
  1421   }
       
  1422 
       
  1423   /* Read the master journal name from the journal, if it is present.
       
  1424   ** If a master journal file name is specified, but the file is not
       
  1425   ** present on disk, then the journal is not hot and does not need to be
       
  1426   ** played back.
       
  1427   */
       
  1428   zMaster = pPager->pTmpSpace;
       
  1429   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
       
  1430   if( rc==SQLITE_OK && zMaster[0] ){
       
  1431     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
       
  1432   }
       
  1433   zMaster = 0;
       
  1434   if( rc!=SQLITE_OK || !res ){
       
  1435     goto end_playback;
       
  1436   }
       
  1437   pPager->journalOff = 0;
       
  1438 
       
  1439   /* This loop terminates either when the readJournalHdr() call returns
       
  1440   ** SQLITE_DONE or an IO error occurs. */
       
  1441   while( 1 ){
       
  1442 
       
  1443     /* Read the next journal header from the journal file.  If there are
       
  1444     ** not enough bytes left in the journal file for a complete header, or
       
  1445     ** it is corrupted, then a process must of failed while writing it.
       
  1446     ** This indicates nothing more needs to be rolled back.
       
  1447     */
       
  1448     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
       
  1449     if( rc!=SQLITE_OK ){ 
       
  1450       if( rc==SQLITE_DONE ){
       
  1451         rc = SQLITE_OK;
       
  1452       }
       
  1453       goto end_playback;
       
  1454     }
       
  1455 
       
  1456     /* If nRec is 0xffffffff, then this journal was created by a process
       
  1457     ** working in no-sync mode. This means that the rest of the journal
       
  1458     ** file consists of pages, there are no more journal headers. Compute
       
  1459     ** the value of nRec based on this assumption.
       
  1460     */
       
  1461     if( nRec==0xffffffff ){
       
  1462       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
       
  1463       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
       
  1464     }
       
  1465 
       
  1466     /* If nRec is 0 and this rollback is of a transaction created by this
       
  1467     ** process and if this is the final header in the journal, then it means
       
  1468     ** that this part of the journal was being filled but has not yet been
       
  1469     ** synced to disk.  Compute the number of pages based on the remaining
       
  1470     ** size of the file.
       
  1471     **
       
  1472     ** The third term of the test was added to fix ticket #2565.
       
  1473     */
       
  1474     if( nRec==0 && !isHot &&
       
  1475         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
       
  1476       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
       
  1477     }
       
  1478 
       
  1479     /* If this is the first header read from the journal, truncate the
       
  1480     ** database file back to its original size.
       
  1481     */
       
  1482     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
       
  1483       rc = pager_truncate(pPager, mxPg);
       
  1484       if( rc!=SQLITE_OK ){
       
  1485         goto end_playback;
       
  1486       }
       
  1487     }
       
  1488 
       
  1489     /* Copy original pages out of the journal and back into the database file.
       
  1490     */
       
  1491     for(u=0; u<nRec; u++){
       
  1492       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
       
  1493       if( rc!=SQLITE_OK ){
       
  1494         if( rc==SQLITE_DONE ){
       
  1495           rc = SQLITE_OK;
       
  1496           pPager->journalOff = szJ;
       
  1497           break;
       
  1498         }else{
       
  1499           /* If we are unable to rollback, then the database is probably
       
  1500           ** going to end up being corrupt.  It is corrupt to us, anyhow.
       
  1501           ** Perhaps the next process to come along can fix it....
       
  1502           */
       
  1503           rc = SQLITE_CORRUPT_BKPT;
       
  1504           goto end_playback;
       
  1505         }
       
  1506       }
       
  1507     }
       
  1508   }
       
  1509   /*NOTREACHED*/
       
  1510   assert( 0 );
       
  1511 
       
  1512 end_playback:
       
  1513   if( rc==SQLITE_OK ){
       
  1514     zMaster = pPager->pTmpSpace;
       
  1515     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
       
  1516   }
       
  1517   if( rc==SQLITE_OK ){
       
  1518     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
       
  1519   }
       
  1520   if( rc==SQLITE_OK && zMaster[0] ){
       
  1521     /* If there was a master journal and this routine will return success,
       
  1522     ** see if it is possible to delete the master journal.
       
  1523     */
       
  1524     rc = pager_delmaster(pPager, zMaster);
       
  1525   }
       
  1526 
       
  1527   /* The Pager.sectorSize variable may have been updated while rolling
       
  1528   ** back a journal created by a process with a different sector size
       
  1529   ** value. Reset it to the correct value for this process.
       
  1530   */
       
  1531   setSectorSize(pPager);
       
  1532   return rc;
       
  1533 }
       
  1534 
       
  1535 /*
       
  1536 ** Playback the statement journal.
       
  1537 **
       
  1538 ** This is similar to playing back the transaction journal but with
       
  1539 ** a few extra twists.
       
  1540 **
       
  1541 **    (1)  The number of pages in the database file at the start of
       
  1542 **         the statement is stored in pPager->stmtSize, not in the
       
  1543 **         journal file itself.
       
  1544 **
       
  1545 **    (2)  In addition to playing back the statement journal, also
       
  1546 **         playback all pages of the transaction journal beginning
       
  1547 **         at offset pPager->stmtJSize.
       
  1548 */
       
  1549 static int pager_stmt_playback(Pager *pPager){
       
  1550   i64 szJ;                 /* Size of the full journal */
       
  1551   i64 hdrOff;
       
  1552   int nRec;                /* Number of Records */
       
  1553   int i;                   /* Loop counter */
       
  1554   int rc;
       
  1555 
       
  1556   szJ = pPager->journalOff;
       
  1557 
       
  1558   /* Set hdrOff to be the offset just after the end of the last journal
       
  1559   ** page written before the first journal-header for this statement
       
  1560   ** transaction was written, or the end of the file if no journal
       
  1561   ** header was written.
       
  1562   */
       
  1563   hdrOff = pPager->stmtHdrOff;
       
  1564   assert( pPager->fullSync || !hdrOff );
       
  1565   if( !hdrOff ){
       
  1566     hdrOff = szJ;
       
  1567   }
       
  1568   
       
  1569   /* Truncate the database back to its original size.
       
  1570   */
       
  1571   rc = pager_truncate(pPager, pPager->stmtSize);
       
  1572   assert( pPager->state>=PAGER_SHARED );
       
  1573 
       
  1574   /* Figure out how many records are in the statement journal.
       
  1575   */
       
  1576   assert( pPager->stmtInUse && pPager->journalOpen );
       
  1577   nRec = pPager->stmtNRec;
       
  1578   
       
  1579   /* Copy original pages out of the statement journal and back into the
       
  1580   ** database file.  Note that the statement journal omits checksums from
       
  1581   ** each record since power-failure recovery is not important to statement
       
  1582   ** journals.
       
  1583   */
       
  1584   for(i=0; i<nRec; i++){
       
  1585     i64 offset = i*(4+pPager->pageSize);
       
  1586     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
       
  1587     assert( rc!=SQLITE_DONE );
       
  1588     if( rc!=SQLITE_OK ) goto end_stmt_playback;
       
  1589   }
       
  1590 
       
  1591   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
       
  1592   ** was the size of the journal file when this statement was started, so
       
  1593   ** everything after that needs to be rolled back, either into the
       
  1594   ** database, the memory cache, or both.
       
  1595   **
       
  1596   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
       
  1597   ** of the first journal header written during this statement transaction.
       
  1598   */
       
  1599   pPager->journalOff = pPager->stmtJSize;
       
  1600   pPager->cksumInit = pPager->stmtCksum;
       
  1601   while( pPager->journalOff < hdrOff ){
       
  1602     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
       
  1603     assert( rc!=SQLITE_DONE );
       
  1604     if( rc!=SQLITE_OK ) goto end_stmt_playback;
       
  1605   }
       
  1606 
       
  1607   while( pPager->journalOff < szJ ){
       
  1608     u32 nJRec;         /* Number of Journal Records */
       
  1609     u32 dummy;
       
  1610     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
       
  1611     if( rc!=SQLITE_OK ){
       
  1612       assert( rc!=SQLITE_DONE );
       
  1613       goto end_stmt_playback;
       
  1614     }
       
  1615     if( nJRec==0 ){
       
  1616       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
       
  1617     }
       
  1618     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
       
  1619       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
       
  1620       assert( rc!=SQLITE_DONE );
       
  1621       if( rc!=SQLITE_OK ) goto end_stmt_playback;
       
  1622     }
       
  1623   }
       
  1624 
       
  1625   pPager->journalOff = szJ;
       
  1626   
       
  1627 end_stmt_playback:
       
  1628   if( rc==SQLITE_OK) {
       
  1629     pPager->journalOff = szJ;
       
  1630     /* pager_reload_cache(pPager); */
       
  1631   }
       
  1632   return rc;
       
  1633 }
       
  1634 
       
  1635 /*
       
  1636 ** Change the maximum number of in-memory pages that are allowed.
       
  1637 */
       
  1638 void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
       
  1639   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
       
  1640 }
       
  1641 
       
  1642 /*
       
  1643 ** Adjust the robustness of the database to damage due to OS crashes
       
  1644 ** or power failures by changing the number of syncs()s when writing
       
  1645 ** the rollback journal.  There are three levels:
       
  1646 **
       
  1647 **    OFF       sqlite3OsSync() is never called.  This is the default
       
  1648 **              for temporary and transient files.
       
  1649 **
       
  1650 **    NORMAL    The journal is synced once before writes begin on the
       
  1651 **              database.  This is normally adequate protection, but
       
  1652 **              it is theoretically possible, though very unlikely,
       
  1653 **              that an inopertune power failure could leave the journal
       
  1654 **              in a state which would cause damage to the database
       
  1655 **              when it is rolled back.
       
  1656 **
       
  1657 **    FULL      The journal is synced twice before writes begin on the
       
  1658 **              database (with some additional information - the nRec field
       
  1659 **              of the journal header - being written in between the two
       
  1660 **              syncs).  If we assume that writing a
       
  1661 **              single disk sector is atomic, then this mode provides
       
  1662 **              assurance that the journal will not be corrupted to the
       
  1663 **              point of causing damage to the database during rollback.
       
  1664 **
       
  1665 ** Numeric values associated with these states are OFF==1, NORMAL=2,
       
  1666 ** and FULL=3.
       
  1667 */
       
  1668 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
       
  1669 void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
       
  1670   pPager->noSync =  level==1 || pPager->tempFile || MEMDB;
       
  1671   pPager->fullSync = level==3 && !pPager->tempFile;
       
  1672   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
       
  1673   if( pPager->noSync ) pPager->needSync = 0;
       
  1674 }
       
  1675 #endif
       
  1676 
       
  1677 /*
       
  1678 ** The following global variable is incremented whenever the library
       
  1679 ** attempts to open a temporary file.  This information is used for
       
  1680 ** testing and analysis only.  
       
  1681 */
       
  1682 #ifdef SQLITE_TEST
       
  1683 int sqlite3_opentemp_count = 0;
       
  1684 #endif
       
  1685 
       
  1686 /*
       
  1687 ** Open a temporary file. 
       
  1688 **
       
  1689 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
       
  1690 ** other error code if we fail. The OS will automatically delete the temporary
       
  1691 ** file when it is closed.
       
  1692 */
       
  1693 static int sqlite3PagerOpentemp(
       
  1694   Pager *pPager,        /* The pager object */
       
  1695   sqlite3_file *pFile,  /* Write the file descriptor here */
       
  1696   int vfsFlags          /* Flags passed through to the VFS */
       
  1697 ){
       
  1698   int rc;
       
  1699 
       
  1700 #ifdef SQLITE_TEST
       
  1701   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
       
  1702 #endif
       
  1703 
       
  1704   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
       
  1705             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
       
  1706   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
       
  1707   assert( rc!=SQLITE_OK || pFile->pMethods );
       
  1708   return rc;
       
  1709 }
       
  1710 
       
  1711 static int pagerStress(void *,PgHdr *);
       
  1712 
       
  1713 /*
       
  1714 ** Create a new page cache and put a pointer to the page cache in *ppPager.
       
  1715 ** The file to be cached need not exist.  The file is not locked until
       
  1716 ** the first call to sqlite3PagerGet() and is only held open until the
       
  1717 ** last page is released using sqlite3PagerUnref().
       
  1718 **
       
  1719 ** If zFilename is NULL then a randomly-named temporary file is created
       
  1720 ** and used as the file to be cached.  The file will be deleted
       
  1721 ** automatically when it is closed.
       
  1722 **
       
  1723 ** If zFilename is ":memory:" then all information is held in cache.
       
  1724 ** It is never written to disk.  This can be used to implement an
       
  1725 ** in-memory database.
       
  1726 */
       
  1727 int sqlite3PagerOpen(
       
  1728   sqlite3_vfs *pVfs,       /* The virtual file system to use */
       
  1729   Pager **ppPager,         /* Return the Pager structure here */
       
  1730   const char *zFilename,   /* Name of the database file to open */
       
  1731   int nExtra,              /* Extra bytes append to each in-memory page */
       
  1732   int flags,               /* flags controlling this file */
       
  1733   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
       
  1734 ){
       
  1735   u8 *pPtr;
       
  1736   Pager *pPager = 0;
       
  1737   int rc = SQLITE_OK;
       
  1738   int i;
       
  1739   int tempFile = 0;
       
  1740   int memDb = 0;
       
  1741   int readOnly = 0;
       
  1742   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
       
  1743   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
       
  1744   int journalFileSize = sqlite3JournalSize(pVfs);
       
  1745   int pcacheSize = sqlite3PcacheSize();
       
  1746   int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
       
  1747   char *zPathname = 0;
       
  1748   int nPathname = 0;
       
  1749 
       
  1750   /* The default return is a NULL pointer */
       
  1751   *ppPager = 0;
       
  1752 
       
  1753   /* Compute and store the full pathname in an allocated buffer pointed
       
  1754   ** to by zPathname, length nPathname. Or, if this is a temporary file,
       
  1755   ** leave both nPathname and zPathname set to 0.
       
  1756   */
       
  1757   if( zFilename && zFilename[0] ){
       
  1758     nPathname = pVfs->mxPathname+1;
       
  1759     zPathname = sqlite3Malloc(nPathname*2);
       
  1760     if( zPathname==0 ){
       
  1761       return SQLITE_NOMEM;
       
  1762     }
       
  1763 #ifndef SQLITE_OMIT_MEMORYDB
       
  1764     if( strcmp(zFilename,":memory:")==0 ){
       
  1765       memDb = 1;
       
  1766       zPathname[0] = 0;
       
  1767       useJournal = 0;
       
  1768     }else
       
  1769 #endif
       
  1770     {
       
  1771       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
       
  1772     }
       
  1773     if( rc!=SQLITE_OK ){
       
  1774       sqlite3_free(zPathname);
       
  1775       return rc;
       
  1776     }
       
  1777     nPathname = strlen(zPathname);
       
  1778   }
       
  1779 
       
  1780   /* Allocate memory for the pager structure */
       
  1781   pPager = sqlite3MallocZero(
       
  1782     sizeof(*pPager) +           /* Pager structure */
       
  1783     pcacheSize      +           /* PCache object */
       
  1784     journalFileSize +           /* The journal file structure */ 
       
  1785     pVfs->szOsFile * 3 +        /* The main db and two journal files */ 
       
  1786     3*nPathname + 40            /* zFilename, zDirectory, zJournal */
       
  1787   );
       
  1788   if( !pPager ){
       
  1789     sqlite3_free(zPathname);
       
  1790     return SQLITE_NOMEM;
       
  1791   }
       
  1792   pPager->pPCache = (PCache *)&pPager[1];
       
  1793   pPtr = ((u8 *)&pPager[1]) + pcacheSize;
       
  1794   pPager->vfsFlags = vfsFlags;
       
  1795   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
       
  1796   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
       
  1797   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
       
  1798   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
       
  1799   pPager->zDirectory = &pPager->zFilename[nPathname+1];
       
  1800   pPager->zJournal = &pPager->zDirectory[nPathname+1];
       
  1801   pPager->pVfs = pVfs;
       
  1802   if( zPathname ){
       
  1803     memcpy(pPager->zFilename, zPathname, nPathname+1);
       
  1804     sqlite3_free(zPathname);
       
  1805   }
       
  1806 
       
  1807   /* Open the pager file.
       
  1808   */
       
  1809   if( zFilename && zFilename[0] && !memDb ){
       
  1810     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
       
  1811       rc = SQLITE_CANTOPEN;
       
  1812     }else{
       
  1813       int fout = 0;
       
  1814       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
       
  1815                          pPager->vfsFlags, &fout);
       
  1816       readOnly = (fout&SQLITE_OPEN_READONLY);
       
  1817 
       
  1818       /* If the file was successfully opened for read/write access,
       
  1819       ** choose a default page size in case we have to create the
       
  1820       ** database file. The default page size is the maximum of:
       
  1821       **
       
  1822       **    + SQLITE_DEFAULT_PAGE_SIZE,
       
  1823       **    + The value returned by sqlite3OsSectorSize()
       
  1824       **    + The largest page size that can be written atomically.
       
  1825       */
       
  1826       if( rc==SQLITE_OK && !readOnly ){
       
  1827         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
       
  1828         if( szPageDflt<iSectorSize ){
       
  1829           szPageDflt = iSectorSize;
       
  1830         }
       
  1831 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
       
  1832         {
       
  1833           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
       
  1834           int ii;
       
  1835           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
       
  1836           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
       
  1837           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
       
  1838           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
       
  1839             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
       
  1840           }
       
  1841         }
       
  1842 #endif
       
  1843         if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
       
  1844           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
       
  1845         }
       
  1846       }
       
  1847     }
       
  1848   }else if( !memDb ){
       
  1849     /* If a temporary file is requested, it is not opened immediately.
       
  1850     ** In this case we accept the default page size and delay actually
       
  1851     ** opening the file until the first call to OsWrite().
       
  1852     */ 
       
  1853     tempFile = 1;
       
  1854     pPager->state = PAGER_EXCLUSIVE;
       
  1855   }
       
  1856 
       
  1857   if( pPager && rc==SQLITE_OK ){
       
  1858     pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
       
  1859   }
       
  1860 
       
  1861   /* If an error occured in either of the blocks above.
       
  1862   ** Free the Pager structure and close the file.
       
  1863   ** Since the pager is not allocated there is no need to set 
       
  1864   ** any Pager.errMask variables.
       
  1865   */
       
  1866   if( !pPager || !pPager->pTmpSpace ){
       
  1867     sqlite3OsClose(pPager->fd);
       
  1868     sqlite3_free(pPager);
       
  1869     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
       
  1870   }
       
  1871   nExtra = FORCE_ALIGNMENT(nExtra);
       
  1872   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
       
  1873                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
       
  1874 
       
  1875   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
       
  1876   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
       
  1877 
       
  1878   /* Fill in Pager.zDirectory[] */
       
  1879   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
       
  1880   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
       
  1881   if( i>0 ) pPager->zDirectory[i-1] = 0;
       
  1882 
       
  1883   /* Fill in Pager.zJournal[] */
       
  1884   if( zPathname ){
       
  1885     memcpy(pPager->zJournal, pPager->zFilename, nPathname);
       
  1886     memcpy(&pPager->zJournal[nPathname], "-journal", 9);
       
  1887   }else{
       
  1888     pPager->zJournal = 0;
       
  1889   }
       
  1890 
       
  1891   /* pPager->journalOpen = 0; */
       
  1892   pPager->useJournal = useJournal;
       
  1893   pPager->noReadlock = noReadlock && readOnly;
       
  1894   /* pPager->stmtOpen = 0; */
       
  1895   /* pPager->stmtInUse = 0; */
       
  1896   /* pPager->nRef = 0; */
       
  1897   pPager->dbSize = memDb-1;
       
  1898   pPager->pageSize = szPageDflt;
       
  1899   /* pPager->stmtSize = 0; */
       
  1900   /* pPager->stmtJSize = 0; */
       
  1901   /* pPager->nPage = 0; */
       
  1902   pPager->mxPage = 100;
       
  1903   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
       
  1904   /* pPager->state = PAGER_UNLOCK; */
       
  1905   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
       
  1906   /* pPager->errMask = 0; */
       
  1907   pPager->tempFile = tempFile;
       
  1908   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
       
  1909           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
       
  1910   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
       
  1911   pPager->exclusiveMode = tempFile; 
       
  1912   pPager->memDb = memDb;
       
  1913   pPager->readOnly = readOnly;
       
  1914   /* pPager->needSync = 0; */
       
  1915   pPager->noSync = pPager->tempFile || !useJournal;
       
  1916   pPager->fullSync = (pPager->noSync?0:1);
       
  1917   pPager->sync_flags = SQLITE_SYNC_NORMAL;
       
  1918   /* pPager->pFirst = 0; */
       
  1919   /* pPager->pFirstSynced = 0; */
       
  1920   /* pPager->pLast = 0; */
       
  1921   pPager->nExtra = nExtra;
       
  1922   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
       
  1923   assert(pPager->fd->pMethods||memDb||tempFile);
       
  1924   if( !memDb ){
       
  1925     setSectorSize(pPager);
       
  1926   }
       
  1927   /* pPager->pBusyHandler = 0; */
       
  1928   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
       
  1929   *ppPager = pPager;
       
  1930   return SQLITE_OK;
       
  1931 }
       
  1932 
       
  1933 /*
       
  1934 ** Set the busy handler function.
       
  1935 */
       
  1936 void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
       
  1937   pPager->pBusyHandler = pBusyHandler;
       
  1938 }
       
  1939 
       
  1940 /*
       
  1941 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
       
  1942 ** is called when the content of a page in cache is restored to its original
       
  1943 ** value as a result of a rollback.  The callback gives higher-level code
       
  1944 ** an opportunity to restore the EXTRA section to agree with the restored
       
  1945 ** page data.
       
  1946 */
       
  1947 void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
       
  1948   pPager->xReiniter = xReinit;
       
  1949 }
       
  1950 
       
  1951 /*
       
  1952 ** Set the page size to *pPageSize. If the suggest new page size is
       
  1953 ** inappropriate, then an alternative page size is set to that
       
  1954 ** value before returning.
       
  1955 */
       
  1956 int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
       
  1957   int rc = pPager->errCode;
       
  1958   if( rc==SQLITE_OK ){
       
  1959     u16 pageSize = *pPageSize;
       
  1960     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
       
  1961     if( pageSize && pageSize!=pPager->pageSize 
       
  1962      && (pPager->memDb==0 || pPager->dbSize==0)
       
  1963      && sqlite3PcacheRefCount(pPager->pPCache)==0 
       
  1964     ){
       
  1965       char *pNew = (char *)sqlite3PageMalloc(pageSize);
       
  1966       if( !pNew ){
       
  1967         rc = SQLITE_NOMEM;
       
  1968       }else{
       
  1969         pager_reset(pPager);
       
  1970         pPager->pageSize = pageSize;
       
  1971         if( !pPager->memDb ) setSectorSize(pPager);
       
  1972         sqlite3PageFree(pPager->pTmpSpace);
       
  1973         pPager->pTmpSpace = pNew;
       
  1974         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
       
  1975       }
       
  1976     }
       
  1977     *pPageSize = pPager->pageSize;
       
  1978   }
       
  1979   return rc;
       
  1980 }
       
  1981 
       
  1982 /*
       
  1983 ** Return a pointer to the "temporary page" buffer held internally
       
  1984 ** by the pager.  This is a buffer that is big enough to hold the
       
  1985 ** entire content of a database page.  This buffer is used internally
       
  1986 ** during rollback and will be overwritten whenever a rollback
       
  1987 ** occurs.  But other modules are free to use it too, as long as
       
  1988 ** no rollbacks are happening.
       
  1989 */
       
  1990 void *sqlite3PagerTempSpace(Pager *pPager){
       
  1991   return pPager->pTmpSpace;
       
  1992 }
       
  1993 
       
  1994 /*
       
  1995 ** Attempt to set the maximum database page count if mxPage is positive. 
       
  1996 ** Make no changes if mxPage is zero or negative.  And never reduce the
       
  1997 ** maximum page count below the current size of the database.
       
  1998 **
       
  1999 ** Regardless of mxPage, return the current maximum page count.
       
  2000 */
       
  2001 int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
       
  2002   if( mxPage>0 ){
       
  2003     pPager->mxPgno = mxPage;
       
  2004   }
       
  2005   sqlite3PagerPagecount(pPager, 0);
       
  2006   return pPager->mxPgno;
       
  2007 }
       
  2008 
       
  2009 /*
       
  2010 ** The following set of routines are used to disable the simulated
       
  2011 ** I/O error mechanism.  These routines are used to avoid simulated
       
  2012 ** errors in places where we do not care about errors.
       
  2013 **
       
  2014 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
       
  2015 ** and generate no code.
       
  2016 */
       
  2017 #ifdef SQLITE_TEST
       
  2018 extern int sqlite3_io_error_pending;
       
  2019 extern int sqlite3_io_error_hit;
       
  2020 static int saved_cnt;
       
  2021 void disable_simulated_io_errors(void){
       
  2022   saved_cnt = sqlite3_io_error_pending;
       
  2023   sqlite3_io_error_pending = -1;
       
  2024 }
       
  2025 void enable_simulated_io_errors(void){
       
  2026   sqlite3_io_error_pending = saved_cnt;
       
  2027 }
       
  2028 #else
       
  2029 # define disable_simulated_io_errors()
       
  2030 # define enable_simulated_io_errors()
       
  2031 #endif
       
  2032 
       
  2033 /*
       
  2034 ** Read the first N bytes from the beginning of the file into memory
       
  2035 ** that pDest points to. 
       
  2036 **
       
  2037 ** No error checking is done. The rational for this is that this function 
       
  2038 ** may be called even if the file does not exist or contain a header. In 
       
  2039 ** these cases sqlite3OsRead() will return an error, to which the correct 
       
  2040 ** response is to zero the memory at pDest and continue.  A real IO error 
       
  2041 ** will presumably recur and be picked up later (Todo: Think about this).
       
  2042 */
       
  2043 int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
       
  2044   int rc = SQLITE_OK;
       
  2045   memset(pDest, 0, N);
       
  2046   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
       
  2047   if( pPager->fd->pMethods ){
       
  2048     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
       
  2049     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
       
  2050     if( rc==SQLITE_IOERR_SHORT_READ ){
       
  2051       rc = SQLITE_OK;
       
  2052     }
       
  2053   }
       
  2054   return rc;
       
  2055 }
       
  2056 
       
  2057 /*
       
  2058 ** Return the total number of pages in the disk file associated with
       
  2059 ** pPager. 
       
  2060 **
       
  2061 ** If the PENDING_BYTE lies on the page directly after the end of the
       
  2062 ** file, then consider this page part of the file too. For example, if
       
  2063 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
       
  2064 ** file is 4096 bytes, 5 is returned instead of 4.
       
  2065 */
       
  2066 int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
       
  2067   i64 n = 0;
       
  2068   int rc;
       
  2069   assert( pPager!=0 );
       
  2070   if( pPager->errCode ){
       
  2071     rc = pPager->errCode;
       
  2072     return rc;
       
  2073   }
       
  2074   if( pPager->dbSize>=0 ){
       
  2075     n = pPager->dbSize;
       
  2076   } else {
       
  2077     assert(pPager->fd->pMethods||pPager->tempFile);
       
  2078     if( (pPager->fd->pMethods)
       
  2079      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
       
  2080       pager_error(pPager, rc);
       
  2081       return rc;
       
  2082     }
       
  2083     if( n>0 && n<pPager->pageSize ){
       
  2084       n = 1;
       
  2085     }else{
       
  2086       n /= pPager->pageSize;
       
  2087     }
       
  2088     if( pPager->state!=PAGER_UNLOCK ){
       
  2089       pPager->dbSize = n;
       
  2090     }
       
  2091   }
       
  2092   if( n==(PENDING_BYTE/pPager->pageSize) ){
       
  2093     n++;
       
  2094   }
       
  2095   if( n>pPager->mxPgno ){
       
  2096     pPager->mxPgno = n;
       
  2097   }
       
  2098   if( pnPage ){
       
  2099     *pnPage = n;
       
  2100   }
       
  2101   return SQLITE_OK;
       
  2102 }
       
  2103 
       
  2104 /*
       
  2105 ** Forward declaration
       
  2106 */
       
  2107 static int syncJournal(Pager*);
       
  2108 
       
  2109 /*
       
  2110 ** This routine is used to truncate the cache when a database
       
  2111 ** is truncated.  Drop from the cache all pages whose pgno is
       
  2112 ** larger than pPager->dbSize and is unreferenced.
       
  2113 **
       
  2114 ** Referenced pages larger than pPager->dbSize are zeroed.
       
  2115 **
       
  2116 ** Actually, at the point this routine is called, it would be
       
  2117 ** an error to have a referenced page.  But rather than delete
       
  2118 ** that page and guarantee a subsequent segfault, it seems better
       
  2119 ** to zero it and hope that we error out sanely.
       
  2120 */
       
  2121 static void pager_truncate_cache(Pager *pPager){
       
  2122   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
       
  2123 }
       
  2124 
       
  2125 /*
       
  2126 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
       
  2127 ** is currently not available.  Repeat until the busy callback returns
       
  2128 ** false or until the lock succeeds.
       
  2129 **
       
  2130 ** Return SQLITE_OK on success and an error code if we cannot obtain
       
  2131 ** the lock.
       
  2132 */
       
  2133 static int pager_wait_on_lock(Pager *pPager, int locktype){
       
  2134   int rc;
       
  2135 
       
  2136   /* The OS lock values must be the same as the Pager lock values */
       
  2137   assert( PAGER_SHARED==SHARED_LOCK );
       
  2138   assert( PAGER_RESERVED==RESERVED_LOCK );
       
  2139   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
       
  2140 
       
  2141   /* If the file is currently unlocked then the size must be unknown */
       
  2142   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
       
  2143 
       
  2144   if( pPager->state>=locktype ){
       
  2145     rc = SQLITE_OK;
       
  2146   }else{
       
  2147     if( pPager->pBusyHandler ) pPager->pBusyHandler->nBusy = 0;
       
  2148     do {
       
  2149       rc = sqlite3OsLock(pPager->fd, locktype);
       
  2150     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
       
  2151     if( rc==SQLITE_OK ){
       
  2152       pPager->state = locktype;
       
  2153       IOTRACE(("LOCK %p %d\n", pPager, locktype))
       
  2154     }
       
  2155   }
       
  2156   return rc;
       
  2157 }
       
  2158 
       
  2159 /*
       
  2160 ** Truncate the file to the number of pages specified.
       
  2161 */
       
  2162 int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
       
  2163   int rc = SQLITE_OK;
       
  2164   assert( pPager->state>=PAGER_SHARED || MEMDB );
       
  2165 
       
  2166 
       
  2167   sqlite3PagerPagecount(pPager, 0);
       
  2168   if( pPager->errCode ){
       
  2169     rc = pPager->errCode;
       
  2170   }else if( nPage<(unsigned)pPager->dbSize ){
       
  2171     if( MEMDB ){
       
  2172       pPager->dbSize = nPage;
       
  2173       pager_truncate_cache(pPager);
       
  2174     }else{
       
  2175       rc = syncJournal(pPager);
       
  2176       if( rc==SQLITE_OK ){
       
  2177         /* Get an exclusive lock on the database before truncating. */
       
  2178         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
       
  2179       }
       
  2180       if( rc==SQLITE_OK ){
       
  2181         rc = pager_truncate(pPager, nPage);
       
  2182       }
       
  2183     }
       
  2184   }
       
  2185 
       
  2186   return rc;
       
  2187 }
       
  2188 
       
  2189 /*
       
  2190 ** Shutdown the page cache.  Free all memory and close all files.
       
  2191 **
       
  2192 ** If a transaction was in progress when this routine is called, that
       
  2193 ** transaction is rolled back.  All outstanding pages are invalidated
       
  2194 ** and their memory is freed.  Any attempt to use a page associated
       
  2195 ** with this page cache after this function returns will likely
       
  2196 ** result in a coredump.
       
  2197 **
       
  2198 ** This function always succeeds. If a transaction is active an attempt
       
  2199 ** is made to roll it back. If an error occurs during the rollback 
       
  2200 ** a hot journal may be left in the filesystem but no error is returned
       
  2201 ** to the caller.
       
  2202 */
       
  2203 int sqlite3PagerClose(Pager *pPager){
       
  2204 
       
  2205   disable_simulated_io_errors();
       
  2206   sqlite3BeginBenignMalloc();
       
  2207   pPager->errCode = 0;
       
  2208   pPager->exclusiveMode = 0;
       
  2209   pager_reset(pPager);
       
  2210   pagerUnlockAndRollback(pPager);
       
  2211   enable_simulated_io_errors();
       
  2212   sqlite3EndBenignMalloc();
       
  2213   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
       
  2214   IOTRACE(("CLOSE %p\n", pPager))
       
  2215   if( pPager->journalOpen ){
       
  2216     sqlite3OsClose(pPager->jfd);
       
  2217   }
       
  2218   sqlite3BitvecDestroy(pPager->pInJournal);
       
  2219   sqlite3BitvecDestroy(pPager->pAlwaysRollback);
       
  2220   if( pPager->stmtOpen ){
       
  2221     sqlite3OsClose(pPager->stfd);
       
  2222   }
       
  2223   sqlite3OsClose(pPager->fd);
       
  2224   /* Temp files are automatically deleted by the OS
       
  2225   ** if( pPager->tempFile ){
       
  2226   **   sqlite3OsDelete(pPager->zFilename);
       
  2227   ** }
       
  2228   */
       
  2229 
       
  2230   sqlite3PageFree(pPager->pTmpSpace);
       
  2231   sqlite3PcacheClose(pPager->pPCache);
       
  2232   sqlite3_free(pPager);
       
  2233   return SQLITE_OK;
       
  2234 }
       
  2235 
       
  2236 #if !defined(NDEBUG) || defined(SQLITE_TEST)
       
  2237 /*
       
  2238 ** Return the page number for the given page data.
       
  2239 */
       
  2240 Pgno sqlite3PagerPagenumber(DbPage *p){
       
  2241   return p->pgno;
       
  2242 }
       
  2243 #endif
       
  2244 
       
  2245 /*
       
  2246 ** Increment the reference count for a page.  The input pointer is
       
  2247 ** a reference to the page data.
       
  2248 */
       
  2249 int sqlite3PagerRef(DbPage *pPg){
       
  2250   sqlite3PcacheRef(pPg);
       
  2251   return SQLITE_OK;
       
  2252 }
       
  2253 
       
  2254 /*
       
  2255 ** Sync the journal.  In other words, make sure all the pages that have
       
  2256 ** been written to the journal have actually reached the surface of the
       
  2257 ** disk.  It is not safe to modify the original database file until after
       
  2258 ** the journal has been synced.  If the original database is modified before
       
  2259 ** the journal is synced and a power failure occurs, the unsynced journal
       
  2260 ** data would be lost and we would be unable to completely rollback the
       
  2261 ** database changes.  Database corruption would occur.
       
  2262 ** 
       
  2263 ** This routine also updates the nRec field in the header of the journal.
       
  2264 ** (See comments on the pager_playback() routine for additional information.)
       
  2265 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
       
  2266 ** is synced, then the nRec field is updated, then a second sync occurs.
       
  2267 **
       
  2268 ** For temporary databases, we do not care if we are able to rollback
       
  2269 ** after a power failure, so no sync occurs.
       
  2270 **
       
  2271 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
       
  2272 ** the database is stored, then OsSync() is never called on the journal
       
  2273 ** file. In this case all that is required is to update the nRec field in
       
  2274 ** the journal header.
       
  2275 **
       
  2276 ** This routine clears the needSync field of every page current held in
       
  2277 ** memory.
       
  2278 */
       
  2279 static int syncJournal(Pager *pPager){
       
  2280   int rc = SQLITE_OK;
       
  2281 
       
  2282   /* Sync the journal before modifying the main database
       
  2283   ** (assuming there is a journal and it needs to be synced.)
       
  2284   */
       
  2285   if( pPager->needSync ){
       
  2286     if( !pPager->tempFile ){
       
  2287       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
       
  2288       assert( pPager->journalOpen );
       
  2289 
       
  2290       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
       
  2291         /* Write the nRec value into the journal file header. If in
       
  2292         ** full-synchronous mode, sync the journal first. This ensures that
       
  2293         ** all data has really hit the disk before nRec is updated to mark
       
  2294         ** it as a candidate for rollback.
       
  2295         **
       
  2296         ** This is not required if the persistent media supports the
       
  2297         ** SAFE_APPEND property. Because in this case it is not possible 
       
  2298         ** for garbage data to be appended to the file, the nRec field
       
  2299         ** is populated with 0xFFFFFFFF when the journal header is written
       
  2300         ** and never needs to be updated.
       
  2301         */
       
  2302         i64 jrnlOff;
       
  2303         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
       
  2304           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
       
  2305           IOTRACE(("JSYNC %p\n", pPager))
       
  2306           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
       
  2307           if( rc!=0 ) return rc;
       
  2308         }
       
  2309 
       
  2310         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
       
  2311         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
       
  2312         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
       
  2313         if( rc ) return rc;
       
  2314       }
       
  2315       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
       
  2316         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
       
  2317         IOTRACE(("JSYNC %p\n", pPager))
       
  2318         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
       
  2319           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
       
  2320         );
       
  2321         if( rc!=0 ) return rc;
       
  2322       }
       
  2323       pPager->journalStarted = 1;
       
  2324     }
       
  2325     pPager->needSync = 0;
       
  2326 
       
  2327     /* Erase the needSync flag from every page.
       
  2328     */
       
  2329     sqlite3PcacheClearFlags(pPager->pPCache, PGHDR_NEED_SYNC);
       
  2330   }
       
  2331 
       
  2332 #ifndef NDEBUG
       
  2333   /* If the Pager.needSync flag is clear then the PgHdr.needSync
       
  2334   ** flag must also be clear for all pages.  Verify that this
       
  2335   ** invariant is true.
       
  2336   */
       
  2337   else{
       
  2338     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_NEED_SYNC);
       
  2339   }
       
  2340 #endif
       
  2341 
       
  2342   return rc;
       
  2343 }
       
  2344 
       
  2345 /*
       
  2346 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
       
  2347 ** every one of those pages out to the database file. No calls are made
       
  2348 ** to the page-cache to mark the pages as clean. It is the responsibility
       
  2349 ** of the caller to use PcacheCleanAll() or PcacheMakeClean() to mark
       
  2350 ** the pages as clean.
       
  2351 */
       
  2352 static int pager_write_pagelist(PgHdr *pList){
       
  2353   Pager *pPager;
       
  2354   int rc;
       
  2355 
       
  2356   if( pList==0 ) return SQLITE_OK;
       
  2357   pPager = pList->pPager;
       
  2358 
       
  2359   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
       
  2360   ** database file. If there is already an EXCLUSIVE lock, the following
       
  2361   ** calls to sqlite3OsLock() are no-ops.
       
  2362   **
       
  2363   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
       
  2364   ** through an intermediate state PENDING.   A PENDING lock prevents new
       
  2365   ** readers from attaching to the database but is unsufficient for us to
       
  2366   ** write.  The idea of a PENDING lock is to prevent new readers from
       
  2367   ** coming in while we wait for existing readers to clear.
       
  2368   **
       
  2369   ** While the pager is in the RESERVED state, the original database file
       
  2370   ** is unchanged and we can rollback without having to playback the
       
  2371   ** journal into the original database file.  Once we transition to
       
  2372   ** EXCLUSIVE, it means the database file has been changed and any rollback
       
  2373   ** will require a journal playback.
       
  2374   */
       
  2375   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
       
  2376   if( rc!=SQLITE_OK ){
       
  2377     return rc;
       
  2378   }
       
  2379 
       
  2380   while( pList ){
       
  2381 
       
  2382     /* If the file has not yet been opened, open it now. */
       
  2383     if( !pPager->fd->pMethods ){
       
  2384       assert(pPager->tempFile);
       
  2385       rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
       
  2386       if( rc ) return rc;
       
  2387     }
       
  2388 
       
  2389     /* If there are dirty pages in the page cache with page numbers greater
       
  2390     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
       
  2391     ** make the file smaller (presumably by auto-vacuum code). Do not write
       
  2392     ** any such pages to the file.
       
  2393     */
       
  2394     if( pList->pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
       
  2395       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
       
  2396       char *pData = CODEC2(pPager, pList->pData, pList->pgno, 6);
       
  2397       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
       
  2398                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
       
  2399       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
       
  2400       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
       
  2401       PAGER_INCR(sqlite3_pager_writedb_count);
       
  2402       PAGER_INCR(pPager->nWrite);
       
  2403       if( pList->pgno==1 ){
       
  2404         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
       
  2405       }
       
  2406     }
       
  2407 #ifndef NDEBUG
       
  2408     else{
       
  2409       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
       
  2410     }
       
  2411 #endif
       
  2412     if( rc ) return rc;
       
  2413 #ifdef SQLITE_CHECK_PAGES
       
  2414     pList->pageHash = pager_pagehash(pList);
       
  2415 #endif
       
  2416     pList = pList->pDirty;
       
  2417   }
       
  2418 
       
  2419   return SQLITE_OK;
       
  2420 }
       
  2421 
       
  2422 /*
       
  2423 ** This function is called by the pcache layer when it has reached some
       
  2424 ** soft memory limit. The argument is a pointer to a purgeable Pager 
       
  2425 ** object. This function attempts to make a single dirty page that has no
       
  2426 ** outstanding references (if one exists) clean so that it can be recycled 
       
  2427 ** by the pcache layer.
       
  2428 */
       
  2429 static int pagerStress(void *p, PgHdr *pPg){
       
  2430   Pager *pPager = (Pager *)p;
       
  2431   int rc = SQLITE_OK;
       
  2432 
       
  2433   if( pPager->doNotSync ){
       
  2434     return SQLITE_OK;
       
  2435   }
       
  2436 
       
  2437   assert( pPg->flags&PGHDR_DIRTY );
       
  2438   if( pPager->errCode==SQLITE_OK ){
       
  2439     if( pPg->flags&PGHDR_NEED_SYNC ){
       
  2440       rc = syncJournal(pPager);
       
  2441       if( rc==SQLITE_OK && pPager->fullSync && 
       
  2442         !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
       
  2443       ){
       
  2444         pPager->nRec = 0;
       
  2445         rc = writeJournalHdr(pPager);
       
  2446       }
       
  2447     }
       
  2448     if( rc==SQLITE_OK ){
       
  2449       pPg->pDirty = 0;
       
  2450       rc = pager_write_pagelist(pPg);
       
  2451     }
       
  2452     if( rc!=SQLITE_OK ){
       
  2453       pager_error(pPager, rc);
       
  2454     }
       
  2455   }
       
  2456 
       
  2457   if( rc==SQLITE_OK ){
       
  2458     sqlite3PcacheMakeClean(pPg);
       
  2459   }
       
  2460   return rc;
       
  2461 }
       
  2462 
       
  2463 
       
  2464 /*
       
  2465 ** Return 1 if there is a hot journal on the given pager.
       
  2466 ** A hot journal is one that needs to be played back.
       
  2467 **
       
  2468 ** If the current size of the database file is 0 but a journal file
       
  2469 ** exists, that is probably an old journal left over from a prior
       
  2470 ** database with the same name.  Just delete the journal.
       
  2471 **
       
  2472 ** Return negative if unable to determine the status of the journal.
       
  2473 **
       
  2474 ** This routine does not open the journal file to examine its
       
  2475 ** content.  Hence, the journal might contain the name of a master
       
  2476 ** journal file that has been deleted, and hence not be hot.  Or
       
  2477 ** the header of the journal might be zeroed out.  This routine
       
  2478 ** does not discover these cases of a non-hot journal - if the
       
  2479 ** journal file exists and is not empty this routine assumes it
       
  2480 ** is hot.  The pager_playback() routine will discover that the
       
  2481 ** journal file is not really hot and will no-op.
       
  2482 */
       
  2483 static int hasHotJournal(Pager *pPager, int *pExists){
       
  2484   sqlite3_vfs *pVfs = pPager->pVfs;
       
  2485   int rc = SQLITE_OK;
       
  2486   int exists;
       
  2487   int locked;
       
  2488   assert( pPager!=0 );
       
  2489   assert( pPager->useJournal );
       
  2490   assert( pPager->fd->pMethods );
       
  2491   *pExists = 0;
       
  2492   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
       
  2493   if( rc==SQLITE_OK && exists ){
       
  2494     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
       
  2495   }
       
  2496   if( rc==SQLITE_OK && exists && !locked ){
       
  2497     int nPage;
       
  2498     rc = sqlite3PagerPagecount(pPager, &nPage);
       
  2499     if( rc==SQLITE_OK ){
       
  2500      if( nPage==0 ){
       
  2501         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
       
  2502       }else{
       
  2503         *pExists = 1;
       
  2504       }
       
  2505     }
       
  2506   }
       
  2507   return rc;
       
  2508 }
       
  2509 
       
  2510 /*
       
  2511 ** Read the content of page pPg out of the database file.
       
  2512 */
       
  2513 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
       
  2514   int rc;
       
  2515   i64 offset;
       
  2516   assert( MEMDB==0 );
       
  2517   assert(pPager->fd->pMethods||pPager->tempFile);
       
  2518   if( !pPager->fd->pMethods ){
       
  2519     return SQLITE_IOERR_SHORT_READ;
       
  2520   }
       
  2521   offset = (pgno-1)*(i64)pPager->pageSize;
       
  2522   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, offset);
       
  2523   PAGER_INCR(sqlite3_pager_readdb_count);
       
  2524   PAGER_INCR(pPager->nRead);
       
  2525   IOTRACE(("PGIN %p %d\n", pPager, pgno));
       
  2526   if( pgno==1 ){
       
  2527     memcpy(&pPager->dbFileVers, &((u8*)pPg->pData)[24],
       
  2528                                               sizeof(pPager->dbFileVers));
       
  2529   }
       
  2530   CODEC1(pPager, pPg->pData, pPg->pgno, 3);
       
  2531   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
       
  2532                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
       
  2533   return rc;
       
  2534 }
       
  2535 
       
  2536 
       
  2537 /*
       
  2538 ** This function is called to obtain the shared lock required before
       
  2539 ** data may be read from the pager cache. If the shared lock has already
       
  2540 ** been obtained, this function is a no-op.
       
  2541 **
       
  2542 ** Immediately after obtaining the shared lock (if required), this function
       
  2543 ** checks for a hot-journal file. If one is found, an emergency rollback
       
  2544 ** is performed immediately.
       
  2545 */
       
  2546 static int pagerSharedLock(Pager *pPager){
       
  2547   int rc = SQLITE_OK;
       
  2548   int isErrorReset = 0;
       
  2549 
       
  2550   /* If this database is opened for exclusive access, has no outstanding 
       
  2551   ** page references and is in an error-state, now is the chance to clear
       
  2552   ** the error. Discard the contents of the pager-cache and treat any
       
  2553   ** open journal file as a hot-journal.
       
  2554   */
       
  2555   if( !MEMDB && pPager->exclusiveMode 
       
  2556    && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
       
  2557   ){
       
  2558     if( pPager->journalOpen ){
       
  2559       isErrorReset = 1;
       
  2560     }
       
  2561     pPager->errCode = SQLITE_OK;
       
  2562     pager_reset(pPager);
       
  2563   }
       
  2564 
       
  2565   /* If the pager is still in an error state, do not proceed. The error 
       
  2566   ** state will be cleared at some point in the future when all page 
       
  2567   ** references are dropped and the cache can be discarded.
       
  2568   */
       
  2569   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
       
  2570     return pPager->errCode;
       
  2571   }
       
  2572 
       
  2573   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
       
  2574     sqlite3_vfs *pVfs = pPager->pVfs;
       
  2575     if( !MEMDB ){
       
  2576       int isHotJournal;
       
  2577       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
       
  2578       if( !pPager->noReadlock ){
       
  2579         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
       
  2580         if( rc!=SQLITE_OK ){
       
  2581           assert( pPager->state==PAGER_UNLOCK );
       
  2582           return pager_error(pPager, rc);
       
  2583         }
       
  2584         assert( pPager->state>=SHARED_LOCK );
       
  2585       }
       
  2586   
       
  2587       /* If a journal file exists, and there is no RESERVED lock on the
       
  2588       ** database file, then it either needs to be played back or deleted.
       
  2589       */
       
  2590       if( !isErrorReset ){
       
  2591         rc = hasHotJournal(pPager, &isHotJournal);
       
  2592         if( rc!=SQLITE_OK ){
       
  2593           goto failed;
       
  2594         }
       
  2595       }
       
  2596       if( isErrorReset || isHotJournal ){
       
  2597         /* Get an EXCLUSIVE lock on the database file. At this point it is
       
  2598         ** important that a RESERVED lock is not obtained on the way to the
       
  2599         ** EXCLUSIVE lock. If it were, another process might open the
       
  2600         ** database file, detect the RESERVED lock, and conclude that the
       
  2601         ** database is safe to read while this process is still rolling it 
       
  2602         ** back.
       
  2603         ** 
       
  2604         ** Because the intermediate RESERVED lock is not requested, the
       
  2605         ** second process will get to this point in the code and fail to
       
  2606         ** obtain its own EXCLUSIVE lock on the database file.
       
  2607         */
       
  2608         if( pPager->state<EXCLUSIVE_LOCK ){
       
  2609           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
       
  2610           if( rc!=SQLITE_OK ){
       
  2611             rc = pager_error(pPager, rc);
       
  2612             goto failed;
       
  2613           }
       
  2614           pPager->state = PAGER_EXCLUSIVE;
       
  2615         }
       
  2616  
       
  2617         /* Open the journal for read/write access. This is because in 
       
  2618         ** exclusive-access mode the file descriptor will be kept open and
       
  2619         ** possibly used for a transaction later on. On some systems, the
       
  2620         ** OsTruncate() call used in exclusive-access mode also requires
       
  2621         ** a read/write file handle.
       
  2622         */
       
  2623         if( !isErrorReset && pPager->journalOpen==0 ){
       
  2624           int res;
       
  2625           rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
       
  2626           if( rc==SQLITE_OK ){
       
  2627             if( res ){
       
  2628               int fout = 0;
       
  2629               int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
       
  2630               assert( !pPager->tempFile );
       
  2631               rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
       
  2632               assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
       
  2633               if( fout&SQLITE_OPEN_READONLY ){
       
  2634                 rc = SQLITE_BUSY;
       
  2635                 sqlite3OsClose(pPager->jfd);
       
  2636               }
       
  2637             }else{
       
  2638               /* If the journal does not exist, that means some other process
       
  2639               ** has already rolled it back */
       
  2640               rc = SQLITE_BUSY;
       
  2641             }
       
  2642           }
       
  2643         }
       
  2644         if( rc!=SQLITE_OK ){
       
  2645           if( rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_UNLOCK 
       
  2646            && rc!=SQLITE_IOERR_NOMEM 
       
  2647           ){
       
  2648             rc = SQLITE_BUSY;
       
  2649           }
       
  2650           goto failed;
       
  2651         }
       
  2652         pPager->journalOpen = 1;
       
  2653         pPager->journalStarted = 0;
       
  2654         pPager->journalOff = 0;
       
  2655         pPager->setMaster = 0;
       
  2656         pPager->journalHdr = 0;
       
  2657  
       
  2658         /* Playback and delete the journal.  Drop the database write
       
  2659         ** lock and reacquire the read lock.
       
  2660         */
       
  2661         rc = pager_playback(pPager, 1);
       
  2662         if( rc!=SQLITE_OK ){
       
  2663           rc = pager_error(pPager, rc);
       
  2664           goto failed;
       
  2665         }
       
  2666         assert(pPager->state==PAGER_SHARED || 
       
  2667             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
       
  2668         );
       
  2669       }
       
  2670 
       
  2671       if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
       
  2672         /* The shared-lock has just been acquired on the database file
       
  2673         ** and there are already pages in the cache (from a previous
       
  2674         ** read or write transaction).  Check to see if the database
       
  2675         ** has been modified.  If the database has changed, flush the
       
  2676         ** cache.
       
  2677         **
       
  2678         ** Database changes is detected by looking at 15 bytes beginning
       
  2679         ** at offset 24 into the file.  The first 4 of these 16 bytes are
       
  2680         ** a 32-bit counter that is incremented with each change.  The
       
  2681         ** other bytes change randomly with each file change when
       
  2682         ** a codec is in use.
       
  2683         ** 
       
  2684         ** There is a vanishingly small chance that a change will not be 
       
  2685         ** detected.  The chance of an undetected change is so small that
       
  2686         ** it can be neglected.
       
  2687         */
       
  2688         char dbFileVers[sizeof(pPager->dbFileVers)];
       
  2689         sqlite3PagerPagecount(pPager, 0);
       
  2690 
       
  2691         if( pPager->errCode ){
       
  2692           rc = pPager->errCode;
       
  2693           goto failed;
       
  2694         }
       
  2695 
       
  2696         if( pPager->dbSize>0 ){
       
  2697           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
       
  2698           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
       
  2699           if( rc!=SQLITE_OK ){
       
  2700             goto failed;
       
  2701           }
       
  2702         }else{
       
  2703           memset(dbFileVers, 0, sizeof(dbFileVers));
       
  2704         }
       
  2705 
       
  2706         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
       
  2707           pager_reset(pPager);
       
  2708         }
       
  2709       }
       
  2710     }
       
  2711     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
       
  2712     if( pPager->state==PAGER_UNLOCK ){
       
  2713       pPager->state = PAGER_SHARED;
       
  2714     }
       
  2715   }
       
  2716 
       
  2717  failed:
       
  2718   if( rc!=SQLITE_OK ){
       
  2719     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
       
  2720     pager_unlock(pPager);
       
  2721   }
       
  2722   return rc;
       
  2723 }
       
  2724 
       
  2725 /*
       
  2726 ** Make sure we have the content for a page.  If the page was
       
  2727 ** previously acquired with noContent==1, then the content was
       
  2728 ** just initialized to zeros instead of being read from disk.
       
  2729 ** But now we need the real data off of disk.  So make sure we
       
  2730 ** have it.  Read it in if we do not have it already.
       
  2731 */
       
  2732 static int pager_get_content(PgHdr *pPg){
       
  2733   if( pPg->flags&PGHDR_NEED_READ ){
       
  2734     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
       
  2735     if( rc==SQLITE_OK ){
       
  2736       pPg->flags &= ~PGHDR_NEED_READ;
       
  2737     }else{
       
  2738       return rc;
       
  2739     }
       
  2740   }
       
  2741   return SQLITE_OK;
       
  2742 }
       
  2743 
       
  2744 /*
       
  2745 ** If the reference count has reached zero, and the pager is not in the
       
  2746 ** middle of a write transaction or opened in exclusive mode, unlock it.
       
  2747 */ 
       
  2748 static void pagerUnlockIfUnused(Pager *pPager){
       
  2749   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
       
  2750     && (!pPager->exclusiveMode || pPager->journalOff>0) 
       
  2751   ){
       
  2752     pagerUnlockAndRollback(pPager);
       
  2753   }
       
  2754 }
       
  2755 
       
  2756 /*
       
  2757 ** Drop a page from the cache using sqlite3PcacheDrop().
       
  2758 **
       
  2759 ** If this means there are now no pages with references to them, a rollback
       
  2760 ** occurs and the lock on the database is removed.
       
  2761 */
       
  2762 static void pagerDropPage(DbPage *pPg){
       
  2763   Pager *pPager = pPg->pPager;
       
  2764   sqlite3PcacheDrop(pPg);
       
  2765   pagerUnlockIfUnused(pPager);
       
  2766 }
       
  2767 
       
  2768 /*
       
  2769 ** Acquire a page.
       
  2770 **
       
  2771 ** A read lock on the disk file is obtained when the first page is acquired. 
       
  2772 ** This read lock is dropped when the last page is released.
       
  2773 **
       
  2774 ** This routine works for any page number greater than 0.  If the database
       
  2775 ** file is smaller than the requested page, then no actual disk
       
  2776 ** read occurs and the memory image of the page is initialized to
       
  2777 ** all zeros.  The extra data appended to a page is always initialized
       
  2778 ** to zeros the first time a page is loaded into memory.
       
  2779 **
       
  2780 ** The acquisition might fail for several reasons.  In all cases,
       
  2781 ** an appropriate error code is returned and *ppPage is set to NULL.
       
  2782 **
       
  2783 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
       
  2784 ** to find a page in the in-memory cache first.  If the page is not already
       
  2785 ** in memory, this routine goes to disk to read it in whereas Lookup()
       
  2786 ** just returns 0.  This routine acquires a read-lock the first time it
       
  2787 ** has to go to disk, and could also playback an old journal if necessary.
       
  2788 ** Since Lookup() never goes to disk, it never has to deal with locks
       
  2789 ** or journal files.
       
  2790 **
       
  2791 ** If noContent is false, the page contents are actually read from disk.
       
  2792 ** If noContent is true, it means that we do not care about the contents
       
  2793 ** of the page at this time, so do not do a disk read.  Just fill in the
       
  2794 ** page content with zeros.  But mark the fact that we have not read the
       
  2795 ** content by setting the PgHdr.needRead flag.  Later on, if 
       
  2796 ** sqlite3PagerWrite() is called on this page or if this routine is
       
  2797 ** called again with noContent==0, that means that the content is needed
       
  2798 ** and the disk read should occur at that point.
       
  2799 */
       
  2800 int sqlite3PagerAcquire(
       
  2801   Pager *pPager,      /* The pager open on the database file */
       
  2802   Pgno pgno,          /* Page number to fetch */
       
  2803   DbPage **ppPage,    /* Write a pointer to the page here */
       
  2804   int noContent       /* Do not bother reading content from disk if true */
       
  2805 ){
       
  2806   PgHdr *pPg = 0;
       
  2807   int rc;
       
  2808 
       
  2809   assert( pPager->state==PAGER_UNLOCK 
       
  2810        || sqlite3PcacheRefCount(pPager->pPCache)>0 
       
  2811        || pgno==1 
       
  2812   );
       
  2813 
       
  2814   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
       
  2815   ** number greater than this, or zero, is requested.
       
  2816   */
       
  2817   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
       
  2818     return SQLITE_CORRUPT_BKPT;
       
  2819   }
       
  2820 
       
  2821   /* Make sure we have not hit any critical errors.
       
  2822   */ 
       
  2823   assert( pPager!=0 );
       
  2824   *ppPage = 0;
       
  2825 
       
  2826   /* If this is the first page accessed, then get a SHARED lock
       
  2827   ** on the database file. pagerSharedLock() is a no-op if 
       
  2828   ** a database lock is already held.
       
  2829   */
       
  2830   rc = pagerSharedLock(pPager);
       
  2831   if( rc!=SQLITE_OK ){
       
  2832     return rc;
       
  2833   }
       
  2834   assert( pPager->state!=PAGER_UNLOCK );
       
  2835 
       
  2836   rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
       
  2837   if( rc!=SQLITE_OK ){
       
  2838     return rc;
       
  2839   }
       
  2840   if( pPg->pPager==0 ){
       
  2841     /* The pager cache has created a new page. Its content needs to 
       
  2842     ** be initialized.
       
  2843     */
       
  2844     int nMax;
       
  2845     PAGER_INCR(pPager->nMiss);
       
  2846     pPg->pPager = pPager;
       
  2847     if( sqlite3BitvecTest(pPager->pInJournal, pgno) ){
       
  2848       assert( !MEMDB );
       
  2849       pPg->flags |= PGHDR_IN_JOURNAL;
       
  2850     }
       
  2851     memset(pPg->pExtra, 0, pPager->nExtra);
       
  2852 
       
  2853     rc = sqlite3PagerPagecount(pPager, &nMax);
       
  2854     if( rc!=SQLITE_OK ){
       
  2855       sqlite3PagerUnref(pPg);
       
  2856       return rc;
       
  2857     }
       
  2858 
       
  2859     if( nMax<(int)pgno || MEMDB || noContent ){
       
  2860       if( pgno>pPager->mxPgno ){
       
  2861         sqlite3PagerUnref(pPg);
       
  2862         return SQLITE_FULL;
       
  2863       }
       
  2864       memset(pPg->pData, 0, pPager->pageSize);
       
  2865       if( noContent ){
       
  2866         pPg->flags |= PGHDR_NEED_READ;
       
  2867       }
       
  2868       IOTRACE(("ZERO %p %d\n", pPager, pgno));
       
  2869     }else{
       
  2870       rc = readDbPage(pPager, pPg, pgno);
       
  2871       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
       
  2872         /* sqlite3PagerUnref(pPg); */
       
  2873         pagerDropPage(pPg);
       
  2874         return rc;
       
  2875       }
       
  2876     }
       
  2877 #ifdef SQLITE_CHECK_PAGES
       
  2878     pPg->pageHash = pager_pagehash(pPg);
       
  2879 #endif
       
  2880   }else{
       
  2881     /* The requested page is in the page cache. */
       
  2882     assert(sqlite3PcacheRefCount(pPager->pPCache)>0 || pgno==1);
       
  2883     PAGER_INCR(pPager->nHit);
       
  2884     if( !noContent ){
       
  2885       rc = pager_get_content(pPg);
       
  2886       if( rc ){
       
  2887         sqlite3PagerUnref(pPg);
       
  2888         return rc;
       
  2889       }
       
  2890     }
       
  2891   }
       
  2892 
       
  2893   *ppPage = pPg;
       
  2894   return SQLITE_OK;
       
  2895 }
       
  2896 
       
  2897 /*
       
  2898 ** Acquire a page if it is already in the in-memory cache.  Do
       
  2899 ** not read the page from disk.  Return a pointer to the page,
       
  2900 ** or 0 if the page is not in cache.
       
  2901 **
       
  2902 ** See also sqlite3PagerGet().  The difference between this routine
       
  2903 ** and sqlite3PagerGet() is that _get() will go to the disk and read
       
  2904 ** in the page if the page is not already in cache.  This routine
       
  2905 ** returns NULL if the page is not in cache or if a disk I/O error 
       
  2906 ** has ever happened.
       
  2907 */
       
  2908 DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
       
  2909   PgHdr *pPg = 0;
       
  2910   assert( pPager!=0 );
       
  2911   assert( pgno!=0 );
       
  2912 
       
  2913   if( (pPager->state!=PAGER_UNLOCK)
       
  2914    && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
       
  2915   ){
       
  2916     sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
       
  2917   }
       
  2918 
       
  2919   return pPg;
       
  2920 }
       
  2921 
       
  2922 /*
       
  2923 ** Release a page.
       
  2924 **
       
  2925 ** If the number of references to the page drop to zero, then the
       
  2926 ** page is added to the LRU list.  When all references to all pages
       
  2927 ** are released, a rollback occurs and the lock on the database is
       
  2928 ** removed.
       
  2929 */
       
  2930 int sqlite3PagerUnref(DbPage *pPg){
       
  2931   if( pPg ){
       
  2932     Pager *pPager = pPg->pPager;
       
  2933     sqlite3PcacheRelease(pPg);
       
  2934     pagerUnlockIfUnused(pPager);
       
  2935   }
       
  2936   return SQLITE_OK;
       
  2937 }
       
  2938 
       
  2939 /*
       
  2940 ** Create a journal file for pPager.  There should already be a RESERVED
       
  2941 ** or EXCLUSIVE lock on the database file when this routine is called.
       
  2942 **
       
  2943 ** Return SQLITE_OK if everything.  Return an error code and release the
       
  2944 ** write lock if anything goes wrong.
       
  2945 */
       
  2946 static int pager_open_journal(Pager *pPager){
       
  2947   sqlite3_vfs *pVfs = pPager->pVfs;
       
  2948   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
       
  2949 
       
  2950   int rc;
       
  2951   assert( !MEMDB );
       
  2952   assert( pPager->state>=PAGER_RESERVED );
       
  2953   assert( pPager->useJournal );
       
  2954   assert( pPager->pInJournal==0 );
       
  2955   sqlite3PagerPagecount(pPager, 0);
       
  2956   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
       
  2957   if( pPager->pInJournal==0 ){
       
  2958     rc = SQLITE_NOMEM;
       
  2959     goto failed_to_open_journal;
       
  2960   }
       
  2961 
       
  2962   if( pPager->journalOpen==0 ){
       
  2963     if( pPager->tempFile ){
       
  2964       flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
       
  2965     }else{
       
  2966       flags |= (SQLITE_OPEN_MAIN_JOURNAL);
       
  2967     }
       
  2968 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
       
  2969     rc = sqlite3JournalOpen(
       
  2970         pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
       
  2971     );
       
  2972 #else
       
  2973     rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
       
  2974 #endif
       
  2975     assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
       
  2976     pPager->journalOff = 0;
       
  2977     pPager->setMaster = 0;
       
  2978     pPager->journalHdr = 0;
       
  2979     if( rc!=SQLITE_OK ){
       
  2980       if( rc==SQLITE_NOMEM ){
       
  2981         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
       
  2982       }
       
  2983       goto failed_to_open_journal;
       
  2984     }
       
  2985   }
       
  2986   pPager->journalOpen = 1;
       
  2987   pPager->journalStarted = 0;
       
  2988   pPager->needSync = 0;
       
  2989   pPager->nRec = 0;
       
  2990   if( pPager->errCode ){
       
  2991     rc = pPager->errCode;
       
  2992     goto failed_to_open_journal;
       
  2993   }
       
  2994   pPager->origDbSize = pPager->dbSize;
       
  2995 
       
  2996   rc = writeJournalHdr(pPager);
       
  2997 
       
  2998   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
       
  2999     rc = sqlite3PagerStmtBegin(pPager);
       
  3000   }
       
  3001   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
       
  3002     rc = pager_end_transaction(pPager, 0);
       
  3003     if( rc==SQLITE_OK ){
       
  3004       rc = SQLITE_FULL;
       
  3005     }
       
  3006   }
       
  3007   return rc;
       
  3008 
       
  3009 failed_to_open_journal:
       
  3010   sqlite3BitvecDestroy(pPager->pInJournal);
       
  3011   pPager->pInJournal = 0;
       
  3012   return rc;
       
  3013 }
       
  3014 
       
  3015 /*
       
  3016 ** Acquire a write-lock on the database.  The lock is removed when
       
  3017 ** the any of the following happen:
       
  3018 **
       
  3019 **   *  sqlite3PagerCommitPhaseTwo() is called.
       
  3020 **   *  sqlite3PagerRollback() is called.
       
  3021 **   *  sqlite3PagerClose() is called.
       
  3022 **   *  sqlite3PagerUnref() is called to on every outstanding page.
       
  3023 **
       
  3024 ** The first parameter to this routine is a pointer to any open page of the
       
  3025 ** database file.  Nothing changes about the page - it is used merely to
       
  3026 ** acquire a pointer to the Pager structure and as proof that there is
       
  3027 ** already a read-lock on the database.
       
  3028 **
       
  3029 ** The second parameter indicates how much space in bytes to reserve for a
       
  3030 ** master journal file-name at the start of the journal when it is created.
       
  3031 **
       
  3032 ** A journal file is opened if this is not a temporary file.  For temporary
       
  3033 ** files, the opening of the journal file is deferred until there is an
       
  3034 ** actual need to write to the journal.
       
  3035 **
       
  3036 ** If the database is already reserved for writing, this routine is a no-op.
       
  3037 **
       
  3038 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
       
  3039 ** immediately instead of waiting until we try to flush the cache.  The
       
  3040 ** exFlag is ignored if a transaction is already active.
       
  3041 */
       
  3042 int sqlite3PagerBegin(DbPage *pPg, int exFlag){
       
  3043   Pager *pPager = pPg->pPager;
       
  3044   int rc = SQLITE_OK;
       
  3045   assert( pPg->nRef>0 );
       
  3046   assert( pPager->state!=PAGER_UNLOCK );
       
  3047   if( pPager->state==PAGER_SHARED ){
       
  3048     assert( pPager->pInJournal==0 );
       
  3049     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
       
  3050     if( MEMDB ){
       
  3051       pPager->state = PAGER_EXCLUSIVE;
       
  3052       pPager->origDbSize = pPager->dbSize;
       
  3053     }else{
       
  3054       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
       
  3055       if( rc==SQLITE_OK ){
       
  3056         pPager->state = PAGER_RESERVED;
       
  3057         if( exFlag ){
       
  3058           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
       
  3059         }
       
  3060       }
       
  3061       if( rc!=SQLITE_OK ){
       
  3062         return rc;
       
  3063       }
       
  3064       pPager->dirtyCache = 0;
       
  3065       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
       
  3066       if( pPager->useJournal && !pPager->tempFile
       
  3067              && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
       
  3068         rc = pager_open_journal(pPager);
       
  3069       }
       
  3070     }
       
  3071   }else if( pPager->journalOpen && pPager->journalOff==0 ){
       
  3072     /* This happens when the pager was in exclusive-access mode the last
       
  3073     ** time a (read or write) transaction was successfully concluded
       
  3074     ** by this connection. Instead of deleting the journal file it was 
       
  3075     ** kept open and either was truncated to 0 bytes or its header was
       
  3076     ** overwritten with zeros.
       
  3077     */
       
  3078     assert( pPager->nRec==0 );
       
  3079     assert( pPager->origDbSize==0 );
       
  3080     assert( pPager->pInJournal==0 );
       
  3081     sqlite3PagerPagecount(pPager, 0);
       
  3082     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
       
  3083     if( !pPager->pInJournal ){
       
  3084       rc = SQLITE_NOMEM;
       
  3085     }else{
       
  3086       pPager->origDbSize = pPager->dbSize;
       
  3087       rc = writeJournalHdr(pPager);
       
  3088     }
       
  3089   }
       
  3090   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
       
  3091   return rc;
       
  3092 }
       
  3093 
       
  3094 /*
       
  3095 ** Make a page dirty.  Set its dirty flag and add it to the dirty
       
  3096 ** page list.
       
  3097 */
       
  3098 static void makeDirty(PgHdr *pPg){
       
  3099   sqlite3PcacheMakeDirty(pPg);
       
  3100 }
       
  3101 
       
  3102 /*
       
  3103 ** Make a page clean.  Clear its dirty bit and remove it from the
       
  3104 ** dirty page list.
       
  3105 */
       
  3106 static void makeClean(PgHdr *pPg){
       
  3107   sqlite3PcacheMakeClean(pPg);
       
  3108 }
       
  3109 
       
  3110 
       
  3111 /*
       
  3112 ** Mark a data page as writeable.  The page is written into the journal 
       
  3113 ** if it is not there already.  This routine must be called before making
       
  3114 ** changes to a page.
       
  3115 **
       
  3116 ** The first time this routine is called, the pager creates a new
       
  3117 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
       
  3118 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
       
  3119 ** calling routine must check for that return value and be careful not to
       
  3120 ** change any page data until this routine returns SQLITE_OK.
       
  3121 **
       
  3122 ** If the journal file could not be written because the disk is full,
       
  3123 ** then this routine returns SQLITE_FULL and does an immediate rollback.
       
  3124 ** All subsequent write attempts also return SQLITE_FULL until there
       
  3125 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
       
  3126 ** reset.
       
  3127 */
       
  3128 static int pager_write(PgHdr *pPg){
       
  3129   void *pData = pPg->pData;
       
  3130   Pager *pPager = pPg->pPager;
       
  3131   int rc = SQLITE_OK;
       
  3132 
       
  3133   /* Check for errors
       
  3134   */
       
  3135   if( pPager->errCode ){ 
       
  3136     return pPager->errCode;
       
  3137   }
       
  3138   if( pPager->readOnly ){
       
  3139     return SQLITE_PERM;
       
  3140   }
       
  3141 
       
  3142   assert( !pPager->setMaster );
       
  3143 
       
  3144   CHECK_PAGE(pPg);
       
  3145 
       
  3146   /* If this page was previously acquired with noContent==1, that means
       
  3147   ** we didn't really read in the content of the page.  This can happen
       
  3148   ** (for example) when the page is being moved to the freelist.  But
       
  3149   ** now we are (perhaps) moving the page off of the freelist for
       
  3150   ** reuse and we need to know its original content so that content
       
  3151   ** can be stored in the rollback journal.  So do the read at this
       
  3152   ** time.
       
  3153   */
       
  3154   rc = pager_get_content(pPg);
       
  3155   if( rc ){
       
  3156     return rc;
       
  3157   }
       
  3158 
       
  3159   /* Mark the page as dirty.  If the page has already been written
       
  3160   ** to the journal then we can return right away.
       
  3161   */
       
  3162   makeDirty(pPg);
       
  3163   if( (pPg->flags&PGHDR_IN_JOURNAL)
       
  3164    && (pageInStatement(pPg) || pPager->stmtInUse==0) 
       
  3165   ){
       
  3166     pPager->dirtyCache = 1;
       
  3167     pPager->dbModified = 1;
       
  3168   }else{
       
  3169 
       
  3170     /* If we get this far, it means that the page needs to be
       
  3171     ** written to the transaction journal or the ckeckpoint journal
       
  3172     ** or both.
       
  3173     **
       
  3174     ** First check to see that the transaction journal exists and
       
  3175     ** create it if it does not.
       
  3176     */
       
  3177     assert( pPager->state!=PAGER_UNLOCK );
       
  3178     rc = sqlite3PagerBegin(pPg, 0);
       
  3179     if( rc!=SQLITE_OK ){
       
  3180       return rc;
       
  3181     }
       
  3182     assert( pPager->state>=PAGER_RESERVED );
       
  3183     if( !pPager->journalOpen && pPager->useJournal
       
  3184           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
       
  3185       rc = pager_open_journal(pPager);
       
  3186       if( rc!=SQLITE_OK ) return rc;
       
  3187     }
       
  3188     pPager->dirtyCache = 1;
       
  3189     pPager->dbModified = 1;
       
  3190   
       
  3191     /* The transaction journal now exists and we have a RESERVED or an
       
  3192     ** EXCLUSIVE lock on the main database file.  Write the current page to
       
  3193     ** the transaction journal if it is not there already.
       
  3194     */
       
  3195     if( !(pPg->flags&PGHDR_IN_JOURNAL) && (pPager->journalOpen || MEMDB) ){
       
  3196       if( (int)pPg->pgno <= pPager->origDbSize ){
       
  3197         if( MEMDB ){
       
  3198           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
       
  3199           rc = sqlite3PcachePreserve(pPg, 0);
       
  3200           if( rc!=SQLITE_OK ){
       
  3201             return rc;
       
  3202           }
       
  3203         }else{
       
  3204           u32 cksum;
       
  3205           char *pData2;
       
  3206 
       
  3207           /* We should never write to the journal file the page that
       
  3208           ** contains the database locks.  The following assert verifies
       
  3209           ** that we do not. */
       
  3210           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
       
  3211           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
       
  3212           cksum = pager_cksum(pPager, (u8*)pData2);
       
  3213           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
       
  3214           if( rc==SQLITE_OK ){
       
  3215             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
       
  3216                                 pPager->journalOff + 4);
       
  3217             pPager->journalOff += pPager->pageSize+4;
       
  3218           }
       
  3219           if( rc==SQLITE_OK ){
       
  3220             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
       
  3221             pPager->journalOff += 4;
       
  3222           }
       
  3223           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
       
  3224                    pPager->journalOff, pPager->pageSize));
       
  3225           PAGER_INCR(sqlite3_pager_writej_count);
       
  3226           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
       
  3227                PAGERID(pPager), pPg->pgno, 
       
  3228                ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg));
       
  3229 
       
  3230           /* An error has occured writing to the journal file. The 
       
  3231           ** transaction will be rolled back by the layer above.
       
  3232           */
       
  3233           if( rc!=SQLITE_OK ){
       
  3234             return rc;
       
  3235           }
       
  3236 
       
  3237           pPager->nRec++;
       
  3238           assert( pPager->pInJournal!=0 );
       
  3239           sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
       
  3240           if( !pPager->noSync ){
       
  3241             pPg->flags |= PGHDR_NEED_SYNC;
       
  3242           }
       
  3243           if( pPager->stmtInUse ){
       
  3244             sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
       
  3245           }
       
  3246         }
       
  3247       }else{
       
  3248         if( !pPager->journalStarted && !pPager->noSync ){
       
  3249           pPg->flags |= PGHDR_NEED_SYNC;
       
  3250         }
       
  3251         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
       
  3252                 PAGERID(pPager), pPg->pgno,
       
  3253                ((pPg->flags&PGHDR_NEED_SYNC)?1:0));
       
  3254       }
       
  3255       if( pPg->flags&PGHDR_NEED_SYNC ){
       
  3256         pPager->needSync = 1;
       
  3257       }
       
  3258       pPg->flags |= PGHDR_IN_JOURNAL;
       
  3259     }
       
  3260   
       
  3261     /* If the statement journal is open and the page is not in it,
       
  3262     ** then write the current page to the statement journal.  Note that
       
  3263     ** the statement journal format differs from the standard journal format
       
  3264     ** in that it omits the checksums and the header.
       
  3265     */
       
  3266     if( pPager->stmtInUse 
       
  3267      && !pageInStatement(pPg) 
       
  3268      && (int)pPg->pgno<=pPager->stmtSize 
       
  3269     ){
       
  3270       assert( (pPg->flags&PGHDR_IN_JOURNAL) 
       
  3271                  || (int)pPg->pgno>pPager->origDbSize );
       
  3272       if( MEMDB ){
       
  3273         rc = sqlite3PcachePreserve(pPg, 1);
       
  3274         if( rc!=SQLITE_OK ){
       
  3275           return rc;
       
  3276         }
       
  3277         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
       
  3278       }else{
       
  3279         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
       
  3280         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
       
  3281         rc = write32bits(pPager->stfd, offset, pPg->pgno);
       
  3282         if( rc==SQLITE_OK ){
       
  3283           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
       
  3284         }
       
  3285         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
       
  3286         if( rc!=SQLITE_OK ){
       
  3287           return rc;
       
  3288         }
       
  3289         pPager->stmtNRec++;
       
  3290         assert( pPager->pInStmt!=0 );
       
  3291         sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
       
  3292       }
       
  3293     }
       
  3294   }
       
  3295 
       
  3296   /* Update the database size and return.
       
  3297   */
       
  3298   assert( pPager->state>=PAGER_SHARED );
       
  3299   if( pPager->dbSize<(int)pPg->pgno ){
       
  3300     pPager->dbSize = pPg->pgno;
       
  3301     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
       
  3302       pPager->dbSize++;
       
  3303     }
       
  3304   }
       
  3305   return rc;
       
  3306 }
       
  3307 
       
  3308 /*
       
  3309 ** This function is used to mark a data-page as writable. It uses 
       
  3310 ** pager_write() to open a journal file (if it is not already open)
       
  3311 ** and write the page *pData to the journal.
       
  3312 **
       
  3313 ** The difference between this function and pager_write() is that this
       
  3314 ** function also deals with the special case where 2 or more pages
       
  3315 ** fit on a single disk sector. In this case all co-resident pages
       
  3316 ** must have been written to the journal file before returning.
       
  3317 */
       
  3318 int sqlite3PagerWrite(DbPage *pDbPage){
       
  3319   int rc = SQLITE_OK;
       
  3320 
       
  3321   PgHdr *pPg = pDbPage;
       
  3322   Pager *pPager = pPg->pPager;
       
  3323   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
       
  3324 
       
  3325   if( !MEMDB && nPagePerSector>1 ){
       
  3326     Pgno nPageCount;          /* Total number of pages in database file */
       
  3327     Pgno pg1;                 /* First page of the sector pPg is located on. */
       
  3328     int nPage;                /* Number of pages starting at pg1 to journal */
       
  3329     int ii;
       
  3330     int needSync = 0;
       
  3331 
       
  3332     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
       
  3333     ** header to be written between the pages journaled by this function.
       
  3334     */
       
  3335     assert( pPager->doNotSync==0 );
       
  3336     pPager->doNotSync = 1;
       
  3337 
       
  3338     /* This trick assumes that both the page-size and sector-size are
       
  3339     ** an integer power of 2. It sets variable pg1 to the identifier
       
  3340     ** of the first page of the sector pPg is located on.
       
  3341     */
       
  3342     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
       
  3343 
       
  3344     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
       
  3345     if( pPg->pgno>nPageCount ){
       
  3346       nPage = (pPg->pgno - pg1)+1;
       
  3347     }else if( (pg1+nPagePerSector-1)>nPageCount ){
       
  3348       nPage = nPageCount+1-pg1;
       
  3349     }else{
       
  3350       nPage = nPagePerSector;
       
  3351     }
       
  3352     assert(nPage>0);
       
  3353     assert(pg1<=pPg->pgno);
       
  3354     assert((pg1+nPage)>pPg->pgno);
       
  3355 
       
  3356     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
       
  3357       Pgno pg = pg1+ii;
       
  3358       PgHdr *pPage;
       
  3359       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
       
  3360         if( pg!=PAGER_MJ_PGNO(pPager) ){
       
  3361           rc = sqlite3PagerGet(pPager, pg, &pPage);
       
  3362           if( rc==SQLITE_OK ){
       
  3363             rc = pager_write(pPage);
       
  3364             if( pPage->flags&PGHDR_NEED_SYNC ){
       
  3365               needSync = 1;
       
  3366             }
       
  3367             sqlite3PagerUnref(pPage);
       
  3368           }
       
  3369         }
       
  3370       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
       
  3371         if( pPage->flags&PGHDR_NEED_SYNC ){
       
  3372           needSync = 1;
       
  3373         }
       
  3374         sqlite3PagerUnref(pPage);
       
  3375       }
       
  3376     }
       
  3377 
       
  3378     /* If the PgHdr.needSync flag is set for any of the nPage pages 
       
  3379     ** starting at pg1, then it needs to be set for all of them. Because
       
  3380     ** writing to any of these nPage pages may damage the others, the
       
  3381     ** journal file must contain sync()ed copies of all of them
       
  3382     ** before any of them can be written out to the database file.
       
  3383     */
       
  3384     if( needSync ){
       
  3385       assert( !MEMDB && pPager->noSync==0 );
       
  3386       for(ii=0; ii<nPage && needSync; ii++){
       
  3387         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
       
  3388         if( pPage ) pPage->flags |= PGHDR_NEED_SYNC;
       
  3389         sqlite3PagerUnref(pPage);
       
  3390       }
       
  3391       assert(pPager->needSync);
       
  3392     }
       
  3393 
       
  3394     assert( pPager->doNotSync==1 );
       
  3395     pPager->doNotSync = 0;
       
  3396   }else{
       
  3397     rc = pager_write(pDbPage);
       
  3398   }
       
  3399   return rc;
       
  3400 }
       
  3401 
       
  3402 /*
       
  3403 ** Return TRUE if the page given in the argument was previously passed
       
  3404 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
       
  3405 ** to change the content of the page.
       
  3406 */
       
  3407 #ifndef NDEBUG
       
  3408 int sqlite3PagerIswriteable(DbPage *pPg){
       
  3409   return pPg->flags&PGHDR_DIRTY;
       
  3410 }
       
  3411 #endif
       
  3412 
       
  3413 /*
       
  3414 ** A call to this routine tells the pager that it is not necessary to
       
  3415 ** write the information on page pPg back to the disk, even though
       
  3416 ** that page might be marked as dirty.
       
  3417 **
       
  3418 ** The overlying software layer calls this routine when all of the data
       
  3419 ** on the given page is unused.  The pager marks the page as clean so
       
  3420 ** that it does not get written to disk.
       
  3421 **
       
  3422 ** Tests show that this optimization, together with the
       
  3423 ** sqlite3PagerDontRollback() below, more than double the speed
       
  3424 ** of large INSERT operations and quadruple the speed of large DELETEs.
       
  3425 **
       
  3426 ** When this routine is called, set the alwaysRollback flag to true.
       
  3427 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
       
  3428 ** will thereafter be ignored.  This is necessary to avoid a problem
       
  3429 ** where a page with data is added to the freelist during one part of
       
  3430 ** a transaction then removed from the freelist during a later part
       
  3431 ** of the same transaction and reused for some other purpose.  When it
       
  3432 ** is first added to the freelist, this routine is called.  When reused,
       
  3433 ** the sqlite3PagerDontRollback() routine is called.  But because the
       
  3434 ** page contains critical data, we still need to be sure it gets
       
  3435 ** rolled back in spite of the sqlite3PagerDontRollback() call.
       
  3436 */
       
  3437 int sqlite3PagerDontWrite(DbPage *pDbPage){
       
  3438   PgHdr *pPg = pDbPage;
       
  3439   Pager *pPager = pPg->pPager;
       
  3440   int rc;
       
  3441 
       
  3442   if( MEMDB || pPg->pgno>pPager->origDbSize ){
       
  3443     return SQLITE_OK;
       
  3444   }
       
  3445   if( pPager->pAlwaysRollback==0 ){
       
  3446     assert( pPager->pInJournal );
       
  3447     pPager->pAlwaysRollback = sqlite3BitvecCreate(pPager->origDbSize);
       
  3448     if( !pPager->pAlwaysRollback ){
       
  3449       return SQLITE_NOMEM;
       
  3450     }
       
  3451   }
       
  3452   rc = sqlite3BitvecSet(pPager->pAlwaysRollback, pPg->pgno);
       
  3453 
       
  3454   if( rc==SQLITE_OK && (pPg->flags&PGHDR_DIRTY) && !pPager->stmtInUse ){
       
  3455     assert( pPager->state>=PAGER_SHARED );
       
  3456     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
       
  3457       /* If this pages is the last page in the file and the file has grown
       
  3458       ** during the current transaction, then do NOT mark the page as clean.
       
  3459       ** When the database file grows, we must make sure that the last page
       
  3460       ** gets written at least once so that the disk file will be the correct
       
  3461       ** size. If you do not write this page and the size of the file
       
  3462       ** on the disk ends up being too small, that can lead to database
       
  3463       ** corruption during the next transaction.
       
  3464       */
       
  3465     }else{
       
  3466       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
       
  3467       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
       
  3468       pPg->flags |= PGHDR_DONT_WRITE;
       
  3469 #ifdef SQLITE_CHECK_PAGES
       
  3470       pPg->pageHash = pager_pagehash(pPg);
       
  3471 #endif
       
  3472     }
       
  3473   }
       
  3474   return rc;
       
  3475 }
       
  3476 
       
  3477 /*
       
  3478 ** A call to this routine tells the pager that if a rollback occurs,
       
  3479 ** it is not necessary to restore the data on the given page.  This
       
  3480 ** means that the pager does not have to record the given page in the
       
  3481 ** rollback journal.
       
  3482 **
       
  3483 ** If we have not yet actually read the content of this page (if
       
  3484 ** the PgHdr.needRead flag is set) then this routine acts as a promise
       
  3485 ** that we will never need to read the page content in the future.
       
  3486 ** so the needRead flag can be cleared at this point.
       
  3487 */
       
  3488 void sqlite3PagerDontRollback(DbPage *pPg){
       
  3489   Pager *pPager = pPg->pPager;
       
  3490 
       
  3491   assert( pPager->state>=PAGER_RESERVED );
       
  3492 
       
  3493   /* If the journal file is not open, or DontWrite() has been called on
       
  3494   ** this page (DontWrite() sets the alwaysRollback flag), then this
       
  3495   ** function is a no-op.
       
  3496   */
       
  3497   if( pPager->journalOpen==0 
       
  3498    || sqlite3BitvecTest(pPager->pAlwaysRollback, pPg->pgno)
       
  3499    || pPg->pgno>pPager->origDbSize
       
  3500   ){
       
  3501     return;
       
  3502   }
       
  3503   assert( !MEMDB );    /* For a memdb, pPager->journalOpen is always 0 */
       
  3504 
       
  3505 #ifdef SQLITE_SECURE_DELETE
       
  3506   if( (pPg->flags & PGHDR_IN_JOURNAL)!=0 || (int)pPg->pgno>pPager->origDbSize ){
       
  3507     return;
       
  3508   }
       
  3509 #endif
       
  3510 
       
  3511   /* If SECURE_DELETE is disabled, then there is no way that this
       
  3512   ** routine can be called on a page for which sqlite3PagerDontWrite()
       
  3513   ** has not been previously called during the same transaction.
       
  3514   ** And if DontWrite() has previously been called, the following
       
  3515   ** conditions must be met.
       
  3516   **
       
  3517   ** (Later:)  Not true.  If the database is corrupted by having duplicate
       
  3518   ** pages on the freelist (ex: corrupt9.test) then the following is not
       
  3519   ** necessarily true:
       
  3520   */
       
  3521   /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ); */
       
  3522 
       
  3523   assert( pPager->pInJournal!=0 );
       
  3524   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
       
  3525   pPg->flags |= PGHDR_IN_JOURNAL;
       
  3526   pPg->flags &= ~PGHDR_NEED_READ;
       
  3527   if( pPager->stmtInUse ){
       
  3528     assert( pPager->stmtSize >= pPager->origDbSize );
       
  3529     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
       
  3530   }
       
  3531   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
       
  3532   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
       
  3533 }
       
  3534 
       
  3535 
       
  3536 /*
       
  3537 ** This routine is called to increment the database file change-counter,
       
  3538 ** stored at byte 24 of the pager file.
       
  3539 */
       
  3540 static int pager_incr_changecounter(Pager *pPager, int isDirect){
       
  3541   PgHdr *pPgHdr;
       
  3542   u32 change_counter;
       
  3543   int rc = SQLITE_OK;
       
  3544 
       
  3545 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
       
  3546   assert( isDirect==0 );  /* isDirect is only true for atomic writes */
       
  3547 #endif
       
  3548   if( !pPager->changeCountDone ){
       
  3549     /* Open page 1 of the file for writing. */
       
  3550     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
       
  3551     if( rc!=SQLITE_OK ) return rc;
       
  3552 
       
  3553     if( !isDirect ){
       
  3554       rc = sqlite3PagerWrite(pPgHdr);
       
  3555       if( rc!=SQLITE_OK ){
       
  3556         sqlite3PagerUnref(pPgHdr);
       
  3557         return rc;
       
  3558       }
       
  3559     }
       
  3560 
       
  3561     /* Increment the value just read and write it back to byte 24. */
       
  3562     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
       
  3563     change_counter++;
       
  3564     put32bits(((char*)pPgHdr->pData)+24, change_counter);
       
  3565 
       
  3566 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
       
  3567     if( isDirect && pPager->fd->pMethods ){
       
  3568       const void *zBuf = pPgHdr->pData;
       
  3569       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
       
  3570     }
       
  3571 #endif
       
  3572 
       
  3573     /* Release the page reference. */
       
  3574     sqlite3PagerUnref(pPgHdr);
       
  3575     pPager->changeCountDone = 1;
       
  3576   }
       
  3577   return rc;
       
  3578 }
       
  3579 
       
  3580 /*
       
  3581 ** Sync the pager file to disk.
       
  3582 */
       
  3583 int sqlite3PagerSync(Pager *pPager){
       
  3584   int rc;
       
  3585   if( MEMDB ){
       
  3586     rc = SQLITE_OK;
       
  3587   }else{
       
  3588     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
       
  3589   }
       
  3590   return rc;
       
  3591 }
       
  3592 
       
  3593 /*
       
  3594 ** Sync the database file for the pager pPager. zMaster points to the name
       
  3595 ** of a master journal file that should be written into the individual
       
  3596 ** journal file. zMaster may be NULL, which is interpreted as no master
       
  3597 ** journal (a single database transaction).
       
  3598 **
       
  3599 ** This routine ensures that the journal is synced, all dirty pages written
       
  3600 ** to the database file and the database file synced. The only thing that
       
  3601 ** remains to commit the transaction is to delete the journal file (or
       
  3602 ** master journal file if specified).
       
  3603 **
       
  3604 ** Note that if zMaster==NULL, this does not overwrite a previous value
       
  3605 ** passed to an sqlite3PagerCommitPhaseOne() call.
       
  3606 **
       
  3607 ** If parameter nTrunc is non-zero, then the pager file is truncated to
       
  3608 ** nTrunc pages (this is used by auto-vacuum databases).
       
  3609 **
       
  3610 ** If the final parameter - noSync - is true, then the database file itself
       
  3611 ** is not synced. The caller must call sqlite3PagerSync() directly to
       
  3612 ** sync the database file before calling CommitPhaseTwo() to delete the
       
  3613 ** journal file in this case.
       
  3614 */
       
  3615 int sqlite3PagerCommitPhaseOne(
       
  3616   Pager *pPager, 
       
  3617   const char *zMaster, 
       
  3618   Pgno nTrunc,
       
  3619   int noSync
       
  3620 ){
       
  3621   int rc = SQLITE_OK;
       
  3622 
       
  3623   if( pPager->errCode ){
       
  3624     return pPager->errCode;
       
  3625   }
       
  3626 
       
  3627   /* If no changes have been made, we can leave the transaction early.
       
  3628   */
       
  3629   if( pPager->dbModified==0 &&
       
  3630         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
       
  3631           pPager->exclusiveMode!=0) ){
       
  3632     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
       
  3633     return SQLITE_OK;
       
  3634   }
       
  3635 
       
  3636   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
       
  3637       pPager->zFilename, zMaster, nTrunc);
       
  3638 
       
  3639   /* If this is an in-memory db, or no pages have been written to, or this
       
  3640   ** function has already been called, it is a no-op.
       
  3641   */
       
  3642   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
       
  3643     PgHdr *pPg;
       
  3644 
       
  3645 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
       
  3646     /* The atomic-write optimization can be used if all of the
       
  3647     ** following are true:
       
  3648     **
       
  3649     **    + The file-system supports the atomic-write property for
       
  3650     **      blocks of size page-size, and
       
  3651     **    + This commit is not part of a multi-file transaction, and
       
  3652     **    + Exactly one page has been modified and store in the journal file.
       
  3653     **
       
  3654     ** If the optimization can be used, then the journal file will never
       
  3655     ** be created for this transaction.
       
  3656     */
       
  3657     int useAtomicWrite;
       
  3658     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
       
  3659     useAtomicWrite = (
       
  3660         !zMaster && 
       
  3661         pPager->journalOpen &&
       
  3662         pPager->journalOff==jrnlBufferSize(pPager) && 
       
  3663         nTrunc==0 && 
       
  3664         (pPg==0 || pPg->pDirty==0)
       
  3665     );
       
  3666     assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
       
  3667     if( useAtomicWrite ){
       
  3668       /* Update the nRec field in the journal file. */
       
  3669       int offset = pPager->journalHdr + sizeof(aJournalMagic);
       
  3670       assert(pPager->nRec==1);
       
  3671       rc = write32bits(pPager->jfd, offset, pPager->nRec);
       
  3672 
       
  3673       /* Update the db file change counter. The following call will modify
       
  3674       ** the in-memory representation of page 1 to include the updated
       
  3675       ** change counter and then write page 1 directly to the database
       
  3676       ** file. Because of the atomic-write property of the host file-system, 
       
  3677       ** this is safe.
       
  3678       */
       
  3679       if( rc==SQLITE_OK ){
       
  3680         rc = pager_incr_changecounter(pPager, 1);
       
  3681       }
       
  3682     }else{
       
  3683       rc = sqlite3JournalCreate(pPager->jfd);
       
  3684     }
       
  3685 
       
  3686     if( !useAtomicWrite && rc==SQLITE_OK )
       
  3687 #endif
       
  3688 
       
  3689     /* If a master journal file name has already been written to the
       
  3690     ** journal file, then no sync is required. This happens when it is
       
  3691     ** written, then the process fails to upgrade from a RESERVED to an
       
  3692     ** EXCLUSIVE lock. The next time the process tries to commit the
       
  3693     ** transaction the m-j name will have already been written.
       
  3694     */
       
  3695     if( !pPager->setMaster ){
       
  3696       rc = pager_incr_changecounter(pPager, 0);
       
  3697       if( rc!=SQLITE_OK ) goto sync_exit;
       
  3698       if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
       
  3699 #ifndef SQLITE_OMIT_AUTOVACUUM
       
  3700         if( nTrunc!=0 ){
       
  3701           /* If this transaction has made the database smaller, then all pages
       
  3702           ** being discarded by the truncation must be written to the journal
       
  3703           ** file.
       
  3704           */
       
  3705           Pgno i;
       
  3706           int iSkip = PAGER_MJ_PGNO(pPager);
       
  3707           for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
       
  3708             if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
       
  3709               rc = sqlite3PagerGet(pPager, i, &pPg);
       
  3710               if( rc!=SQLITE_OK ) goto sync_exit;
       
  3711               rc = sqlite3PagerWrite(pPg);
       
  3712               sqlite3PagerUnref(pPg);
       
  3713               if( rc!=SQLITE_OK ) goto sync_exit;
       
  3714             }
       
  3715           } 
       
  3716         }
       
  3717 #endif
       
  3718         rc = writeMasterJournal(pPager, zMaster);
       
  3719         if( rc!=SQLITE_OK ) goto sync_exit;
       
  3720         rc = syncJournal(pPager);
       
  3721       }
       
  3722     }
       
  3723     if( rc!=SQLITE_OK ) goto sync_exit;
       
  3724 
       
  3725 #ifndef SQLITE_OMIT_AUTOVACUUM
       
  3726     if( nTrunc!=0 ){
       
  3727       rc = sqlite3PagerTruncate(pPager, nTrunc);
       
  3728       if( rc!=SQLITE_OK ) goto sync_exit;
       
  3729     }
       
  3730 #endif
       
  3731 
       
  3732     /* Write all dirty pages to the database file */
       
  3733     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
       
  3734     rc = pager_write_pagelist(pPg);
       
  3735     if( rc!=SQLITE_OK ){
       
  3736       assert( rc!=SQLITE_IOERR_BLOCKED );
       
  3737       /* The error might have left the dirty list all fouled up here,
       
  3738       ** but that does not matter because if the if the dirty list did
       
  3739       ** get corrupted, then the transaction will roll back and
       
  3740       ** discard the dirty list.  There is an assert in
       
  3741       ** pager_get_all_dirty_pages() that verifies that no attempt
       
  3742       ** is made to use an invalid dirty list.
       
  3743       */
       
  3744       goto sync_exit;
       
  3745     }
       
  3746     sqlite3PcacheCleanAll(pPager->pPCache);
       
  3747 
       
  3748     /* Sync the database file. */
       
  3749     if( !pPager->noSync && !noSync ){
       
  3750       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
       
  3751     }
       
  3752     IOTRACE(("DBSYNC %p\n", pPager))
       
  3753 
       
  3754     pPager->state = PAGER_SYNCED;
       
  3755   }else if( MEMDB && nTrunc!=0 ){
       
  3756     rc = sqlite3PagerTruncate(pPager, nTrunc);
       
  3757   }
       
  3758 
       
  3759 sync_exit:
       
  3760   if( rc==SQLITE_IOERR_BLOCKED ){
       
  3761     /* pager_incr_changecounter() may attempt to obtain an exclusive
       
  3762      * lock to spill the cache and return IOERR_BLOCKED. But since 
       
  3763      * there is no chance the cache is inconsistent, it is
       
  3764      * better to return SQLITE_BUSY.
       
  3765      */
       
  3766     rc = SQLITE_BUSY;
       
  3767   }
       
  3768   return rc;
       
  3769 }
       
  3770 
       
  3771 
       
  3772 /*
       
  3773 ** Commit all changes to the database and release the write lock.
       
  3774 **
       
  3775 ** If the commit fails for any reason, a rollback attempt is made
       
  3776 ** and an error code is returned.  If the commit worked, SQLITE_OK
       
  3777 ** is returned.
       
  3778 */
       
  3779 int sqlite3PagerCommitPhaseTwo(Pager *pPager){
       
  3780   int rc = SQLITE_OK;
       
  3781 
       
  3782   if( pPager->errCode ){
       
  3783     return pPager->errCode;
       
  3784   }
       
  3785   if( pPager->state<PAGER_RESERVED ){
       
  3786     return SQLITE_ERROR;
       
  3787   }
       
  3788   if( pPager->dbModified==0 &&
       
  3789         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
       
  3790           pPager->exclusiveMode!=0) ){
       
  3791     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
       
  3792     return SQLITE_OK;
       
  3793   }
       
  3794   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
       
  3795   if( MEMDB ){
       
  3796     sqlite3PcacheCommit(pPager->pPCache, 0);
       
  3797     sqlite3PcacheCleanAll(pPager->pPCache);
       
  3798     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
       
  3799     pPager->state = PAGER_SHARED;
       
  3800   }else{
       
  3801     assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
       
  3802     rc = pager_end_transaction(pPager, pPager->setMaster);
       
  3803     rc = pager_error(pPager, rc);
       
  3804   }
       
  3805   return rc;
       
  3806 }
       
  3807 
       
  3808 /*
       
  3809 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
       
  3810 ** All in-memory cache pages revert to their original data contents.
       
  3811 ** The journal is deleted.
       
  3812 **
       
  3813 ** This routine cannot fail unless some other process is not following
       
  3814 ** the correct locking protocol or unless some other
       
  3815 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
       
  3816 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
       
  3817 ** codes are returned for all these occasions.  Otherwise,
       
  3818 ** SQLITE_OK is returned.
       
  3819 */
       
  3820 int sqlite3PagerRollback(Pager *pPager){
       
  3821   int rc = SQLITE_OK;
       
  3822   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
       
  3823   if( MEMDB ){
       
  3824     sqlite3PcacheRollback(pPager->pPCache, 1, pPager->xReiniter);
       
  3825     sqlite3PcacheRollback(pPager->pPCache, 0, pPager->xReiniter);
       
  3826     sqlite3PcacheCleanAll(pPager->pPCache);
       
  3827     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
       
  3828     pPager->dbSize = pPager->origDbSize;
       
  3829     pager_truncate_cache(pPager);
       
  3830     pPager->stmtInUse = 0;
       
  3831     pPager->state = PAGER_SHARED;
       
  3832   }else if( !pPager->dirtyCache || !pPager->journalOpen ){
       
  3833     rc = pager_end_transaction(pPager, pPager->setMaster);
       
  3834   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
       
  3835     if( pPager->state>=PAGER_EXCLUSIVE ){
       
  3836       pager_playback(pPager, 0);
       
  3837     }
       
  3838     rc = pPager->errCode;
       
  3839   }else{
       
  3840     if( pPager->state==PAGER_RESERVED ){
       
  3841       int rc2;
       
  3842       rc = pager_playback(pPager, 0);
       
  3843       rc2 = pager_end_transaction(pPager, pPager->setMaster);
       
  3844       if( rc==SQLITE_OK ){
       
  3845         rc = rc2;
       
  3846       }
       
  3847     }else{
       
  3848       rc = pager_playback(pPager, 0);
       
  3849     }
       
  3850 
       
  3851     pPager->dbSize = -1;
       
  3852 
       
  3853     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
       
  3854     ** cache. So call pager_error() on the way out to make any error 
       
  3855     ** persistent.
       
  3856     */
       
  3857     rc = pager_error(pPager, rc);
       
  3858   }
       
  3859   return rc;
       
  3860 }
       
  3861 
       
  3862 /*
       
  3863 ** Return TRUE if the database file is opened read-only.  Return FALSE
       
  3864 ** if the database is (in theory) writable.
       
  3865 */
       
  3866 int sqlite3PagerIsreadonly(Pager *pPager){
       
  3867   return pPager->readOnly;
       
  3868 }
       
  3869 
       
  3870 /*
       
  3871 ** Return the number of references to the pager.
       
  3872 */
       
  3873 int sqlite3PagerRefcount(Pager *pPager){
       
  3874   return sqlite3PcacheRefCount(pPager->pPCache);
       
  3875 }
       
  3876 
       
  3877 /*
       
  3878 ** Return the number of references to the specified page.
       
  3879 */
       
  3880 int sqlite3PagerPageRefcount(DbPage *pPage){
       
  3881   return sqlite3PcachePageRefcount(pPage);
       
  3882 }
       
  3883 
       
  3884 #ifdef SQLITE_TEST
       
  3885 /*
       
  3886 ** This routine is used for testing and analysis only.
       
  3887 */
       
  3888 int *sqlite3PagerStats(Pager *pPager){
       
  3889   static int a[11];
       
  3890   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
       
  3891   a[1] = sqlite3PcachePagecount(pPager->pPCache);
       
  3892   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
       
  3893   a[3] = pPager->dbSize;
       
  3894   a[4] = pPager->state;
       
  3895   a[5] = pPager->errCode;
       
  3896   a[6] = pPager->nHit;
       
  3897   a[7] = pPager->nMiss;
       
  3898   a[8] = 0;  /* Used to be pPager->nOvfl */
       
  3899   a[9] = pPager->nRead;
       
  3900   a[10] = pPager->nWrite;
       
  3901   return a;
       
  3902 }
       
  3903 int sqlite3PagerIsMemdb(Pager *pPager){
       
  3904   return MEMDB;
       
  3905 }
       
  3906 #endif
       
  3907 
       
  3908 /*
       
  3909 ** Set the statement rollback point.
       
  3910 **
       
  3911 ** This routine should be called with the transaction journal already
       
  3912 ** open.  A new statement journal is created that can be used to rollback
       
  3913 ** changes of a single SQL command within a larger transaction.
       
  3914 */
       
  3915 static int pagerStmtBegin(Pager *pPager){
       
  3916   int rc;
       
  3917   assert( !pPager->stmtInUse );
       
  3918   assert( pPager->state>=PAGER_SHARED );
       
  3919   assert( pPager->dbSize>=0 );
       
  3920   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
       
  3921   if( MEMDB ){
       
  3922     pPager->stmtInUse = 1;
       
  3923     pPager->stmtSize = pPager->dbSize;
       
  3924     return SQLITE_OK;
       
  3925   }
       
  3926   if( !pPager->journalOpen ){
       
  3927     pPager->stmtAutoopen = 1;
       
  3928     return SQLITE_OK;
       
  3929   }
       
  3930   assert( pPager->journalOpen );
       
  3931   assert( pPager->pInStmt==0 );
       
  3932   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
       
  3933   if( pPager->pInStmt==0 ){
       
  3934     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
       
  3935     return SQLITE_NOMEM;
       
  3936   }
       
  3937   pPager->stmtJSize = pPager->journalOff;
       
  3938   pPager->stmtSize = pPager->dbSize;
       
  3939   pPager->stmtHdrOff = 0;
       
  3940   pPager->stmtCksum = pPager->cksumInit;
       
  3941   if( !pPager->stmtOpen ){
       
  3942     rc = sqlite3PagerOpentemp(pPager, pPager->stfd, SQLITE_OPEN_SUBJOURNAL);
       
  3943     if( rc ){
       
  3944       goto stmt_begin_failed;
       
  3945     }
       
  3946     pPager->stmtOpen = 1;
       
  3947     pPager->stmtNRec = 0;
       
  3948   }
       
  3949   pPager->stmtInUse = 1;
       
  3950   return SQLITE_OK;
       
  3951  
       
  3952 stmt_begin_failed:
       
  3953   if( pPager->pInStmt ){
       
  3954     sqlite3BitvecDestroy(pPager->pInStmt);
       
  3955     pPager->pInStmt = 0;
       
  3956   }
       
  3957   return rc;
       
  3958 }
       
  3959 int sqlite3PagerStmtBegin(Pager *pPager){
       
  3960   int rc;
       
  3961   rc = pagerStmtBegin(pPager);
       
  3962   return rc;
       
  3963 }
       
  3964 
       
  3965 /*
       
  3966 ** Commit a statement.
       
  3967 */
       
  3968 int sqlite3PagerStmtCommit(Pager *pPager){
       
  3969   if( pPager->stmtInUse ){
       
  3970     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
       
  3971     if( !MEMDB ){
       
  3972       sqlite3BitvecDestroy(pPager->pInStmt);
       
  3973       pPager->pInStmt = 0;
       
  3974     }else{
       
  3975       sqlite3PcacheCommit(pPager->pPCache, 1);
       
  3976     }
       
  3977     pPager->stmtNRec = 0;
       
  3978     pPager->stmtInUse = 0;
       
  3979   }
       
  3980   pPager->stmtAutoopen = 0;
       
  3981   return SQLITE_OK;
       
  3982 }
       
  3983 
       
  3984 /*
       
  3985 ** Rollback a statement.
       
  3986 */
       
  3987 int sqlite3PagerStmtRollback(Pager *pPager){
       
  3988   int rc;
       
  3989   if( pPager->stmtInUse ){
       
  3990     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
       
  3991     if( MEMDB ){
       
  3992       sqlite3PcacheRollback(pPager->pPCache, 1, pPager->xReiniter);
       
  3993       pPager->dbSize = pPager->stmtSize;
       
  3994       pager_truncate_cache(pPager);
       
  3995       rc = SQLITE_OK;
       
  3996     }else{
       
  3997       rc = pager_stmt_playback(pPager);
       
  3998     }
       
  3999     sqlite3PagerStmtCommit(pPager);
       
  4000   }else{
       
  4001     rc = SQLITE_OK;
       
  4002   }
       
  4003   pPager->stmtAutoopen = 0;
       
  4004   return rc;
       
  4005 }
       
  4006 
       
  4007 /*
       
  4008 ** Return the full pathname of the database file.
       
  4009 */
       
  4010 const char *sqlite3PagerFilename(Pager *pPager){
       
  4011   return pPager->zFilename;
       
  4012 }
       
  4013 
       
  4014 /*
       
  4015 ** Return the VFS structure for the pager.
       
  4016 */
       
  4017 const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
       
  4018   return pPager->pVfs;
       
  4019 }
       
  4020 
       
  4021 /*
       
  4022 ** Return the file handle for the database file associated
       
  4023 ** with the pager.  This might return NULL if the file has
       
  4024 ** not yet been opened.
       
  4025 */
       
  4026 sqlite3_file *sqlite3PagerFile(Pager *pPager){
       
  4027   return pPager->fd;
       
  4028 }
       
  4029 
       
  4030 /*
       
  4031 ** Return the directory of the database file.
       
  4032 */
       
  4033 const char *sqlite3PagerDirname(Pager *pPager){
       
  4034   return pPager->zDirectory;
       
  4035 }
       
  4036 
       
  4037 /*
       
  4038 ** Return the full pathname of the journal file.
       
  4039 */
       
  4040 const char *sqlite3PagerJournalname(Pager *pPager){
       
  4041   return pPager->zJournal;
       
  4042 }
       
  4043 
       
  4044 /*
       
  4045 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
       
  4046 ** if fsync()s are executed normally.
       
  4047 */
       
  4048 int sqlite3PagerNosync(Pager *pPager){
       
  4049   return pPager->noSync;
       
  4050 }
       
  4051 
       
  4052 #ifdef SQLITE_HAS_CODEC
       
  4053 /*
       
  4054 ** Set the codec for this pager
       
  4055 */
       
  4056 void sqlite3PagerSetCodec(
       
  4057   Pager *pPager,
       
  4058   void *(*xCodec)(void*,void*,Pgno,int),
       
  4059   void *pCodecArg
       
  4060 ){
       
  4061   pPager->xCodec = xCodec;
       
  4062   pPager->pCodecArg = pCodecArg;
       
  4063 }
       
  4064 #endif
       
  4065 
       
  4066 #ifndef SQLITE_OMIT_AUTOVACUUM
       
  4067 /*
       
  4068 ** Move the page pPg to location pgno in the file.
       
  4069 **
       
  4070 ** There must be no references to the page previously located at
       
  4071 ** pgno (which we call pPgOld) though that page is allowed to be
       
  4072 ** in cache.  If the page previously located at pgno is not already
       
  4073 ** in the rollback journal, it is not put there by by this routine.
       
  4074 **
       
  4075 ** References to the page pPg remain valid. Updating any
       
  4076 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
       
  4077 ** allocated along with the page) is the responsibility of the caller.
       
  4078 **
       
  4079 ** A transaction must be active when this routine is called. It used to be
       
  4080 ** required that a statement transaction was not active, but this restriction
       
  4081 ** has been removed (CREATE INDEX needs to move a page when a statement
       
  4082 ** transaction is active).
       
  4083 **
       
  4084 ** If the fourth argument, isCommit, is non-zero, then this page is being
       
  4085 ** moved as part of a database reorganization just before the transaction 
       
  4086 ** is being committed. In this case, it is guaranteed that the database page 
       
  4087 ** pPg refers to will not be written to again within this transaction.
       
  4088 */
       
  4089 int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
       
  4090   PgHdr *pPgOld;  /* The page being overwritten. */
       
  4091   Pgno needSyncPgno = 0;
       
  4092 
       
  4093   assert( pPg->nRef>0 );
       
  4094 
       
  4095   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
       
  4096       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno);
       
  4097   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
       
  4098 
       
  4099   pager_get_content(pPg);
       
  4100 
       
  4101   /* If the journal needs to be sync()ed before page pPg->pgno can
       
  4102   ** be written to, store pPg->pgno in local variable needSyncPgno.
       
  4103   **
       
  4104   ** If the isCommit flag is set, there is no need to remember that
       
  4105   ** the journal needs to be sync()ed before database page pPg->pgno 
       
  4106   ** can be written to. The caller has already promised not to write to it.
       
  4107   */
       
  4108   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
       
  4109     needSyncPgno = pPg->pgno;
       
  4110     assert( (pPg->flags&PGHDR_IN_JOURNAL) || (int)pgno>pPager->origDbSize );
       
  4111     assert( pPg->flags&PGHDR_DIRTY );
       
  4112     assert( pPager->needSync );
       
  4113   }
       
  4114 
       
  4115   /* If the cache contains a page with page-number pgno, remove it
       
  4116   ** from its hash chain. Also, if the PgHdr.needSync was set for 
       
  4117   ** page pgno before the 'move' operation, it needs to be retained 
       
  4118   ** for the page moved there.
       
  4119   */
       
  4120   pPg->flags &= ~(PGHDR_NEED_SYNC|PGHDR_IN_JOURNAL);
       
  4121   pPgOld = pager_lookup(pPager, pgno);
       
  4122   assert( !pPgOld || pPgOld->nRef==1 );
       
  4123   if( pPgOld ){
       
  4124     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
       
  4125   }
       
  4126   if( sqlite3BitvecTest(pPager->pInJournal, pgno) ){
       
  4127     assert( !MEMDB );
       
  4128     pPg->flags |= PGHDR_IN_JOURNAL;
       
  4129   }
       
  4130 
       
  4131   sqlite3PcacheMove(pPg, pgno);
       
  4132   if( pPgOld ){
       
  4133     sqlite3PcacheMove(pPgOld, 0);
       
  4134     sqlite3PcacheRelease(pPgOld);
       
  4135   }
       
  4136 
       
  4137   makeDirty(pPg);
       
  4138   pPager->dirtyCache = 1;
       
  4139   pPager->dbModified = 1;
       
  4140 
       
  4141   if( needSyncPgno ){
       
  4142     /* If needSyncPgno is non-zero, then the journal file needs to be 
       
  4143     ** sync()ed before any data is written to database file page needSyncPgno.
       
  4144     ** Currently, no such page exists in the page-cache and the 
       
  4145     ** "is journaled" bitvec flag has been set. This needs to be remedied by
       
  4146     ** loading the page into the pager-cache and setting the PgHdr.needSync 
       
  4147     ** flag.
       
  4148     **
       
  4149     ** If the attempt to load the page into the page-cache fails, (due
       
  4150     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
       
  4151     ** array. Otherwise, if the page is loaded and written again in
       
  4152     ** this transaction, it may be written to the database file before
       
  4153     ** it is synced into the journal file. This way, it may end up in
       
  4154     ** the journal file twice, but that is not a problem.
       
  4155     **
       
  4156     ** The sqlite3PagerGet() call may cause the journal to sync. So make
       
  4157     ** sure the Pager.needSync flag is set too.
       
  4158     */
       
  4159     int rc;
       
  4160     PgHdr *pPgHdr;
       
  4161     assert( pPager->needSync );
       
  4162     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
       
  4163     if( rc!=SQLITE_OK ){
       
  4164       if( pPager->pInJournal && (int)needSyncPgno<=pPager->origDbSize ){
       
  4165         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
       
  4166       }
       
  4167       return rc;
       
  4168     }
       
  4169     pPager->needSync = 1;
       
  4170     assert( pPager->noSync==0 && !MEMDB );
       
  4171     pPgHdr->flags |= PGHDR_NEED_SYNC;
       
  4172     pPgHdr->flags |= PGHDR_IN_JOURNAL;
       
  4173     makeDirty(pPgHdr);
       
  4174     sqlite3PagerUnref(pPgHdr);
       
  4175   }
       
  4176 
       
  4177   return SQLITE_OK;
       
  4178 }
       
  4179 #endif
       
  4180 
       
  4181 /*
       
  4182 ** Return a pointer to the data for the specified page.
       
  4183 */
       
  4184 void *sqlite3PagerGetData(DbPage *pPg){
       
  4185   assert( pPg->nRef>0 || pPg->pPager->memDb );
       
  4186   return pPg->pData;
       
  4187 }
       
  4188 
       
  4189 /*
       
  4190 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
       
  4191 ** allocated along with the specified page.
       
  4192 */
       
  4193 void *sqlite3PagerGetExtra(DbPage *pPg){
       
  4194   Pager *pPager = pPg->pPager;
       
  4195   return (pPager?pPg->pExtra:0);
       
  4196 }
       
  4197 
       
  4198 /*
       
  4199 ** Get/set the locking-mode for this pager. Parameter eMode must be one
       
  4200 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
       
  4201 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
       
  4202 ** the locking-mode is set to the value specified.
       
  4203 **
       
  4204 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
       
  4205 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
       
  4206 ** locking-mode.
       
  4207 */
       
  4208 int sqlite3PagerLockingMode(Pager *pPager, int eMode){
       
  4209   assert( eMode==PAGER_LOCKINGMODE_QUERY
       
  4210             || eMode==PAGER_LOCKINGMODE_NORMAL
       
  4211             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
       
  4212   assert( PAGER_LOCKINGMODE_QUERY<0 );
       
  4213   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
       
  4214   if( eMode>=0 && !pPager->tempFile ){
       
  4215     pPager->exclusiveMode = eMode;
       
  4216   }
       
  4217   return (int)pPager->exclusiveMode;
       
  4218 }
       
  4219 
       
  4220 /*
       
  4221 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
       
  4222 **
       
  4223 **    PAGER_JOURNALMODE_QUERY
       
  4224 **    PAGER_JOURNALMODE_DELETE
       
  4225 **    PAGER_JOURNALMODE_TRUNCATE
       
  4226 **    PAGER_JOURNALMODE_PERSIST
       
  4227 **    PAGER_JOURNALMODE_OFF
       
  4228 **
       
  4229 ** If the parameter is not _QUERY, then the journal-mode is set to the
       
  4230 ** value specified.
       
  4231 **
       
  4232 ** The returned indicate the current (possibly updated)
       
  4233 ** journal-mode.
       
  4234 */
       
  4235 int sqlite3PagerJournalMode(Pager *pPager, int eMode){
       
  4236   assert( eMode==PAGER_JOURNALMODE_QUERY
       
  4237             || eMode==PAGER_JOURNALMODE_DELETE
       
  4238             || eMode==PAGER_JOURNALMODE_TRUNCATE
       
  4239             || eMode==PAGER_JOURNALMODE_PERSIST
       
  4240             || eMode==PAGER_JOURNALMODE_OFF );
       
  4241   assert( PAGER_JOURNALMODE_QUERY<0 );
       
  4242   if( eMode>=0 ){
       
  4243     pPager->journalMode = eMode;
       
  4244   }else{
       
  4245     assert( eMode==PAGER_JOURNALMODE_QUERY );
       
  4246   }
       
  4247   return (int)pPager->journalMode;
       
  4248 }
       
  4249 
       
  4250 /*
       
  4251 ** Get/set the size-limit used for persistent journal files.
       
  4252 */
       
  4253 i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
       
  4254   if( iLimit>=-1 ){
       
  4255     pPager->journalSizeLimit = iLimit;
       
  4256   }
       
  4257   return pPager->journalSizeLimit;
       
  4258 }
       
  4259 
       
  4260 #endif /* SQLITE_OMIT_DISKIO */