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