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