xref: /sqlite-3.40.0/src/pager.c (revision f2fcd075)
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 #ifndef SQLITE_OMIT_DISKIO
22 #include "sqliteInt.h"
23 #include "wal.h"
24 
25 
26 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
27 **
28 ** This comment block describes invariants that hold when using a rollback
29 ** journal.  These invariants do not apply for journal_mode=WAL,
30 ** journal_mode=MEMORY, or journal_mode=OFF.
31 **
32 ** Within this comment block, a page is deemed to have been synced
33 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
34 ** Otherwise, the page is not synced until the xSync method of the VFS
35 ** is called successfully on the file containing the page.
36 **
37 ** Definition:  A page of the database file is said to be "overwriteable" if
38 ** one or more of the following are true about the page:
39 **
40 **     (a)  The original content of the page as it was at the beginning of
41 **          the transaction has been written into the rollback journal and
42 **          synced.
43 **
44 **     (b)  The page was a freelist leaf page at the start of the transaction.
45 **
46 **     (c)  The page number is greater than the largest page that existed in
47 **          the database file at the start of the transaction.
48 **
49 ** (1) A page of the database file is never overwritten unless one of the
50 **     following are true:
51 **
52 **     (a) The page and all other pages on the same sector are overwriteable.
53 **
54 **     (b) The atomic page write optimization is enabled, and the entire
55 **         transaction other than the update of the transaction sequence
56 **         number consists of a single page change.
57 **
58 ** (2) The content of a page written into the rollback journal exactly matches
59 **     both the content in the database when the rollback journal was written
60 **     and the content in the database at the beginning of the current
61 **     transaction.
62 **
63 ** (3) Writes to the database file are an integer multiple of the page size
64 **     in length and are aligned on a page boundary.
65 **
66 ** (4) Reads from the database file are either aligned on a page boundary and
67 **     an integer multiple of the page size in length or are taken from the
68 **     first 100 bytes of the database file.
69 **
70 ** (5) All writes to the database file are synced prior to the rollback journal
71 **     being deleted, truncated, or zeroed.
72 **
73 ** (6) If a master journal file is used, then all writes to the database file
74 **     are synced prior to the master journal being deleted.
75 **
76 ** Definition: Two databases (or the same database at two points it time)
77 ** are said to be "logically equivalent" if they give the same answer to
78 ** all queries.  Note in particular the the content of freelist leaf
79 ** pages can be changed arbitarily without effecting the logical equivalence
80 ** of the database.
81 **
82 ** (7) At any time, if any subset, including the empty set and the total set,
83 **     of the unsynced changes to a rollback journal are removed and the
84 **     journal is rolled back, the resulting database file will be logical
85 **     equivalent to the database file at the beginning of the transaction.
86 **
87 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
88 **     is called to restore the database file to the same size it was at
89 **     the beginning of the transaction.  (In some VFSes, the xTruncate
90 **     method is a no-op, but that does not change the fact the SQLite will
91 **     invoke it.)
92 **
93 ** (9) Whenever the database file is modified, at least one bit in the range
94 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
95 **     the EXCLUSIVE lock, thus signaling other connections on the same
96 **     database to flush their caches.
97 **
98 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
99 **      than one billion transactions.
100 **
101 ** (11) A database file is well-formed at the beginning and at the conclusion
102 **      of every transaction.
103 **
104 ** (12) An EXCLUSIVE lock is held on the database file when writing to
105 **      the database file.
106 **
107 ** (13) A SHARED lock is held on the database file while reading any
108 **      content out of the database file.
109 **
110 ******************************************************************************/
111 
112 /*
113 ** Macros for troubleshooting.  Normally turned off
114 */
115 #if 0
116 int sqlite3PagerTrace=1;  /* True to enable tracing */
117 #define sqlite3DebugPrintf printf
118 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
119 #else
120 #define PAGERTRACE(X)
121 #endif
122 
123 /*
124 ** The following two macros are used within the PAGERTRACE() macros above
125 ** to print out file-descriptors.
126 **
127 ** PAGERID() takes a pointer to a Pager struct as its argument. The
128 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
129 ** struct as its argument.
130 */
131 #define PAGERID(p) ((int)(p->fd))
132 #define FILEHANDLEID(fd) ((int)fd)
133 
134 /*
135 ** The Pager.eState variable stores the current 'state' of a pager. A
136 ** pager may be in any one of the seven states shown in the following
137 ** state diagram.
138 **
139 **                            OPEN <------+------+
140 **                              |         |      |
141 **                              V         |      |
142 **               +---------> READER-------+      |
143 **               |              |                |
144 **               |              V                |
145 **               |<-------WRITER_LOCKED------> ERROR
146 **               |              |                ^
147 **               |              V                |
148 **               |<------WRITER_CACHEMOD-------->|
149 **               |              |                |
150 **               |              V                |
151 **               |<-------WRITER_DBMOD---------->|
152 **               |              |                |
153 **               |              V                |
154 **               +<------WRITER_FINISHED-------->+
155 **
156 **
157 ** List of state transitions and the C [function] that performs each:
158 **
159 **   OPEN              -> READER              [sqlite3PagerSharedLock]
160 **   READER            -> OPEN                [pager_unlock]
161 **
162 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
163 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
164 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
165 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
166 **   WRITER_***        -> READER              [pager_end_transaction]
167 **
168 **   WRITER_***        -> ERROR               [pager_error]
169 **   ERROR             -> OPEN                [pager_unlock]
170 **
171 **
172 **  OPEN:
173 **
174 **    The pager starts up in this state. Nothing is guaranteed in this
175 **    state - the file may or may not be locked and the database size is
176 **    unknown. The database may not be read or written.
177 **
178 **    * No read or write transaction is active.
179 **    * Any lock, or no lock at all, may be held on the database file.
180 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
181 **
182 **  READER:
183 **
184 **    In this state all the requirements for reading the database in
185 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
186 **    was) in exclusive-locking mode, a user-level read transaction is
187 **    open. The database size is known in this state.
188 **
189 **    A connection running with locking_mode=normal enters this state when
190 **    it opens a read-transaction on the database and returns to state
191 **    OPEN after the read-transaction is completed. However a connection
192 **    running in locking_mode=exclusive (including temp databases) remains in
193 **    this state even after the read-transaction is closed. The only way
194 **    a locking_mode=exclusive connection can transition from READER to OPEN
195 **    is via the ERROR state (see below).
196 **
197 **    * A read transaction may be active (but a write-transaction cannot).
198 **    * A SHARED or greater lock is held on the database file.
199 **    * The dbSize variable may be trusted (even if a user-level read
200 **      transaction is not active). The dbOrigSize and dbFileSize variables
201 **      may not be trusted at this point.
202 **    * If the database is a WAL database, then the WAL connection is open.
203 **    * Even if a read-transaction is not open, it is guaranteed that
204 **      there is no hot-journal in the file-system.
205 **
206 **  WRITER_LOCKED:
207 **
208 **    The pager moves to this state from READER when a write-transaction
209 **    is first opened on the database. In WRITER_LOCKED state, all locks
210 **    required to start a write-transaction are held, but no actual
211 **    modifications to the cache or database have taken place.
212 **
213 **    In rollback mode, a RESERVED or (if the transaction was opened with
214 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
215 **    moving to this state, but the journal file is not written to or opened
216 **    to in this state. If the transaction is committed or rolled back while
217 **    in WRITER_LOCKED state, all that is required is to unlock the database
218 **    file.
219 **
220 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
221 **    If the connection is running with locking_mode=exclusive, an attempt
222 **    is made to obtain an EXCLUSIVE lock on the database file.
223 **
224 **    * A write transaction is active.
225 **    * If the connection is open in rollback-mode, a RESERVED or greater
226 **      lock is held on the database file.
227 **    * If the connection is open in WAL-mode, a WAL write transaction
228 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
229 **      called).
230 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
231 **    * The contents of the pager cache have not been modified.
232 **    * The journal file may or may not be open.
233 **    * Nothing (not even the first header) has been written to the journal.
234 **
235 **  WRITER_CACHEMOD:
236 **
237 **    A pager moves from WRITER_LOCKED state to this state when a page is
238 **    first modified by the upper layer. In rollback mode the journal file
239 **    is opened (if it is not already open) and a header written to the
240 **    start of it. The database file on disk has not been modified.
241 **
242 **    * A write transaction is active.
243 **    * A RESERVED or greater lock is held on the database file.
244 **    * The journal file is open and the first header has been written
245 **      to it, but the header has not been synced to disk.
246 **    * The contents of the page cache have been modified.
247 **
248 **  WRITER_DBMOD:
249 **
250 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
251 **    when it modifies the contents of the database file. WAL connections
252 **    never enter this state (since they do not modify the database file,
253 **    just the log file).
254 **
255 **    * A write transaction is active.
256 **    * An EXCLUSIVE or greater lock is held on the database file.
257 **    * The journal file is open and the first header has been written
258 **      and synced to disk.
259 **    * The contents of the page cache have been modified (and possibly
260 **      written to disk).
261 **
262 **  WRITER_FINISHED:
263 **
264 **    It is not possible for a WAL connection to enter this state.
265 **
266 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
267 **    state after the entire transaction has been successfully written into the
268 **    database file. In this state the transaction may be committed simply
269 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
270 **    not possible to modify the database further. At this point, the upper
271 **    layer must either commit or rollback the transaction.
272 **
273 **    * A write transaction is active.
274 **    * An EXCLUSIVE or greater lock is held on the database file.
275 **    * All writing and syncing of journal and database data has finished.
276 **      If no error occured, all that remains is to finalize the journal to
277 **      commit the transaction. If an error did occur, the caller will need
278 **      to rollback the transaction.
279 **
280 **  ERROR:
281 **
282 **    The ERROR state is entered when an IO or disk-full error (including
283 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
284 **    difficult to be sure that the in-memory pager state (cache contents,
285 **    db size etc.) are consistent with the contents of the file-system.
286 **
287 **    Temporary pager files may enter the ERROR state, but in-memory pagers
288 **    cannot.
289 **
290 **    For example, if an IO error occurs while performing a rollback,
291 **    the contents of the page-cache may be left in an inconsistent state.
292 **    At this point it would be dangerous to change back to READER state
293 **    (as usually happens after a rollback). Any subsequent readers might
294 **    report database corruption (due to the inconsistent cache), and if
295 **    they upgrade to writers, they may inadvertently corrupt the database
296 **    file. To avoid this hazard, the pager switches into the ERROR state
297 **    instead of READER following such an error.
298 **
299 **    Once it has entered the ERROR state, any attempt to use the pager
300 **    to read or write data returns an error. Eventually, once all
301 **    outstanding transactions have been abandoned, the pager is able to
302 **    transition back to OPEN state, discarding the contents of the
303 **    page-cache and any other in-memory state at the same time. Everything
304 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
305 **    when a read-transaction is next opened on the pager (transitioning
306 **    the pager into READER state). At that point the system has recovered
307 **    from the error.
308 **
309 **    Specifically, the pager jumps into the ERROR state if:
310 **
311 **      1. An error occurs while attempting a rollback. This happens in
312 **         function sqlite3PagerRollback().
313 **
314 **      2. An error occurs while attempting to finalize a journal file
315 **         following a commit in function sqlite3PagerCommitPhaseTwo().
316 **
317 **      3. An error occurs while attempting to write to the journal or
318 **         database file in function pagerStress() in order to free up
319 **         memory.
320 **
321 **    In other cases, the error is returned to the b-tree layer. The b-tree
322 **    layer then attempts a rollback operation. If the error condition
323 **    persists, the pager enters the ERROR state via condition (1) above.
324 **
325 **    Condition (3) is necessary because it can be triggered by a read-only
326 **    statement executed within a transaction. In this case, if the error
327 **    code were simply returned to the user, the b-tree layer would not
328 **    automatically attempt a rollback, as it assumes that an error in a
329 **    read-only statement cannot leave the pager in an internally inconsistent
330 **    state.
331 **
332 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
333 **    * There are one or more outstanding references to pages (after the
334 **      last reference is dropped the pager should move back to OPEN state).
335 **    * The pager is not an in-memory pager.
336 **
337 **
338 ** Notes:
339 **
340 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
341 **     connection is open in WAL mode. A WAL connection is always in one
342 **     of the first four states.
343 **
344 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
345 **     state. There are two exceptions: immediately after exclusive-mode has
346 **     been turned on (and before any read or write transactions are
347 **     executed), and when the pager is leaving the "error state".
348 **
349 **   * See also: assert_pager_state().
350 */
351 #define PAGER_OPEN                  0
352 #define PAGER_READER                1
353 #define PAGER_WRITER_LOCKED         2
354 #define PAGER_WRITER_CACHEMOD       3
355 #define PAGER_WRITER_DBMOD          4
356 #define PAGER_WRITER_FINISHED       5
357 #define PAGER_ERROR                 6
358 
359 /*
360 ** The Pager.eLock variable is almost always set to one of the
361 ** following locking-states, according to the lock currently held on
362 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
363 ** This variable is kept up to date as locks are taken and released by
364 ** the pagerLockDb() and pagerUnlockDb() wrappers.
365 **
366 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
367 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
368 ** the operation was successful. In these circumstances pagerLockDb() and
369 ** pagerUnlockDb() take a conservative approach - eLock is always updated
370 ** when unlocking the file, and only updated when locking the file if the
371 ** VFS call is successful. This way, the Pager.eLock variable may be set
372 ** to a less exclusive (lower) value than the lock that is actually held
373 ** at the system level, but it is never set to a more exclusive value.
374 **
375 ** This is usually safe. If an xUnlock fails or appears to fail, there may
376 ** be a few redundant xLock() calls or a lock may be held for longer than
377 ** required, but nothing really goes wrong.
378 **
379 ** The exception is when the database file is unlocked as the pager moves
380 ** from ERROR to OPEN state. At this point there may be a hot-journal file
381 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
382 ** transition, by the same pager or any other). If the call to xUnlock()
383 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
384 ** can confuse the call to xCheckReservedLock() call made later as part
385 ** of hot-journal detection.
386 **
387 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
388 ** lock held by this process or any others". So xCheckReservedLock may
389 ** return true because the caller itself is holding an EXCLUSIVE lock (but
390 ** doesn't know it because of a previous error in xUnlock). If this happens
391 ** a hot-journal may be mistaken for a journal being created by an active
392 ** transaction in another process, causing SQLite to read from the database
393 ** without rolling it back.
394 **
395 ** To work around this, if a call to xUnlock() fails when unlocking the
396 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
397 ** is only changed back to a real locking state after a successful call
398 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
399 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
400 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
401 ** lock on the database file before attempting to roll it back. See function
402 ** PagerSharedLock() for more detail.
403 **
404 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
405 ** PAGER_OPEN state.
406 */
407 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
408 
409 /*
410 ** A macro used for invoking the codec if there is one
411 */
412 #ifdef SQLITE_HAS_CODEC
413 # define CODEC1(P,D,N,X,E) \
414     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
415 # define CODEC2(P,D,N,X,E,O) \
416     if( P->xCodec==0 ){ O=(char*)D; }else \
417     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
418 #else
419 # define CODEC1(P,D,N,X,E)   /* NO-OP */
420 # define CODEC2(P,D,N,X,E,O) O=(char*)D
421 #endif
422 
423 /*
424 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
425 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
426 ** This could conceivably cause corruption following a power failure on
427 ** such a system. This is currently an undocumented limit.
428 */
429 #define MAX_SECTOR_SIZE 0x10000
430 
431 /*
432 ** An instance of the following structure is allocated for each active
433 ** savepoint and statement transaction in the system. All such structures
434 ** are stored in the Pager.aSavepoint[] array, which is allocated and
435 ** resized using sqlite3Realloc().
436 **
437 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
438 ** set to 0. If a journal-header is written into the main journal while
439 ** the savepoint is active, then iHdrOffset is set to the byte offset
440 ** immediately following the last journal record written into the main
441 ** journal before the journal-header. This is required during savepoint
442 ** rollback (see pagerPlaybackSavepoint()).
443 */
444 typedef struct PagerSavepoint PagerSavepoint;
445 struct PagerSavepoint {
446   i64 iOffset;                 /* Starting offset in main journal */
447   i64 iHdrOffset;              /* See above */
448   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
449   Pgno nOrig;                  /* Original number of pages in file */
450   Pgno iSubRec;                /* Index of first record in sub-journal */
451 #ifndef SQLITE_OMIT_WAL
452   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
453 #endif
454 };
455 
456 /*
457 ** A open page cache is an instance of struct Pager. A description of
458 ** some of the more important member variables follows:
459 **
460 ** eState
461 **
462 **   The current 'state' of the pager object. See the comment and state
463 **   diagram above for a description of the pager state.
464 **
465 ** eLock
466 **
467 **   For a real on-disk database, the current lock held on the database file -
468 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
469 **
470 **   For a temporary or in-memory database (neither of which require any
471 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
472 **   databases always have Pager.exclusiveMode==1, this tricks the pager
473 **   logic into thinking that it already has all the locks it will ever
474 **   need (and no reason to release them).
475 **
476 **   In some (obscure) circumstances, this variable may also be set to
477 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
478 **   details.
479 **
480 ** changeCountDone
481 **
482 **   This boolean variable is used to make sure that the change-counter
483 **   (the 4-byte header field at byte offset 24 of the database file) is
484 **   not updated more often than necessary.
485 **
486 **   It is set to true when the change-counter field is updated, which
487 **   can only happen if an exclusive lock is held on the database file.
488 **   It is cleared (set to false) whenever an exclusive lock is
489 **   relinquished on the database file. Each time a transaction is committed,
490 **   The changeCountDone flag is inspected. If it is true, the work of
491 **   updating the change-counter is omitted for the current transaction.
492 **
493 **   This mechanism means that when running in exclusive mode, a connection
494 **   need only update the change-counter once, for the first transaction
495 **   committed.
496 **
497 ** setMaster
498 **
499 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
500 **   (or may not) specify a master-journal name to be written into the
501 **   journal file before it is synced to disk.
502 **
503 **   Whether or not a journal file contains a master-journal pointer affects
504 **   the way in which the journal file is finalized after the transaction is
505 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
506 **   If a journal file does not contain a master-journal pointer, it is
507 **   finalized by overwriting the first journal header with zeroes. If
508 **   it does contain a master-journal pointer the journal file is finalized
509 **   by truncating it to zero bytes, just as if the connection were
510 **   running in "journal_mode=truncate" mode.
511 **
512 **   Journal files that contain master journal pointers cannot be finalized
513 **   simply by overwriting the first journal-header with zeroes, as the
514 **   master journal pointer could interfere with hot-journal rollback of any
515 **   subsequently interrupted transaction that reuses the journal file.
516 **
517 **   The flag is cleared as soon as the journal file is finalized (either
518 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
519 **   journal file from being successfully finalized, the setMaster flag
520 **   is cleared anyway (and the pager will move to ERROR state).
521 **
522 ** doNotSpill, doNotSyncSpill
523 **
524 **   These two boolean variables control the behaviour of cache-spills
525 **   (calls made by the pcache module to the pagerStress() routine to
526 **   write cached data to the file-system in order to free up memory).
527 **
528 **   When doNotSpill is non-zero, writing to the database from pagerStress()
529 **   is disabled altogether. This is done in a very obscure case that
530 **   comes up during savepoint rollback that requires the pcache module
531 **   to allocate a new page to prevent the journal file from being written
532 **   while it is being traversed by code in pager_playback().
533 **
534 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
535 **   is permitted, but syncing the journal file is not. This flag is set
536 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
537 **   the database page-size in order to prevent a journal sync from happening
538 **   in between the journalling of two pages on the same sector.
539 **
540 ** subjInMemory
541 **
542 **   This is a boolean variable. If true, then any required sub-journal
543 **   is opened as an in-memory journal file. If false, then in-memory
544 **   sub-journals are only used for in-memory pager files.
545 **
546 **   This variable is updated by the upper layer each time a new
547 **   write-transaction is opened.
548 **
549 ** dbSize, dbOrigSize, dbFileSize
550 **
551 **   Variable dbSize is set to the number of pages in the database file.
552 **   It is valid in PAGER_READER and higher states (all states except for
553 **   OPEN and ERROR).
554 **
555 **   dbSize is set based on the size of the database file, which may be
556 **   larger than the size of the database (the value stored at offset
557 **   28 of the database header by the btree). If the size of the file
558 **   is not an integer multiple of the page-size, the value stored in
559 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
560 **   Except, any file that is greater than 0 bytes in size is considered
561 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
562 **   to dbSize==1).
563 **
564 **   During a write-transaction, if pages with page-numbers greater than
565 **   dbSize are modified in the cache, dbSize is updated accordingly.
566 **   Similarly, if the database is truncated using PagerTruncateImage(),
567 **   dbSize is updated.
568 **
569 **   Variables dbOrigSize and dbFileSize are valid in states
570 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
571 **   variable at the start of the transaction. It is used during rollback,
572 **   and to determine whether or not pages need to be journalled before
573 **   being modified.
574 **
575 **   Throughout a write-transaction, dbFileSize contains the size of
576 **   the file on disk in pages. It is set to a copy of dbSize when the
577 **   write-transaction is first opened, and updated when VFS calls are made
578 **   to write or truncate the database file on disk.
579 **
580 **   The only reason the dbFileSize variable is required is to suppress
581 **   unnecessary calls to xTruncate() after committing a transaction. If,
582 **   when a transaction is committed, the dbFileSize variable indicates
583 **   that the database file is larger than the database image (Pager.dbSize),
584 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
585 **   to measure the database file on disk, and then truncates it if required.
586 **   dbFileSize is not used when rolling back a transaction. In this case
587 **   pager_truncate() is called unconditionally (which means there may be
588 **   a call to xFilesize() that is not strictly required). In either case,
589 **   pager_truncate() may cause the file to become smaller or larger.
590 **
591 ** dbHintSize
592 **
593 **   The dbHintSize variable is used to limit the number of calls made to
594 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
595 **
596 **   dbHintSize is set to a copy of the dbSize variable when a
597 **   write-transaction is opened (at the same time as dbFileSize and
598 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
599 **   dbHintSize is increased to the number of pages that correspond to the
600 **   size-hint passed to the method call. See pager_write_pagelist() for
601 **   details.
602 **
603 ** errCode
604 **
605 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
606 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
607 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
608 **   sub-codes.
609 */
610 struct Pager {
611   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
612   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
613   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
614   u8 useJournal;              /* Use a rollback journal on this file */
615   u8 noReadlock;              /* Do not bother to obtain readlocks */
616   u8 noSync;                  /* Do not sync the journal if true */
617   u8 fullSync;                /* Do extra syncs of the journal for robustness */
618   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
619   u8 tempFile;                /* zFilename is a temporary file */
620   u8 readOnly;                /* True for a read-only database */
621   u8 memDb;                   /* True to inhibit all file I/O */
622 
623   /**************************************************************************
624   ** The following block contains those class members that change during
625   ** routine opertion.  Class members not in this block are either fixed
626   ** when the pager is first created or else only change when there is a
627   ** significant mode change (such as changing the page_size, locking_mode,
628   ** or the journal_mode).  From another view, these class members describe
629   ** the "state" of the pager, while other class members describe the
630   ** "configuration" of the pager.
631   */
632   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
633   u8 eLock;                   /* Current lock held on database file */
634   u8 changeCountDone;         /* Set after incrementing the change-counter */
635   u8 setMaster;               /* True if a m-j name has been written to jrnl */
636   u8 doNotSpill;              /* Do not spill the cache when non-zero */
637   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
638   u8 subjInMemory;            /* True to use in-memory sub-journals */
639   Pgno dbSize;                /* Number of pages in the database */
640   Pgno dbOrigSize;            /* dbSize before the current transaction */
641   Pgno dbFileSize;            /* Number of pages in the database file */
642   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
643   int errCode;                /* One of several kinds of errors */
644   int nRec;                   /* Pages journalled since last j-header written */
645   u32 cksumInit;              /* Quasi-random value added to every checksum */
646   u32 nSubRec;                /* Number of records written to sub-journal */
647   Bitvec *pInJournal;         /* One bit for each page in the database file */
648   sqlite3_file *fd;           /* File descriptor for database */
649   sqlite3_file *jfd;          /* File descriptor for main journal */
650   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
651   i64 journalOff;             /* Current write offset in the journal file */
652   i64 journalHdr;             /* Byte offset to previous journal header */
653   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
654   PagerSavepoint *aSavepoint; /* Array of active savepoints */
655   int nSavepoint;             /* Number of elements in aSavepoint[] */
656   char dbFileVers[16];        /* Changes whenever database file changes */
657   /*
658   ** End of the routinely-changing class members
659   ***************************************************************************/
660 
661   u16 nExtra;                 /* Add this many bytes to each in-memory page */
662   i16 nReserve;               /* Number of unused bytes at end of each page */
663   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
664   u32 sectorSize;             /* Assumed sector size during rollback */
665   int pageSize;               /* Number of bytes in a page */
666   Pgno mxPgno;                /* Maximum allowed size of the database */
667   i64 journalSizeLimit;       /* Size limit for persistent journal files */
668   char *zFilename;            /* Name of the database file */
669   char *zJournal;             /* Name of the journal file */
670   int (*xBusyHandler)(void*); /* Function to call when busy */
671   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
672 #ifdef SQLITE_TEST
673   int nHit, nMiss;            /* Cache hits and missing */
674   int nRead, nWrite;          /* Database pages read/written */
675 #endif
676   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
677 #ifdef SQLITE_HAS_CODEC
678   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
679   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
680   void (*xCodecFree)(void*);             /* Destructor for the codec */
681   void *pCodec;               /* First argument to xCodec... methods */
682 #endif
683   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
684   PCache *pPCache;            /* Pointer to page cache object */
685 #ifndef SQLITE_OMIT_WAL
686   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
687   char *zWal;                 /* File name for write-ahead log */
688 #endif
689 };
690 
691 /*
692 ** The following global variables hold counters used for
693 ** testing purposes only.  These variables do not exist in
694 ** a non-testing build.  These variables are not thread-safe.
695 */
696 #ifdef SQLITE_TEST
697 int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
698 int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
699 int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
700 # define PAGER_INCR(v)  v++
701 #else
702 # define PAGER_INCR(v)
703 #endif
704 
705 
706 
707 /*
708 ** Journal files begin with the following magic string.  The data
709 ** was obtained from /dev/random.  It is used only as a sanity check.
710 **
711 ** Since version 2.8.0, the journal format contains additional sanity
712 ** checking information.  If the power fails while the journal is being
713 ** written, semi-random garbage data might appear in the journal
714 ** file after power is restored.  If an attempt is then made
715 ** to roll the journal back, the database could be corrupted.  The additional
716 ** sanity checking data is an attempt to discover the garbage in the
717 ** journal and ignore it.
718 **
719 ** The sanity checking information for the new journal format consists
720 ** of a 32-bit checksum on each page of data.  The checksum covers both
721 ** the page number and the pPager->pageSize bytes of data for the page.
722 ** This cksum is initialized to a 32-bit random value that appears in the
723 ** journal file right after the header.  The random initializer is important,
724 ** because garbage data that appears at the end of a journal is likely
725 ** data that was once in other files that have now been deleted.  If the
726 ** garbage data came from an obsolete journal file, the checksums might
727 ** be correct.  But by initializing the checksum to random value which
728 ** is different for every journal, we minimize that risk.
729 */
730 static const unsigned char aJournalMagic[] = {
731   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
732 };
733 
734 /*
735 ** The size of the of each page record in the journal is given by
736 ** the following macro.
737 */
738 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
739 
740 /*
741 ** The journal header size for this pager. This is usually the same
742 ** size as a single disk sector. See also setSectorSize().
743 */
744 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
745 
746 /*
747 ** The macro MEMDB is true if we are dealing with an in-memory database.
748 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
749 ** the value of MEMDB will be a constant and the compiler will optimize
750 ** out code that would never execute.
751 */
752 #ifdef SQLITE_OMIT_MEMORYDB
753 # define MEMDB 0
754 #else
755 # define MEMDB pPager->memDb
756 #endif
757 
758 /*
759 ** The maximum legal page number is (2^31 - 1).
760 */
761 #define PAGER_MAX_PGNO 2147483647
762 
763 /*
764 ** The argument to this macro is a file descriptor (type sqlite3_file*).
765 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
766 **
767 ** This is so that expressions can be written as:
768 **
769 **   if( isOpen(pPager->jfd) ){ ...
770 **
771 ** instead of
772 **
773 **   if( pPager->jfd->pMethods ){ ...
774 */
775 #define isOpen(pFd) ((pFd)->pMethods)
776 
777 /*
778 ** Return true if this pager uses a write-ahead log instead of the usual
779 ** rollback journal. Otherwise false.
780 */
781 #ifndef SQLITE_OMIT_WAL
782 static int pagerUseWal(Pager *pPager){
783   return (pPager->pWal!=0);
784 }
785 #else
786 # define pagerUseWal(x) 0
787 # define pagerRollbackWal(x) 0
788 # define pagerWalFrames(v,w,x,y,z) 0
789 # define pagerOpenWalIfPresent(z) SQLITE_OK
790 # define pagerBeginReadTransaction(z) SQLITE_OK
791 #endif
792 
793 #ifndef NDEBUG
794 /*
795 ** Usage:
796 **
797 **   assert( assert_pager_state(pPager) );
798 **
799 ** This function runs many asserts to try to find inconsistencies in
800 ** the internal state of the Pager object.
801 */
802 static int assert_pager_state(Pager *p){
803   Pager *pPager = p;
804 
805   /* State must be valid. */
806   assert( p->eState==PAGER_OPEN
807        || p->eState==PAGER_READER
808        || p->eState==PAGER_WRITER_LOCKED
809        || p->eState==PAGER_WRITER_CACHEMOD
810        || p->eState==PAGER_WRITER_DBMOD
811        || p->eState==PAGER_WRITER_FINISHED
812        || p->eState==PAGER_ERROR
813   );
814 
815   /* Regardless of the current state, a temp-file connection always behaves
816   ** as if it has an exclusive lock on the database file. It never updates
817   ** the change-counter field, so the changeCountDone flag is always set.
818   */
819   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
820   assert( p->tempFile==0 || pPager->changeCountDone );
821 
822   /* If the useJournal flag is clear, the journal-mode must be "OFF".
823   ** And if the journal-mode is "OFF", the journal file must not be open.
824   */
825   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
826   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
827 
828   /* Check that MEMDB implies noSync. And an in-memory journal. Since
829   ** this means an in-memory pager performs no IO at all, it cannot encounter
830   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
831   ** a journal file. (although the in-memory journal implementation may
832   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
833   ** is therefore not possible for an in-memory pager to enter the ERROR
834   ** state.
835   */
836   if( MEMDB ){
837     assert( p->noSync );
838     assert( p->journalMode==PAGER_JOURNALMODE_OFF
839          || p->journalMode==PAGER_JOURNALMODE_MEMORY
840     );
841     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
842     assert( pagerUseWal(p)==0 );
843   }
844 
845   /* If changeCountDone is set, a RESERVED lock or greater must be held
846   ** on the file.
847   */
848   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
849   assert( p->eLock!=PENDING_LOCK );
850 
851   switch( p->eState ){
852     case PAGER_OPEN:
853       assert( !MEMDB );
854       assert( pPager->errCode==SQLITE_OK );
855       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
856       break;
857 
858     case PAGER_READER:
859       assert( pPager->errCode==SQLITE_OK );
860       assert( p->eLock!=UNKNOWN_LOCK );
861       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
862       break;
863 
864     case PAGER_WRITER_LOCKED:
865       assert( p->eLock!=UNKNOWN_LOCK );
866       assert( pPager->errCode==SQLITE_OK );
867       if( !pagerUseWal(pPager) ){
868         assert( p->eLock>=RESERVED_LOCK );
869       }
870       assert( pPager->dbSize==pPager->dbOrigSize );
871       assert( pPager->dbOrigSize==pPager->dbFileSize );
872       assert( pPager->dbOrigSize==pPager->dbHintSize );
873       assert( pPager->setMaster==0 );
874       break;
875 
876     case PAGER_WRITER_CACHEMOD:
877       assert( p->eLock!=UNKNOWN_LOCK );
878       assert( pPager->errCode==SQLITE_OK );
879       if( !pagerUseWal(pPager) ){
880         /* It is possible that if journal_mode=wal here that neither the
881         ** journal file nor the WAL file are open. This happens during
882         ** a rollback transaction that switches from journal_mode=off
883         ** to journal_mode=wal.
884         */
885         assert( p->eLock>=RESERVED_LOCK );
886         assert( isOpen(p->jfd)
887              || p->journalMode==PAGER_JOURNALMODE_OFF
888              || p->journalMode==PAGER_JOURNALMODE_WAL
889         );
890       }
891       assert( pPager->dbOrigSize==pPager->dbFileSize );
892       assert( pPager->dbOrigSize==pPager->dbHintSize );
893       break;
894 
895     case PAGER_WRITER_DBMOD:
896       assert( p->eLock==EXCLUSIVE_LOCK );
897       assert( pPager->errCode==SQLITE_OK );
898       assert( !pagerUseWal(pPager) );
899       assert( p->eLock>=EXCLUSIVE_LOCK );
900       assert( isOpen(p->jfd)
901            || p->journalMode==PAGER_JOURNALMODE_OFF
902            || p->journalMode==PAGER_JOURNALMODE_WAL
903       );
904       assert( pPager->dbOrigSize<=pPager->dbHintSize );
905       break;
906 
907     case PAGER_WRITER_FINISHED:
908       assert( p->eLock==EXCLUSIVE_LOCK );
909       assert( pPager->errCode==SQLITE_OK );
910       assert( !pagerUseWal(pPager) );
911       assert( isOpen(p->jfd)
912            || p->journalMode==PAGER_JOURNALMODE_OFF
913            || p->journalMode==PAGER_JOURNALMODE_WAL
914       );
915       break;
916 
917     case PAGER_ERROR:
918       /* There must be at least one outstanding reference to the pager if
919       ** in ERROR state. Otherwise the pager should have already dropped
920       ** back to OPEN state.
921       */
922       assert( pPager->errCode!=SQLITE_OK );
923       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
924       break;
925   }
926 
927   return 1;
928 }
929 
930 /*
931 ** Return a pointer to a human readable string in a static buffer
932 ** containing the state of the Pager object passed as an argument. This
933 ** is intended to be used within debuggers. For example, as an alternative
934 ** to "print *pPager" in gdb:
935 **
936 ** (gdb) printf "%s", print_pager_state(pPager)
937 */
938 static char *print_pager_state(Pager *p){
939   static char zRet[1024];
940 
941   sqlite3_snprintf(1024, zRet,
942       "Filename:      %s\n"
943       "State:         %s errCode=%d\n"
944       "Lock:          %s\n"
945       "Locking mode:  locking_mode=%s\n"
946       "Journal mode:  journal_mode=%s\n"
947       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
948       "Journal:       journalOff=%lld journalHdr=%lld\n"
949       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
950       , p->zFilename
951       , p->eState==PAGER_OPEN            ? "OPEN" :
952         p->eState==PAGER_READER          ? "READER" :
953         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
954         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
955         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
956         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
957         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
958       , (int)p->errCode
959       , p->eLock==NO_LOCK         ? "NO_LOCK" :
960         p->eLock==RESERVED_LOCK   ? "RESERVED" :
961         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
962         p->eLock==SHARED_LOCK     ? "SHARED" :
963         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
964       , p->exclusiveMode ? "exclusive" : "normal"
965       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
966         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
967         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
968         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
969         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
970         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
971       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
972       , p->journalOff, p->journalHdr
973       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
974   );
975 
976   return zRet;
977 }
978 #endif
979 
980 /*
981 ** Return true if it is necessary to write page *pPg into the sub-journal.
982 ** A page needs to be written into the sub-journal if there exists one
983 ** or more open savepoints for which:
984 **
985 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
986 **   * The bit corresponding to the page-number is not set in
987 **     PagerSavepoint.pInSavepoint.
988 */
989 static int subjRequiresPage(PgHdr *pPg){
990   Pgno pgno = pPg->pgno;
991   Pager *pPager = pPg->pPager;
992   int i;
993   for(i=0; i<pPager->nSavepoint; i++){
994     PagerSavepoint *p = &pPager->aSavepoint[i];
995     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
996       return 1;
997     }
998   }
999   return 0;
1000 }
1001 
1002 /*
1003 ** Return true if the page is already in the journal file.
1004 */
1005 static int pageInJournal(PgHdr *pPg){
1006   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
1007 }
1008 
1009 /*
1010 ** Read a 32-bit integer from the given file descriptor.  Store the integer
1011 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
1012 ** error code is something goes wrong.
1013 **
1014 ** All values are stored on disk as big-endian.
1015 */
1016 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
1017   unsigned char ac[4];
1018   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
1019   if( rc==SQLITE_OK ){
1020     *pRes = sqlite3Get4byte(ac);
1021   }
1022   return rc;
1023 }
1024 
1025 /*
1026 ** Write a 32-bit integer into a string buffer in big-endian byte order.
1027 */
1028 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
1029 
1030 
1031 /*
1032 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
1033 ** on success or an error code is something goes wrong.
1034 */
1035 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
1036   char ac[4];
1037   put32bits(ac, val);
1038   return sqlite3OsWrite(fd, ac, 4, offset);
1039 }
1040 
1041 /*
1042 ** Unlock the database file to level eLock, which must be either NO_LOCK
1043 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
1044 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
1045 **
1046 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
1047 ** called, do not modify it. See the comment above the #define of
1048 ** UNKNOWN_LOCK for an explanation of this.
1049 */
1050 static int pagerUnlockDb(Pager *pPager, int eLock){
1051   int rc = SQLITE_OK;
1052 
1053   assert( !pPager->exclusiveMode );
1054   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
1055   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
1056   if( isOpen(pPager->fd) ){
1057     assert( pPager->eLock>=eLock );
1058     rc = sqlite3OsUnlock(pPager->fd, eLock);
1059     if( pPager->eLock!=UNKNOWN_LOCK ){
1060       pPager->eLock = (u8)eLock;
1061     }
1062     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
1063   }
1064   return rc;
1065 }
1066 
1067 /*
1068 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
1069 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
1070 ** Pager.eLock variable to the new locking state.
1071 **
1072 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
1073 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
1074 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
1075 ** of this.
1076 */
1077 static int pagerLockDb(Pager *pPager, int eLock){
1078   int rc = SQLITE_OK;
1079 
1080   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
1081   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
1082     rc = sqlite3OsLock(pPager->fd, eLock);
1083     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
1084       pPager->eLock = (u8)eLock;
1085       IOTRACE(("LOCK %p %d\n", pPager, eLock))
1086     }
1087   }
1088   return rc;
1089 }
1090 
1091 /*
1092 ** This function determines whether or not the atomic-write optimization
1093 ** can be used with this pager. The optimization can be used if:
1094 **
1095 **  (a) the value returned by OsDeviceCharacteristics() indicates that
1096 **      a database page may be written atomically, and
1097 **  (b) the value returned by OsSectorSize() is less than or equal
1098 **      to the page size.
1099 **
1100 ** The optimization is also always enabled for temporary files. It is
1101 ** an error to call this function if pPager is opened on an in-memory
1102 ** database.
1103 **
1104 ** If the optimization cannot be used, 0 is returned. If it can be used,
1105 ** then the value returned is the size of the journal file when it
1106 ** contains rollback data for exactly one page.
1107 */
1108 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
1109 static int jrnlBufferSize(Pager *pPager){
1110   assert( !MEMDB );
1111   if( !pPager->tempFile ){
1112     int dc;                           /* Device characteristics */
1113     int nSector;                      /* Sector size */
1114     int szPage;                       /* Page size */
1115 
1116     assert( isOpen(pPager->fd) );
1117     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
1118     nSector = pPager->sectorSize;
1119     szPage = pPager->pageSize;
1120 
1121     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
1122     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
1123     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
1124       return 0;
1125     }
1126   }
1127 
1128   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
1129 }
1130 #endif
1131 
1132 /*
1133 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
1134 ** on the cache using a hash function.  This is used for testing
1135 ** and debugging only.
1136 */
1137 #ifdef SQLITE_CHECK_PAGES
1138 /*
1139 ** Return a 32-bit hash of the page data for pPage.
1140 */
1141 static u32 pager_datahash(int nByte, unsigned char *pData){
1142   u32 hash = 0;
1143   int i;
1144   for(i=0; i<nByte; i++){
1145     hash = (hash*1039) + pData[i];
1146   }
1147   return hash;
1148 }
1149 static u32 pager_pagehash(PgHdr *pPage){
1150   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
1151 }
1152 static void pager_set_pagehash(PgHdr *pPage){
1153   pPage->pageHash = pager_pagehash(pPage);
1154 }
1155 
1156 /*
1157 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
1158 ** is defined, and NDEBUG is not defined, an assert() statement checks
1159 ** that the page is either dirty or still matches the calculated page-hash.
1160 */
1161 #define CHECK_PAGE(x) checkPage(x)
1162 static void checkPage(PgHdr *pPg){
1163   Pager *pPager = pPg->pPager;
1164   assert( pPager->eState!=PAGER_ERROR );
1165   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
1166 }
1167 
1168 #else
1169 #define pager_datahash(X,Y)  0
1170 #define pager_pagehash(X)  0
1171 #define pager_set_pagehash(X)
1172 #define CHECK_PAGE(x)
1173 #endif  /* SQLITE_CHECK_PAGES */
1174 
1175 /*
1176 ** When this is called the journal file for pager pPager must be open.
1177 ** This function attempts to read a master journal file name from the
1178 ** end of the file and, if successful, copies it into memory supplied
1179 ** by the caller. See comments above writeMasterJournal() for the format
1180 ** used to store a master journal file name at the end of a journal file.
1181 **
1182 ** zMaster must point to a buffer of at least nMaster bytes allocated by
1183 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
1184 ** enough space to write the master journal name). If the master journal
1185 ** name in the journal is longer than nMaster bytes (including a
1186 ** nul-terminator), then this is handled as if no master journal name
1187 ** were present in the journal.
1188 **
1189 ** If a master journal file name is present at the end of the journal
1190 ** file, then it is copied into the buffer pointed to by zMaster. A
1191 ** nul-terminator byte is appended to the buffer following the master
1192 ** journal file name.
1193 **
1194 ** If it is determined that no master journal file name is present
1195 ** zMaster[0] is set to 0 and SQLITE_OK returned.
1196 **
1197 ** If an error occurs while reading from the journal file, an SQLite
1198 ** error code is returned.
1199 */
1200 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
1201   int rc;                    /* Return code */
1202   u32 len;                   /* Length in bytes of master journal name */
1203   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
1204   u32 cksum;                 /* MJ checksum value read from journal */
1205   u32 u;                     /* Unsigned loop counter */
1206   unsigned char aMagic[8];   /* A buffer to hold the magic header */
1207   zMaster[0] = '\0';
1208 
1209   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
1210    || szJ<16
1211    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
1212    || len>=nMaster
1213    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
1214    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
1215    || memcmp(aMagic, aJournalMagic, 8)
1216    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
1217   ){
1218     return rc;
1219   }
1220 
1221   /* See if the checksum matches the master journal name */
1222   for(u=0; u<len; u++){
1223     cksum -= zMaster[u];
1224   }
1225   if( cksum ){
1226     /* If the checksum doesn't add up, then one or more of the disk sectors
1227     ** containing the master journal filename is corrupted. This means
1228     ** definitely roll back, so just return SQLITE_OK and report a (nul)
1229     ** master-journal filename.
1230     */
1231     len = 0;
1232   }
1233   zMaster[len] = '\0';
1234 
1235   return SQLITE_OK;
1236 }
1237 
1238 /*
1239 ** Return the offset of the sector boundary at or immediately
1240 ** following the value in pPager->journalOff, assuming a sector
1241 ** size of pPager->sectorSize bytes.
1242 **
1243 ** i.e for a sector size of 512:
1244 **
1245 **   Pager.journalOff          Return value
1246 **   ---------------------------------------
1247 **   0                         0
1248 **   512                       512
1249 **   100                       512
1250 **   2000                      2048
1251 **
1252 */
1253 static i64 journalHdrOffset(Pager *pPager){
1254   i64 offset = 0;
1255   i64 c = pPager->journalOff;
1256   if( c ){
1257     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
1258   }
1259   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
1260   assert( offset>=c );
1261   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
1262   return offset;
1263 }
1264 
1265 /*
1266 ** The journal file must be open when this function is called.
1267 **
1268 ** This function is a no-op if the journal file has not been written to
1269 ** within the current transaction (i.e. if Pager.journalOff==0).
1270 **
1271 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
1272 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
1273 ** zero the 28-byte header at the start of the journal file. In either case,
1274 ** if the pager is not in no-sync mode, sync the journal file immediately
1275 ** after writing or truncating it.
1276 **
1277 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
1278 ** following the truncation or zeroing described above the size of the
1279 ** journal file in bytes is larger than this value, then truncate the
1280 ** journal file to Pager.journalSizeLimit bytes. The journal file does
1281 ** not need to be synced following this operation.
1282 **
1283 ** If an IO error occurs, abandon processing and return the IO error code.
1284 ** Otherwise, return SQLITE_OK.
1285 */
1286 static int zeroJournalHdr(Pager *pPager, int doTruncate){
1287   int rc = SQLITE_OK;                               /* Return code */
1288   assert( isOpen(pPager->jfd) );
1289   if( pPager->journalOff ){
1290     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
1291 
1292     IOTRACE(("JZEROHDR %p\n", pPager))
1293     if( doTruncate || iLimit==0 ){
1294       rc = sqlite3OsTruncate(pPager->jfd, 0);
1295     }else{
1296       static const char zeroHdr[28] = {0};
1297       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
1298     }
1299     if( rc==SQLITE_OK && !pPager->noSync ){
1300       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
1301     }
1302 
1303     /* At this point the transaction is committed but the write lock
1304     ** is still held on the file. If there is a size limit configured for
1305     ** the persistent journal and the journal file currently consumes more
1306     ** space than that limit allows for, truncate it now. There is no need
1307     ** to sync the file following this operation.
1308     */
1309     if( rc==SQLITE_OK && iLimit>0 ){
1310       i64 sz;
1311       rc = sqlite3OsFileSize(pPager->jfd, &sz);
1312       if( rc==SQLITE_OK && sz>iLimit ){
1313         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
1314       }
1315     }
1316   }
1317   return rc;
1318 }
1319 
1320 /*
1321 ** The journal file must be open when this routine is called. A journal
1322 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
1323 ** current location.
1324 **
1325 ** The format for the journal header is as follows:
1326 ** - 8 bytes: Magic identifying journal format.
1327 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
1328 ** - 4 bytes: Random number used for page hash.
1329 ** - 4 bytes: Initial database page count.
1330 ** - 4 bytes: Sector size used by the process that wrote this journal.
1331 ** - 4 bytes: Database page size.
1332 **
1333 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
1334 */
1335 static int writeJournalHdr(Pager *pPager){
1336   int rc = SQLITE_OK;                 /* Return code */
1337   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
1338   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
1339   u32 nWrite;                         /* Bytes of header sector written */
1340   int ii;                             /* Loop counter */
1341 
1342   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
1343 
1344   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
1345     nHeader = JOURNAL_HDR_SZ(pPager);
1346   }
1347 
1348   /* If there are active savepoints and any of them were created
1349   ** since the most recent journal header was written, update the
1350   ** PagerSavepoint.iHdrOffset fields now.
1351   */
1352   for(ii=0; ii<pPager->nSavepoint; ii++){
1353     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
1354       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
1355     }
1356   }
1357 
1358   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
1359 
1360   /*
1361   ** Write the nRec Field - the number of page records that follow this
1362   ** journal header. Normally, zero is written to this value at this time.
1363   ** After the records are added to the journal (and the journal synced,
1364   ** if in full-sync mode), the zero is overwritten with the true number
1365   ** of records (see syncJournal()).
1366   **
1367   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
1368   ** reading the journal this value tells SQLite to assume that the
1369   ** rest of the journal file contains valid page records. This assumption
1370   ** is dangerous, as if a failure occurred whilst writing to the journal
1371   ** file it may contain some garbage data. There are two scenarios
1372   ** where this risk can be ignored:
1373   **
1374   **   * When the pager is in no-sync mode. Corruption can follow a
1375   **     power failure in this case anyway.
1376   **
1377   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
1378   **     that garbage data is never appended to the journal file.
1379   */
1380   assert( isOpen(pPager->fd) || pPager->noSync );
1381   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
1382    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
1383   ){
1384     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
1385     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
1386   }else{
1387     memset(zHeader, 0, sizeof(aJournalMagic)+4);
1388   }
1389 
1390   /* The random check-hash initialiser */
1391   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
1392   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
1393   /* The initial database size */
1394   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
1395   /* The assumed sector size for this process */
1396   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
1397 
1398   /* The page size */
1399   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
1400 
1401   /* Initializing the tail of the buffer is not necessary.  Everything
1402   ** works find if the following memset() is omitted.  But initializing
1403   ** the memory prevents valgrind from complaining, so we are willing to
1404   ** take the performance hit.
1405   */
1406   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
1407          nHeader-(sizeof(aJournalMagic)+20));
1408 
1409   /* In theory, it is only necessary to write the 28 bytes that the
1410   ** journal header consumes to the journal file here. Then increment the
1411   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
1412   ** record is written to the following sector (leaving a gap in the file
1413   ** that will be implicitly filled in by the OS).
1414   **
1415   ** However it has been discovered that on some systems this pattern can
1416   ** be significantly slower than contiguously writing data to the file,
1417   ** even if that means explicitly writing data to the block of
1418   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
1419   ** is done.
1420   **
1421   ** The loop is required here in case the sector-size is larger than the
1422   ** database page size. Since the zHeader buffer is only Pager.pageSize
1423   ** bytes in size, more than one call to sqlite3OsWrite() may be required
1424   ** to populate the entire journal header sector.
1425   */
1426   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
1427     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
1428     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
1429     assert( pPager->journalHdr <= pPager->journalOff );
1430     pPager->journalOff += nHeader;
1431   }
1432 
1433   return rc;
1434 }
1435 
1436 /*
1437 ** The journal file must be open when this is called. A journal header file
1438 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
1439 ** file. The current location in the journal file is given by
1440 ** pPager->journalOff. See comments above function writeJournalHdr() for
1441 ** a description of the journal header format.
1442 **
1443 ** If the header is read successfully, *pNRec is set to the number of
1444 ** page records following this header and *pDbSize is set to the size of the
1445 ** database before the transaction began, in pages. Also, pPager->cksumInit
1446 ** is set to the value read from the journal header. SQLITE_OK is returned
1447 ** in this case.
1448 **
1449 ** If the journal header file appears to be corrupted, SQLITE_DONE is
1450 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
1451 ** cannot be read from the journal file an error code is returned.
1452 */
1453 static int readJournalHdr(
1454   Pager *pPager,               /* Pager object */
1455   int isHot,
1456   i64 journalSize,             /* Size of the open journal file in bytes */
1457   u32 *pNRec,                  /* OUT: Value read from the nRec field */
1458   u32 *pDbSize                 /* OUT: Value of original database size field */
1459 ){
1460   int rc;                      /* Return code */
1461   unsigned char aMagic[8];     /* A buffer to hold the magic header */
1462   i64 iHdrOff;                 /* Offset of journal header being read */
1463 
1464   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
1465 
1466   /* Advance Pager.journalOff to the start of the next sector. If the
1467   ** journal file is too small for there to be a header stored at this
1468   ** point, return SQLITE_DONE.
1469   */
1470   pPager->journalOff = journalHdrOffset(pPager);
1471   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
1472     return SQLITE_DONE;
1473   }
1474   iHdrOff = pPager->journalOff;
1475 
1476   /* Read in the first 8 bytes of the journal header. If they do not match
1477   ** the  magic string found at the start of each journal header, return
1478   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
1479   ** proceed.
1480   */
1481   if( isHot || iHdrOff!=pPager->journalHdr ){
1482     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
1483     if( rc ){
1484       return rc;
1485     }
1486     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
1487       return SQLITE_DONE;
1488     }
1489   }
1490 
1491   /* Read the first three 32-bit fields of the journal header: The nRec
1492   ** field, the checksum-initializer and the database size at the start
1493   ** of the transaction. Return an error code if anything goes wrong.
1494   */
1495   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
1496    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
1497    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
1498   ){
1499     return rc;
1500   }
1501 
1502   if( pPager->journalOff==0 ){
1503     u32 iPageSize;               /* Page-size field of journal header */
1504     u32 iSectorSize;             /* Sector-size field of journal header */
1505 
1506     /* Read the page-size and sector-size journal header fields. */
1507     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
1508      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
1509     ){
1510       return rc;
1511     }
1512 
1513     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
1514     ** journal header to zero. In this case, assume that the Pager.pageSize
1515     ** variable is already set to the correct page size.
1516     */
1517     if( iPageSize==0 ){
1518       iPageSize = pPager->pageSize;
1519     }
1520 
1521     /* Check that the values read from the page-size and sector-size fields
1522     ** are within range. To be 'in range', both values need to be a power
1523     ** of two greater than or equal to 512 or 32, and not greater than their
1524     ** respective compile time maximum limits.
1525     */
1526     if( iPageSize<512                  || iSectorSize<32
1527      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
1528      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
1529     ){
1530       /* If the either the page-size or sector-size in the journal-header is
1531       ** invalid, then the process that wrote the journal-header must have
1532       ** crashed before the header was synced. In this case stop reading
1533       ** the journal file here.
1534       */
1535       return SQLITE_DONE;
1536     }
1537 
1538     /* Update the page-size to match the value read from the journal.
1539     ** Use a testcase() macro to make sure that malloc failure within
1540     ** PagerSetPagesize() is tested.
1541     */
1542     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
1543     testcase( rc!=SQLITE_OK );
1544 
1545     /* Update the assumed sector-size to match the value used by
1546     ** the process that created this journal. If this journal was
1547     ** created by a process other than this one, then this routine
1548     ** is being called from within pager_playback(). The local value
1549     ** of Pager.sectorSize is restored at the end of that routine.
1550     */
1551     pPager->sectorSize = iSectorSize;
1552   }
1553 
1554   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
1555   return rc;
1556 }
1557 
1558 
1559 /*
1560 ** Write the supplied master journal name into the journal file for pager
1561 ** pPager at the current location. The master journal name must be the last
1562 ** thing written to a journal file. If the pager is in full-sync mode, the
1563 ** journal file descriptor is advanced to the next sector boundary before
1564 ** anything is written. The format is:
1565 **
1566 **   + 4 bytes: PAGER_MJ_PGNO.
1567 **   + N bytes: Master journal filename in utf-8.
1568 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
1569 **   + 4 bytes: Master journal name checksum.
1570 **   + 8 bytes: aJournalMagic[].
1571 **
1572 ** The master journal page checksum is the sum of the bytes in the master
1573 ** journal name, where each byte is interpreted as a signed 8-bit integer.
1574 **
1575 ** If zMaster is a NULL pointer (occurs for a single database transaction),
1576 ** this call is a no-op.
1577 */
1578 static int writeMasterJournal(Pager *pPager, const char *zMaster){
1579   int rc;                          /* Return code */
1580   int nMaster;                     /* Length of string zMaster */
1581   i64 iHdrOff;                     /* Offset of header in journal file */
1582   i64 jrnlSize;                    /* Size of journal file on disk */
1583   u32 cksum = 0;                   /* Checksum of string zMaster */
1584 
1585   assert( pPager->setMaster==0 );
1586   assert( !pagerUseWal(pPager) );
1587 
1588   if( !zMaster
1589    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
1590    || pPager->journalMode==PAGER_JOURNALMODE_OFF
1591   ){
1592     return SQLITE_OK;
1593   }
1594   pPager->setMaster = 1;
1595   assert( isOpen(pPager->jfd) );
1596   assert( pPager->journalHdr <= pPager->journalOff );
1597 
1598   /* Calculate the length in bytes and the checksum of zMaster */
1599   for(nMaster=0; zMaster[nMaster]; nMaster++){
1600     cksum += zMaster[nMaster];
1601   }
1602 
1603   /* If in full-sync mode, advance to the next disk sector before writing
1604   ** the master journal name. This is in case the previous page written to
1605   ** the journal has already been synced.
1606   */
1607   if( pPager->fullSync ){
1608     pPager->journalOff = journalHdrOffset(pPager);
1609   }
1610   iHdrOff = pPager->journalOff;
1611 
1612   /* Write the master journal data to the end of the journal file. If
1613   ** an error occurs, return the error code to the caller.
1614   */
1615   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
1616    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
1617    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
1618    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
1619    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
1620   ){
1621     return rc;
1622   }
1623   pPager->journalOff += (nMaster+20);
1624 
1625   /* If the pager is in peristent-journal mode, then the physical
1626   ** journal-file may extend past the end of the master-journal name
1627   ** and 8 bytes of magic data just written to the file. This is
1628   ** dangerous because the code to rollback a hot-journal file
1629   ** will not be able to find the master-journal name to determine
1630   ** whether or not the journal is hot.
1631   **
1632   ** Easiest thing to do in this scenario is to truncate the journal
1633   ** file to the required size.
1634   */
1635   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
1636    && jrnlSize>pPager->journalOff
1637   ){
1638     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
1639   }
1640   return rc;
1641 }
1642 
1643 /*
1644 ** Find a page in the hash table given its page number. Return
1645 ** a pointer to the page or NULL if the requested page is not
1646 ** already in memory.
1647 */
1648 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
1649   PgHdr *p;                         /* Return value */
1650 
1651   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
1652   ** fail, since no attempt to allocate dynamic memory will be made.
1653   */
1654   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
1655   return p;
1656 }
1657 
1658 /*
1659 ** Discard the entire contents of the in-memory page-cache.
1660 */
1661 static void pager_reset(Pager *pPager){
1662   sqlite3BackupRestart(pPager->pBackup);
1663   sqlite3PcacheClear(pPager->pPCache);
1664 }
1665 
1666 /*
1667 ** Free all structures in the Pager.aSavepoint[] array and set both
1668 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
1669 ** if it is open and the pager is not in exclusive mode.
1670 */
1671 static void releaseAllSavepoints(Pager *pPager){
1672   int ii;               /* Iterator for looping through Pager.aSavepoint */
1673   for(ii=0; ii<pPager->nSavepoint; ii++){
1674     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
1675   }
1676   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
1677     sqlite3OsClose(pPager->sjfd);
1678   }
1679   sqlite3_free(pPager->aSavepoint);
1680   pPager->aSavepoint = 0;
1681   pPager->nSavepoint = 0;
1682   pPager->nSubRec = 0;
1683 }
1684 
1685 /*
1686 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
1687 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
1688 ** or SQLITE_NOMEM if a malloc failure occurs.
1689 */
1690 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
1691   int ii;                   /* Loop counter */
1692   int rc = SQLITE_OK;       /* Result code */
1693 
1694   for(ii=0; ii<pPager->nSavepoint; ii++){
1695     PagerSavepoint *p = &pPager->aSavepoint[ii];
1696     if( pgno<=p->nOrig ){
1697       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
1698       testcase( rc==SQLITE_NOMEM );
1699       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
1700     }
1701   }
1702   return rc;
1703 }
1704 
1705 /*
1706 ** This function is a no-op if the pager is in exclusive mode and not
1707 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
1708 ** state.
1709 **
1710 ** If the pager is not in exclusive-access mode, the database file is
1711 ** completely unlocked. If the file is unlocked and the file-system does
1712 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
1713 ** closed (if it is open).
1714 **
1715 ** If the pager is in ERROR state when this function is called, the
1716 ** contents of the pager cache are discarded before switching back to
1717 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
1718 ** or not, any journal file left in the file-system will be treated
1719 ** as a hot-journal and rolled back the next time a read-transaction
1720 ** is opened (by this or by any other connection).
1721 */
1722 static void pager_unlock(Pager *pPager){
1723 
1724   assert( pPager->eState==PAGER_READER
1725        || pPager->eState==PAGER_OPEN
1726        || pPager->eState==PAGER_ERROR
1727   );
1728 
1729   sqlite3BitvecDestroy(pPager->pInJournal);
1730   pPager->pInJournal = 0;
1731   releaseAllSavepoints(pPager);
1732 
1733   if( pagerUseWal(pPager) ){
1734     assert( !isOpen(pPager->jfd) );
1735     sqlite3WalEndReadTransaction(pPager->pWal);
1736     pPager->eState = PAGER_OPEN;
1737   }else if( !pPager->exclusiveMode ){
1738     int rc;                       /* Error code returned by pagerUnlockDb() */
1739     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
1740 
1741     /* If the operating system support deletion of open files, then
1742     ** close the journal file when dropping the database lock.  Otherwise
1743     ** another connection with journal_mode=delete might delete the file
1744     ** out from under us.
1745     */
1746     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
1747     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
1748     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
1749     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
1750     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
1751     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
1752     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
1753      || 1!=(pPager->journalMode & 5)
1754     ){
1755       sqlite3OsClose(pPager->jfd);
1756     }
1757 
1758     /* If the pager is in the ERROR state and the call to unlock the database
1759     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
1760     ** above the #define for UNKNOWN_LOCK for an explanation of why this
1761     ** is necessary.
1762     */
1763     rc = pagerUnlockDb(pPager, NO_LOCK);
1764     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
1765       pPager->eLock = UNKNOWN_LOCK;
1766     }
1767 
1768     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
1769     ** without clearing the error code. This is intentional - the error
1770     ** code is cleared and the cache reset in the block below.
1771     */
1772     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
1773     pPager->changeCountDone = 0;
1774     pPager->eState = PAGER_OPEN;
1775   }
1776 
1777   /* If Pager.errCode is set, the contents of the pager cache cannot be
1778   ** trusted. Now that there are no outstanding references to the pager,
1779   ** it can safely move back to PAGER_OPEN state. This happens in both
1780   ** normal and exclusive-locking mode.
1781   */
1782   if( pPager->errCode ){
1783     assert( !MEMDB );
1784     pager_reset(pPager);
1785     pPager->changeCountDone = pPager->tempFile;
1786     pPager->eState = PAGER_OPEN;
1787     pPager->errCode = SQLITE_OK;
1788   }
1789 
1790   pPager->journalOff = 0;
1791   pPager->journalHdr = 0;
1792   pPager->setMaster = 0;
1793 }
1794 
1795 /*
1796 ** This function is called whenever an IOERR or FULL error that requires
1797 ** the pager to transition into the ERROR state may ahve occurred.
1798 ** The first argument is a pointer to the pager structure, the second
1799 ** the error-code about to be returned by a pager API function. The
1800 ** value returned is a copy of the second argument to this function.
1801 **
1802 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
1803 ** IOERR sub-codes, the pager enters the ERROR state and the error code
1804 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
1805 ** all major API calls on the Pager will immediately return Pager.errCode.
1806 **
1807 ** The ERROR state indicates that the contents of the pager-cache
1808 ** cannot be trusted. This state can be cleared by completely discarding
1809 ** the contents of the pager-cache. If a transaction was active when
1810 ** the persistent error occurred, then the rollback journal may need
1811 ** to be replayed to restore the contents of the database file (as if
1812 ** it were a hot-journal).
1813 */
1814 static int pager_error(Pager *pPager, int rc){
1815   int rc2 = rc & 0xff;
1816   assert( rc==SQLITE_OK || !MEMDB );
1817   assert(
1818        pPager->errCode==SQLITE_FULL ||
1819        pPager->errCode==SQLITE_OK ||
1820        (pPager->errCode & 0xff)==SQLITE_IOERR
1821   );
1822   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
1823     pPager->errCode = rc;
1824     pPager->eState = PAGER_ERROR;
1825   }
1826   return rc;
1827 }
1828 
1829 /*
1830 ** This routine ends a transaction. A transaction is usually ended by
1831 ** either a COMMIT or a ROLLBACK operation. This routine may be called
1832 ** after rollback of a hot-journal, or if an error occurs while opening
1833 ** the journal file or writing the very first journal-header of a
1834 ** database transaction.
1835 **
1836 ** This routine is never called in PAGER_ERROR state. If it is called
1837 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
1838 ** exclusive than a RESERVED lock, it is a no-op.
1839 **
1840 ** Otherwise, any active savepoints are released.
1841 **
1842 ** If the journal file is open, then it is "finalized". Once a journal
1843 ** file has been finalized it is not possible to use it to roll back a
1844 ** transaction. Nor will it be considered to be a hot-journal by this
1845 ** or any other database connection. Exactly how a journal is finalized
1846 ** depends on whether or not the pager is running in exclusive mode and
1847 ** the current journal-mode (Pager.journalMode value), as follows:
1848 **
1849 **   journalMode==MEMORY
1850 **     Journal file descriptor is simply closed. This destroys an
1851 **     in-memory journal.
1852 **
1853 **   journalMode==TRUNCATE
1854 **     Journal file is truncated to zero bytes in size.
1855 **
1856 **   journalMode==PERSIST
1857 **     The first 28 bytes of the journal file are zeroed. This invalidates
1858 **     the first journal header in the file, and hence the entire journal
1859 **     file. An invalid journal file cannot be rolled back.
1860 **
1861 **   journalMode==DELETE
1862 **     The journal file is closed and deleted using sqlite3OsDelete().
1863 **
1864 **     If the pager is running in exclusive mode, this method of finalizing
1865 **     the journal file is never used. Instead, if the journalMode is
1866 **     DELETE and the pager is in exclusive mode, the method described under
1867 **     journalMode==PERSIST is used instead.
1868 **
1869 ** After the journal is finalized, the pager moves to PAGER_READER state.
1870 ** If running in non-exclusive rollback mode, the lock on the file is
1871 ** downgraded to a SHARED_LOCK.
1872 **
1873 ** SQLITE_OK is returned if no error occurs. If an error occurs during
1874 ** any of the IO operations to finalize the journal file or unlock the
1875 ** database then the IO error code is returned to the user. If the
1876 ** operation to finalize the journal file fails, then the code still
1877 ** tries to unlock the database file if not in exclusive mode. If the
1878 ** unlock operation fails as well, then the first error code related
1879 ** to the first error encountered (the journal finalization one) is
1880 ** returned.
1881 */
1882 static int pager_end_transaction(Pager *pPager, int hasMaster){
1883   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
1884   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
1885 
1886   /* Do nothing if the pager does not have an open write transaction
1887   ** or at least a RESERVED lock. This function may be called when there
1888   ** is no write-transaction active but a RESERVED or greater lock is
1889   ** held under two circumstances:
1890   **
1891   **   1. After a successful hot-journal rollback, it is called with
1892   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
1893   **
1894   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
1895   **      lock switches back to locking_mode=normal and then executes a
1896   **      read-transaction, this function is called with eState==PAGER_READER
1897   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
1898   */
1899   assert( assert_pager_state(pPager) );
1900   assert( pPager->eState!=PAGER_ERROR );
1901   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
1902     return SQLITE_OK;
1903   }
1904 
1905   releaseAllSavepoints(pPager);
1906   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
1907   if( isOpen(pPager->jfd) ){
1908     assert( !pagerUseWal(pPager) );
1909 
1910     /* Finalize the journal file. */
1911     if( sqlite3IsMemJournal(pPager->jfd) ){
1912       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
1913       sqlite3OsClose(pPager->jfd);
1914     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
1915       if( pPager->journalOff==0 ){
1916         rc = SQLITE_OK;
1917       }else{
1918         rc = sqlite3OsTruncate(pPager->jfd, 0);
1919       }
1920       pPager->journalOff = 0;
1921     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
1922       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
1923     ){
1924       rc = zeroJournalHdr(pPager, hasMaster);
1925       pPager->journalOff = 0;
1926     }else{
1927       /* This branch may be executed with Pager.journalMode==MEMORY if
1928       ** a hot-journal was just rolled back. In this case the journal
1929       ** file should be closed and deleted. If this connection writes to
1930       ** the database file, it will do so using an in-memory journal.
1931       */
1932       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
1933            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
1934            || pPager->journalMode==PAGER_JOURNALMODE_WAL
1935       );
1936       sqlite3OsClose(pPager->jfd);
1937       if( !pPager->tempFile ){
1938         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
1939       }
1940     }
1941   }
1942 
1943 #ifdef SQLITE_CHECK_PAGES
1944   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
1945   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
1946     PgHdr *p = pager_lookup(pPager, 1);
1947     if( p ){
1948       p->pageHash = 0;
1949       sqlite3PagerUnref(p);
1950     }
1951   }
1952 #endif
1953 
1954   sqlite3BitvecDestroy(pPager->pInJournal);
1955   pPager->pInJournal = 0;
1956   pPager->nRec = 0;
1957   sqlite3PcacheCleanAll(pPager->pPCache);
1958   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
1959 
1960   if( pagerUseWal(pPager) ){
1961     /* Drop the WAL write-lock, if any. Also, if the connection was in
1962     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
1963     ** lock held on the database file.
1964     */
1965     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
1966     assert( rc2==SQLITE_OK );
1967   }
1968   if( !pPager->exclusiveMode
1969    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
1970   ){
1971     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
1972     pPager->changeCountDone = 0;
1973   }
1974   pPager->eState = PAGER_READER;
1975   pPager->setMaster = 0;
1976 
1977   return (rc==SQLITE_OK?rc2:rc);
1978 }
1979 
1980 /*
1981 ** Execute a rollback if a transaction is active and unlock the
1982 ** database file.
1983 **
1984 ** If the pager has already entered the ERROR state, do not attempt
1985 ** the rollback at this time. Instead, pager_unlock() is called. The
1986 ** call to pager_unlock() will discard all in-memory pages, unlock
1987 ** the database file and move the pager back to OPEN state. If this
1988 ** means that there is a hot-journal left in the file-system, the next
1989 ** connection to obtain a shared lock on the pager (which may be this one)
1990 ** will roll it back.
1991 **
1992 ** If the pager has not already entered the ERROR state, but an IO or
1993 ** malloc error occurs during a rollback, then this will itself cause
1994 ** the pager to enter the ERROR state. Which will be cleared by the
1995 ** call to pager_unlock(), as described above.
1996 */
1997 static void pagerUnlockAndRollback(Pager *pPager){
1998   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
1999     assert( assert_pager_state(pPager) );
2000     if( pPager->eState>=PAGER_WRITER_LOCKED ){
2001       sqlite3BeginBenignMalloc();
2002       sqlite3PagerRollback(pPager);
2003       sqlite3EndBenignMalloc();
2004     }else if( !pPager->exclusiveMode ){
2005       assert( pPager->eState==PAGER_READER );
2006       pager_end_transaction(pPager, 0);
2007     }
2008   }
2009   pager_unlock(pPager);
2010 }
2011 
2012 /*
2013 ** Parameter aData must point to a buffer of pPager->pageSize bytes
2014 ** of data. Compute and return a checksum based ont the contents of the
2015 ** page of data and the current value of pPager->cksumInit.
2016 **
2017 ** This is not a real checksum. It is really just the sum of the
2018 ** random initial value (pPager->cksumInit) and every 200th byte
2019 ** of the page data, starting with byte offset (pPager->pageSize%200).
2020 ** Each byte is interpreted as an 8-bit unsigned integer.
2021 **
2022 ** Changing the formula used to compute this checksum results in an
2023 ** incompatible journal file format.
2024 **
2025 ** If journal corruption occurs due to a power failure, the most likely
2026 ** scenario is that one end or the other of the record will be changed.
2027 ** It is much less likely that the two ends of the journal record will be
2028 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
2029 ** though fast and simple, catches the mostly likely kind of corruption.
2030 */
2031 static u32 pager_cksum(Pager *pPager, const u8 *aData){
2032   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
2033   int i = pPager->pageSize-200;          /* Loop counter */
2034   while( i>0 ){
2035     cksum += aData[i];
2036     i -= 200;
2037   }
2038   return cksum;
2039 }
2040 
2041 /*
2042 ** Report the current page size and number of reserved bytes back
2043 ** to the codec.
2044 */
2045 #ifdef SQLITE_HAS_CODEC
2046 static void pagerReportSize(Pager *pPager){
2047   if( pPager->xCodecSizeChng ){
2048     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
2049                            (int)pPager->nReserve);
2050   }
2051 }
2052 #else
2053 # define pagerReportSize(X)     /* No-op if we do not support a codec */
2054 #endif
2055 
2056 /*
2057 ** Read a single page from either the journal file (if isMainJrnl==1) or
2058 ** from the sub-journal (if isMainJrnl==0) and playback that page.
2059 ** The page begins at offset *pOffset into the file. The *pOffset
2060 ** value is increased to the start of the next page in the journal.
2061 **
2062 ** The main rollback journal uses checksums - the statement journal does
2063 ** not.
2064 **
2065 ** If the page number of the page record read from the (sub-)journal file
2066 ** is greater than the current value of Pager.dbSize, then playback is
2067 ** skipped and SQLITE_OK is returned.
2068 **
2069 ** If pDone is not NULL, then it is a record of pages that have already
2070 ** been played back.  If the page at *pOffset has already been played back
2071 ** (if the corresponding pDone bit is set) then skip the playback.
2072 ** Make sure the pDone bit corresponding to the *pOffset page is set
2073 ** prior to returning.
2074 **
2075 ** If the page record is successfully read from the (sub-)journal file
2076 ** and played back, then SQLITE_OK is returned. If an IO error occurs
2077 ** while reading the record from the (sub-)journal file or while writing
2078 ** to the database file, then the IO error code is returned. If data
2079 ** is successfully read from the (sub-)journal file but appears to be
2080 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
2081 ** two circumstances:
2082 **
2083 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
2084 **   * If the record is being rolled back from the main journal file
2085 **     and the checksum field does not match the record content.
2086 **
2087 ** Neither of these two scenarios are possible during a savepoint rollback.
2088 **
2089 ** If this is a savepoint rollback, then memory may have to be dynamically
2090 ** allocated by this function. If this is the case and an allocation fails,
2091 ** SQLITE_NOMEM is returned.
2092 */
2093 static int pager_playback_one_page(
2094   Pager *pPager,                /* The pager being played back */
2095   i64 *pOffset,                 /* Offset of record to playback */
2096   Bitvec *pDone,                /* Bitvec of pages already played back */
2097   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
2098   int isSavepnt                 /* True for a savepoint rollback */
2099 ){
2100   int rc;
2101   PgHdr *pPg;                   /* An existing page in the cache */
2102   Pgno pgno;                    /* The page number of a page in journal */
2103   u32 cksum;                    /* Checksum used for sanity checking */
2104   char *aData;                  /* Temporary storage for the page */
2105   sqlite3_file *jfd;            /* The file descriptor for the journal file */
2106   int isSynced;                 /* True if journal page is synced */
2107 
2108   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
2109   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
2110   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
2111   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
2112 
2113   aData = pPager->pTmpSpace;
2114   assert( aData );         /* Temp storage must have already been allocated */
2115   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
2116 
2117   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
2118   ** or savepoint rollback done at the request of the caller) or this is
2119   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
2120   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
2121   ** only reads from the main journal, not the sub-journal.
2122   */
2123   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
2124        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
2125   );
2126   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
2127 
2128   /* Read the page number and page data from the journal or sub-journal
2129   ** file. Return an error code to the caller if an IO error occurs.
2130   */
2131   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
2132   rc = read32bits(jfd, *pOffset, &pgno);
2133   if( rc!=SQLITE_OK ) return rc;
2134   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
2135   if( rc!=SQLITE_OK ) return rc;
2136   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
2137 
2138   /* Sanity checking on the page.  This is more important that I originally
2139   ** thought.  If a power failure occurs while the journal is being written,
2140   ** it could cause invalid data to be written into the journal.  We need to
2141   ** detect this invalid data (with high probability) and ignore it.
2142   */
2143   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
2144     assert( !isSavepnt );
2145     return SQLITE_DONE;
2146   }
2147   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
2148     return SQLITE_OK;
2149   }
2150   if( isMainJrnl ){
2151     rc = read32bits(jfd, (*pOffset)-4, &cksum);
2152     if( rc ) return rc;
2153     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
2154       return SQLITE_DONE;
2155     }
2156   }
2157 
2158   /* If this page has already been played by before during the current
2159   ** rollback, then don't bother to play it back again.
2160   */
2161   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
2162     return rc;
2163   }
2164 
2165   /* When playing back page 1, restore the nReserve setting
2166   */
2167   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
2168     pPager->nReserve = ((u8*)aData)[20];
2169     pagerReportSize(pPager);
2170   }
2171 
2172   /* If the pager is in CACHEMOD state, then there must be a copy of this
2173   ** page in the pager cache. In this case just update the pager cache,
2174   ** not the database file. The page is left marked dirty in this case.
2175   **
2176   ** An exception to the above rule: If the database is in no-sync mode
2177   ** and a page is moved during an incremental vacuum then the page may
2178   ** not be in the pager cache. Later: if a malloc() or IO error occurs
2179   ** during a Movepage() call, then the page may not be in the cache
2180   ** either. So the condition described in the above paragraph is not
2181   ** assert()able.
2182   **
2183   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
2184   ** pager cache if it exists and the main file. The page is then marked
2185   ** not dirty. Since this code is only executed in PAGER_OPEN state for
2186   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
2187   ** if the pager is in OPEN state.
2188   **
2189   ** Ticket #1171:  The statement journal might contain page content that is
2190   ** different from the page content at the start of the transaction.
2191   ** This occurs when a page is changed prior to the start of a statement
2192   ** then changed again within the statement.  When rolling back such a
2193   ** statement we must not write to the original database unless we know
2194   ** for certain that original page contents are synced into the main rollback
2195   ** journal.  Otherwise, a power loss might leave modified data in the
2196   ** database file without an entry in the rollback journal that can
2197   ** restore the database to its original form.  Two conditions must be
2198   ** met before writing to the database files. (1) the database must be
2199   ** locked.  (2) we know that the original page content is fully synced
2200   ** in the main journal either because the page is not in cache or else
2201   ** the page is marked as needSync==0.
2202   **
2203   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
2204   ** is possible to fail a statement on a database that does not yet exist.
2205   ** Do not attempt to write if database file has never been opened.
2206   */
2207   if( pagerUseWal(pPager) ){
2208     pPg = 0;
2209   }else{
2210     pPg = pager_lookup(pPager, pgno);
2211   }
2212   assert( pPg || !MEMDB );
2213   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
2214   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
2215            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
2216            (isMainJrnl?"main-journal":"sub-journal")
2217   ));
2218   if( isMainJrnl ){
2219     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
2220   }else{
2221     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
2222   }
2223   if( isOpen(pPager->fd)
2224    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
2225    && isSynced
2226   ){
2227     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
2228     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
2229     assert( !pagerUseWal(pPager) );
2230     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
2231     if( pgno>pPager->dbFileSize ){
2232       pPager->dbFileSize = pgno;
2233     }
2234     if( pPager->pBackup ){
2235       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
2236       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
2237       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
2238     }
2239   }else if( !isMainJrnl && pPg==0 ){
2240     /* If this is a rollback of a savepoint and data was not written to
2241     ** the database and the page is not in-memory, there is a potential
2242     ** problem. When the page is next fetched by the b-tree layer, it
2243     ** will be read from the database file, which may or may not be
2244     ** current.
2245     **
2246     ** There are a couple of different ways this can happen. All are quite
2247     ** obscure. When running in synchronous mode, this can only happen
2248     ** if the page is on the free-list at the start of the transaction, then
2249     ** populated, then moved using sqlite3PagerMovepage().
2250     **
2251     ** The solution is to add an in-memory page to the cache containing
2252     ** the data just read from the sub-journal. Mark the page as dirty
2253     ** and if the pager requires a journal-sync, then mark the page as
2254     ** requiring a journal-sync before it is written.
2255     */
2256     assert( isSavepnt );
2257     assert( pPager->doNotSpill==0 );
2258     pPager->doNotSpill++;
2259     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
2260     assert( pPager->doNotSpill==1 );
2261     pPager->doNotSpill--;
2262     if( rc!=SQLITE_OK ) return rc;
2263     pPg->flags &= ~PGHDR_NEED_READ;
2264     sqlite3PcacheMakeDirty(pPg);
2265   }
2266   if( pPg ){
2267     /* No page should ever be explicitly rolled back that is in use, except
2268     ** for page 1 which is held in use in order to keep the lock on the
2269     ** database active. However such a page may be rolled back as a result
2270     ** of an internal error resulting in an automatic call to
2271     ** sqlite3PagerRollback().
2272     */
2273     void *pData;
2274     pData = pPg->pData;
2275     memcpy(pData, (u8*)aData, pPager->pageSize);
2276     pPager->xReiniter(pPg);
2277     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
2278       /* If the contents of this page were just restored from the main
2279       ** journal file, then its content must be as they were when the
2280       ** transaction was first opened. In this case we can mark the page
2281       ** as clean, since there will be no need to write it out to the
2282       ** database.
2283       **
2284       ** There is one exception to this rule. If the page is being rolled
2285       ** back as part of a savepoint (or statement) rollback from an
2286       ** unsynced portion of the main journal file, then it is not safe
2287       ** to mark the page as clean. This is because marking the page as
2288       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
2289       ** already in the journal file (recorded in Pager.pInJournal) and
2290       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
2291       ** again within this transaction, it will be marked as dirty but
2292       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
2293       ** be written out into the database file before its journal file
2294       ** segment is synced. If a crash occurs during or following this,
2295       ** database corruption may ensue.
2296       */
2297       assert( !pagerUseWal(pPager) );
2298       sqlite3PcacheMakeClean(pPg);
2299     }
2300     pager_set_pagehash(pPg);
2301 
2302     /* If this was page 1, then restore the value of Pager.dbFileVers.
2303     ** Do this before any decoding. */
2304     if( pgno==1 ){
2305       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
2306     }
2307 
2308     /* Decode the page just read from disk */
2309     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
2310     sqlite3PcacheRelease(pPg);
2311   }
2312   return rc;
2313 }
2314 
2315 /*
2316 ** Parameter zMaster is the name of a master journal file. A single journal
2317 ** file that referred to the master journal file has just been rolled back.
2318 ** This routine checks if it is possible to delete the master journal file,
2319 ** and does so if it is.
2320 **
2321 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
2322 ** available for use within this function.
2323 **
2324 ** When a master journal file is created, it is populated with the names
2325 ** of all of its child journals, one after another, formatted as utf-8
2326 ** encoded text. The end of each child journal file is marked with a
2327 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
2328 ** file for a transaction involving two databases might be:
2329 **
2330 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
2331 **
2332 ** A master journal file may only be deleted once all of its child
2333 ** journals have been rolled back.
2334 **
2335 ** This function reads the contents of the master-journal file into
2336 ** memory and loops through each of the child journal names. For
2337 ** each child journal, it checks if:
2338 **
2339 **   * if the child journal exists, and if so
2340 **   * if the child journal contains a reference to master journal
2341 **     file zMaster
2342 **
2343 ** If a child journal can be found that matches both of the criteria
2344 ** above, this function returns without doing anything. Otherwise, if
2345 ** no such child journal can be found, file zMaster is deleted from
2346 ** the file-system using sqlite3OsDelete().
2347 **
2348 ** If an IO error within this function, an error code is returned. This
2349 ** function allocates memory by calling sqlite3Malloc(). If an allocation
2350 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
2351 ** occur, SQLITE_OK is returned.
2352 **
2353 ** TODO: This function allocates a single block of memory to load
2354 ** the entire contents of the master journal file. This could be
2355 ** a couple of kilobytes or so - potentially larger than the page
2356 ** size.
2357 */
2358 static int pager_delmaster(Pager *pPager, const char *zMaster){
2359   sqlite3_vfs *pVfs = pPager->pVfs;
2360   int rc;                   /* Return code */
2361   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
2362   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
2363   char *zMasterJournal = 0; /* Contents of master journal file */
2364   i64 nMasterJournal;       /* Size of master journal file */
2365   char *zJournal;           /* Pointer to one journal within MJ file */
2366   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
2367   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
2368 
2369   /* Allocate space for both the pJournal and pMaster file descriptors.
2370   ** If successful, open the master journal file for reading.
2371   */
2372   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
2373   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
2374   if( !pMaster ){
2375     rc = SQLITE_NOMEM;
2376   }else{
2377     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
2378     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
2379   }
2380   if( rc!=SQLITE_OK ) goto delmaster_out;
2381 
2382   /* Load the entire master journal file into space obtained from
2383   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
2384   ** sufficient space (in zMasterPtr) to hold the names of master
2385   ** journal files extracted from regular rollback-journals.
2386   */
2387   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
2388   if( rc!=SQLITE_OK ) goto delmaster_out;
2389   nMasterPtr = pVfs->mxPathname+1;
2390   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
2391   if( !zMasterJournal ){
2392     rc = SQLITE_NOMEM;
2393     goto delmaster_out;
2394   }
2395   zMasterPtr = &zMasterJournal[nMasterJournal+1];
2396   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
2397   if( rc!=SQLITE_OK ) goto delmaster_out;
2398   zMasterJournal[nMasterJournal] = 0;
2399 
2400   zJournal = zMasterJournal;
2401   while( (zJournal-zMasterJournal)<nMasterJournal ){
2402     int exists;
2403     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
2404     if( rc!=SQLITE_OK ){
2405       goto delmaster_out;
2406     }
2407     if( exists ){
2408       /* One of the journals pointed to by the master journal exists.
2409       ** Open it and check if it points at the master journal. If
2410       ** so, return without deleting the master journal file.
2411       */
2412       int c;
2413       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
2414       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
2415       if( rc!=SQLITE_OK ){
2416         goto delmaster_out;
2417       }
2418 
2419       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
2420       sqlite3OsClose(pJournal);
2421       if( rc!=SQLITE_OK ){
2422         goto delmaster_out;
2423       }
2424 
2425       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
2426       if( c ){
2427         /* We have a match. Do not delete the master journal file. */
2428         goto delmaster_out;
2429       }
2430     }
2431     zJournal += (sqlite3Strlen30(zJournal)+1);
2432   }
2433 
2434   sqlite3OsClose(pMaster);
2435   rc = sqlite3OsDelete(pVfs, zMaster, 0);
2436 
2437 delmaster_out:
2438   sqlite3_free(zMasterJournal);
2439   if( pMaster ){
2440     sqlite3OsClose(pMaster);
2441     assert( !isOpen(pJournal) );
2442     sqlite3_free(pMaster);
2443   }
2444   return rc;
2445 }
2446 
2447 
2448 /*
2449 ** This function is used to change the actual size of the database
2450 ** file in the file-system. This only happens when committing a transaction,
2451 ** or rolling back a transaction (including rolling back a hot-journal).
2452 **
2453 ** If the main database file is not open, or the pager is not in either
2454 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
2455 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
2456 ** If the file on disk is currently larger than nPage pages, then use the VFS
2457 ** xTruncate() method to truncate it.
2458 **
2459 ** Or, it might might be the case that the file on disk is smaller than
2460 ** nPage pages. Some operating system implementations can get confused if
2461 ** you try to truncate a file to some size that is larger than it
2462 ** currently is, so detect this case and write a single zero byte to
2463 ** the end of the new file instead.
2464 **
2465 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
2466 ** the database file, return the error code to the caller.
2467 */
2468 static int pager_truncate(Pager *pPager, Pgno nPage){
2469   int rc = SQLITE_OK;
2470   assert( pPager->eState!=PAGER_ERROR );
2471   assert( pPager->eState!=PAGER_READER );
2472 
2473   if( isOpen(pPager->fd)
2474    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
2475   ){
2476     i64 currentSize, newSize;
2477     assert( pPager->eLock==EXCLUSIVE_LOCK );
2478     /* TODO: Is it safe to use Pager.dbFileSize here? */
2479     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
2480     newSize = pPager->pageSize*(i64)nPage;
2481     if( rc==SQLITE_OK && currentSize!=newSize ){
2482       if( currentSize>newSize ){
2483         rc = sqlite3OsTruncate(pPager->fd, newSize);
2484       }else{
2485         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
2486       }
2487       if( rc==SQLITE_OK ){
2488         pPager->dbFileSize = nPage;
2489       }
2490     }
2491   }
2492   return rc;
2493 }
2494 
2495 /*
2496 ** Set the value of the Pager.sectorSize variable for the given
2497 ** pager based on the value returned by the xSectorSize method
2498 ** of the open database file. The sector size will be used used
2499 ** to determine the size and alignment of journal header and
2500 ** master journal pointers within created journal files.
2501 **
2502 ** For temporary files the effective sector size is always 512 bytes.
2503 **
2504 ** Otherwise, for non-temporary files, the effective sector size is
2505 ** the value returned by the xSectorSize() method rounded up to 32 if
2506 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
2507 ** is greater than MAX_SECTOR_SIZE.
2508 */
2509 static void setSectorSize(Pager *pPager){
2510   assert( isOpen(pPager->fd) || pPager->tempFile );
2511 
2512   if( !pPager->tempFile ){
2513     /* Sector size doesn't matter for temporary files. Also, the file
2514     ** may not have been opened yet, in which case the OsSectorSize()
2515     ** call will segfault.
2516     */
2517     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
2518   }
2519   if( pPager->sectorSize<32 ){
2520     pPager->sectorSize = 512;
2521   }
2522   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
2523     assert( MAX_SECTOR_SIZE>=512 );
2524     pPager->sectorSize = MAX_SECTOR_SIZE;
2525   }
2526 }
2527 
2528 /*
2529 ** Playback the journal and thus restore the database file to
2530 ** the state it was in before we started making changes.
2531 **
2532 ** The journal file format is as follows:
2533 **
2534 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
2535 **  (2)  4 byte big-endian integer which is the number of valid page records
2536 **       in the journal.  If this value is 0xffffffff, then compute the
2537 **       number of page records from the journal size.
2538 **  (3)  4 byte big-endian integer which is the initial value for the
2539 **       sanity checksum.
2540 **  (4)  4 byte integer which is the number of pages to truncate the
2541 **       database to during a rollback.
2542 **  (5)  4 byte big-endian integer which is the sector size.  The header
2543 **       is this many bytes in size.
2544 **  (6)  4 byte big-endian integer which is the page size.
2545 **  (7)  zero padding out to the next sector size.
2546 **  (8)  Zero or more pages instances, each as follows:
2547 **        +  4 byte page number.
2548 **        +  pPager->pageSize bytes of data.
2549 **        +  4 byte checksum
2550 **
2551 ** When we speak of the journal header, we mean the first 7 items above.
2552 ** Each entry in the journal is an instance of the 8th item.
2553 **
2554 ** Call the value from the second bullet "nRec".  nRec is the number of
2555 ** valid page entries in the journal.  In most cases, you can compute the
2556 ** value of nRec from the size of the journal file.  But if a power
2557 ** failure occurred while the journal was being written, it could be the
2558 ** case that the size of the journal file had already been increased but
2559 ** the extra entries had not yet made it safely to disk.  In such a case,
2560 ** the value of nRec computed from the file size would be too large.  For
2561 ** that reason, we always use the nRec value in the header.
2562 **
2563 ** If the nRec value is 0xffffffff it means that nRec should be computed
2564 ** from the file size.  This value is used when the user selects the
2565 ** no-sync option for the journal.  A power failure could lead to corruption
2566 ** in this case.  But for things like temporary table (which will be
2567 ** deleted when the power is restored) we don't care.
2568 **
2569 ** If the file opened as the journal file is not a well-formed
2570 ** journal file then all pages up to the first corrupted page are rolled
2571 ** back (or no pages if the journal header is corrupted). The journal file
2572 ** is then deleted and SQLITE_OK returned, just as if no corruption had
2573 ** been encountered.
2574 **
2575 ** If an I/O or malloc() error occurs, the journal-file is not deleted
2576 ** and an error code is returned.
2577 **
2578 ** The isHot parameter indicates that we are trying to rollback a journal
2579 ** that might be a hot journal.  Or, it could be that the journal is
2580 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
2581 ** If the journal really is hot, reset the pager cache prior rolling
2582 ** back any content.  If the journal is merely persistent, no reset is
2583 ** needed.
2584 */
2585 static int pager_playback(Pager *pPager, int isHot){
2586   sqlite3_vfs *pVfs = pPager->pVfs;
2587   i64 szJ;                 /* Size of the journal file in bytes */
2588   u32 nRec;                /* Number of Records in the journal */
2589   u32 u;                   /* Unsigned loop counter */
2590   Pgno mxPg = 0;           /* Size of the original file in pages */
2591   int rc;                  /* Result code of a subroutine */
2592   int res = 1;             /* Value returned by sqlite3OsAccess() */
2593   char *zMaster = 0;       /* Name of master journal file if any */
2594   int needPagerReset;      /* True to reset page prior to first page rollback */
2595 
2596   /* Figure out how many records are in the journal.  Abort early if
2597   ** the journal is empty.
2598   */
2599   assert( isOpen(pPager->jfd) );
2600   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
2601   if( rc!=SQLITE_OK ){
2602     goto end_playback;
2603   }
2604 
2605   /* Read the master journal name from the journal, if it is present.
2606   ** If a master journal file name is specified, but the file is not
2607   ** present on disk, then the journal is not hot and does not need to be
2608   ** played back.
2609   **
2610   ** TODO: Technically the following is an error because it assumes that
2611   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
2612   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
2613   **  mxPathname is 512, which is the same as the minimum allowable value
2614   ** for pageSize.
2615   */
2616   zMaster = pPager->pTmpSpace;
2617   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
2618   if( rc==SQLITE_OK && zMaster[0] ){
2619     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2620   }
2621   zMaster = 0;
2622   if( rc!=SQLITE_OK || !res ){
2623     goto end_playback;
2624   }
2625   pPager->journalOff = 0;
2626   needPagerReset = isHot;
2627 
2628   /* This loop terminates either when a readJournalHdr() or
2629   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
2630   ** occurs.
2631   */
2632   while( 1 ){
2633     /* Read the next journal header from the journal file.  If there are
2634     ** not enough bytes left in the journal file for a complete header, or
2635     ** it is corrupted, then a process must have failed while writing it.
2636     ** This indicates nothing more needs to be rolled back.
2637     */
2638     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
2639     if( rc!=SQLITE_OK ){
2640       if( rc==SQLITE_DONE ){
2641         rc = SQLITE_OK;
2642       }
2643       goto end_playback;
2644     }
2645 
2646     /* If nRec is 0xffffffff, then this journal was created by a process
2647     ** working in no-sync mode. This means that the rest of the journal
2648     ** file consists of pages, there are no more journal headers. Compute
2649     ** the value of nRec based on this assumption.
2650     */
2651     if( nRec==0xffffffff ){
2652       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
2653       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
2654     }
2655 
2656     /* If nRec is 0 and this rollback is of a transaction created by this
2657     ** process and if this is the final header in the journal, then it means
2658     ** that this part of the journal was being filled but has not yet been
2659     ** synced to disk.  Compute the number of pages based on the remaining
2660     ** size of the file.
2661     **
2662     ** The third term of the test was added to fix ticket #2565.
2663     ** When rolling back a hot journal, nRec==0 always means that the next
2664     ** chunk of the journal contains zero pages to be rolled back.  But
2665     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
2666     ** the journal, it means that the journal might contain additional
2667     ** pages that need to be rolled back and that the number of pages
2668     ** should be computed based on the journal file size.
2669     */
2670     if( nRec==0 && !isHot &&
2671         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
2672       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
2673     }
2674 
2675     /* If this is the first header read from the journal, truncate the
2676     ** database file back to its original size.
2677     */
2678     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
2679       rc = pager_truncate(pPager, mxPg);
2680       if( rc!=SQLITE_OK ){
2681         goto end_playback;
2682       }
2683       pPager->dbSize = mxPg;
2684     }
2685 
2686     /* Copy original pages out of the journal and back into the
2687     ** database file and/or page cache.
2688     */
2689     for(u=0; u<nRec; u++){
2690       if( needPagerReset ){
2691         pager_reset(pPager);
2692         needPagerReset = 0;
2693       }
2694       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
2695       if( rc!=SQLITE_OK ){
2696         if( rc==SQLITE_DONE ){
2697           rc = SQLITE_OK;
2698           pPager->journalOff = szJ;
2699           break;
2700         }else if( rc==SQLITE_IOERR_SHORT_READ ){
2701           /* If the journal has been truncated, simply stop reading and
2702           ** processing the journal. This might happen if the journal was
2703           ** not completely written and synced prior to a crash.  In that
2704           ** case, the database should have never been written in the
2705           ** first place so it is OK to simply abandon the rollback. */
2706           rc = SQLITE_OK;
2707           goto end_playback;
2708         }else{
2709           /* If we are unable to rollback, quit and return the error
2710           ** code.  This will cause the pager to enter the error state
2711           ** so that no further harm will be done.  Perhaps the next
2712           ** process to come along will be able to rollback the database.
2713           */
2714           goto end_playback;
2715         }
2716       }
2717     }
2718   }
2719   /*NOTREACHED*/
2720   assert( 0 );
2721 
2722 end_playback:
2723   /* Following a rollback, the database file should be back in its original
2724   ** state prior to the start of the transaction, so invoke the
2725   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
2726   ** assertion that the transaction counter was modified.
2727   */
2728   assert(
2729     pPager->fd->pMethods==0 ||
2730     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
2731   );
2732 
2733   /* If this playback is happening automatically as a result of an IO or
2734   ** malloc error that occurred after the change-counter was updated but
2735   ** before the transaction was committed, then the change-counter
2736   ** modification may just have been reverted. If this happens in exclusive
2737   ** mode, then subsequent transactions performed by the connection will not
2738   ** update the change-counter at all. This may lead to cache inconsistency
2739   ** problems for other processes at some point in the future. So, just
2740   ** in case this has happened, clear the changeCountDone flag now.
2741   */
2742   pPager->changeCountDone = pPager->tempFile;
2743 
2744   if( rc==SQLITE_OK ){
2745     zMaster = pPager->pTmpSpace;
2746     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
2747     testcase( rc!=SQLITE_OK );
2748   }
2749   if( rc==SQLITE_OK && !pPager->noSync
2750    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
2751   ){
2752     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
2753   }
2754   if( rc==SQLITE_OK ){
2755     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
2756     testcase( rc!=SQLITE_OK );
2757   }
2758   if( rc==SQLITE_OK && zMaster[0] && res ){
2759     /* If there was a master journal and this routine will return success,
2760     ** see if it is possible to delete the master journal.
2761     */
2762     rc = pager_delmaster(pPager, zMaster);
2763     testcase( rc!=SQLITE_OK );
2764   }
2765 
2766   /* The Pager.sectorSize variable may have been updated while rolling
2767   ** back a journal created by a process with a different sector size
2768   ** value. Reset it to the correct value for this process.
2769   */
2770   setSectorSize(pPager);
2771   return rc;
2772 }
2773 
2774 
2775 /*
2776 ** Read the content for page pPg out of the database file and into
2777 ** pPg->pData. A shared lock or greater must be held on the database
2778 ** file before this function is called.
2779 **
2780 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
2781 ** the value read from the database file.
2782 **
2783 ** If an IO error occurs, then the IO error is returned to the caller.
2784 ** Otherwise, SQLITE_OK is returned.
2785 */
2786 static int readDbPage(PgHdr *pPg){
2787   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
2788   Pgno pgno = pPg->pgno;       /* Page number to read */
2789   int rc = SQLITE_OK;          /* Return code */
2790   int isInWal = 0;             /* True if page is in log file */
2791   int pgsz = pPager->pageSize; /* Number of bytes to read */
2792 
2793   assert( pPager->eState>=PAGER_READER && !MEMDB );
2794   assert( isOpen(pPager->fd) );
2795 
2796   if( NEVER(!isOpen(pPager->fd)) ){
2797     assert( pPager->tempFile );
2798     memset(pPg->pData, 0, pPager->pageSize);
2799     return SQLITE_OK;
2800   }
2801 
2802   if( pagerUseWal(pPager) ){
2803     /* Try to pull the page from the write-ahead log. */
2804     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
2805   }
2806   if( rc==SQLITE_OK && !isInWal ){
2807     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
2808     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
2809     if( rc==SQLITE_IOERR_SHORT_READ ){
2810       rc = SQLITE_OK;
2811     }
2812   }
2813 
2814   if( pgno==1 ){
2815     if( rc ){
2816       /* If the read is unsuccessful, set the dbFileVers[] to something
2817       ** that will never be a valid file version.  dbFileVers[] is a copy
2818       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
2819       ** zero or the size of the database in page. Bytes 32..35 and 35..39
2820       ** should be page numbers which are never 0xffffffff.  So filling
2821       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
2822       **
2823       ** For an encrypted database, the situation is more complex:  bytes
2824       ** 24..39 of the database are white noise.  But the probability of
2825       ** white noising equaling 16 bytes of 0xff is vanishingly small so
2826       ** we should still be ok.
2827       */
2828       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
2829     }else{
2830       u8 *dbFileVers = &((u8*)pPg->pData)[24];
2831       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
2832     }
2833   }
2834   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
2835 
2836   PAGER_INCR(sqlite3_pager_readdb_count);
2837   PAGER_INCR(pPager->nRead);
2838   IOTRACE(("PGIN %p %d\n", pPager, pgno));
2839   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
2840                PAGERID(pPager), pgno, pager_pagehash(pPg)));
2841 
2842   return rc;
2843 }
2844 
2845 #ifndef SQLITE_OMIT_WAL
2846 /*
2847 ** This function is invoked once for each page that has already been
2848 ** written into the log file when a WAL transaction is rolled back.
2849 ** Parameter iPg is the page number of said page. The pCtx argument
2850 ** is actually a pointer to the Pager structure.
2851 **
2852 ** If page iPg is present in the cache, and has no outstanding references,
2853 ** it is discarded. Otherwise, if there are one or more outstanding
2854 ** references, the page content is reloaded from the database. If the
2855 ** attempt to reload content from the database is required and fails,
2856 ** return an SQLite error code. Otherwise, SQLITE_OK.
2857 */
2858 static int pagerUndoCallback(void *pCtx, Pgno iPg){
2859   int rc = SQLITE_OK;
2860   Pager *pPager = (Pager *)pCtx;
2861   PgHdr *pPg;
2862 
2863   pPg = sqlite3PagerLookup(pPager, iPg);
2864   if( pPg ){
2865     if( sqlite3PcachePageRefcount(pPg)==1 ){
2866       sqlite3PcacheDrop(pPg);
2867     }else{
2868       rc = readDbPage(pPg);
2869       if( rc==SQLITE_OK ){
2870         pPager->xReiniter(pPg);
2871       }
2872       sqlite3PagerUnref(pPg);
2873     }
2874   }
2875 
2876   /* Normally, if a transaction is rolled back, any backup processes are
2877   ** updated as data is copied out of the rollback journal and into the
2878   ** database. This is not generally possible with a WAL database, as
2879   ** rollback involves simply truncating the log file. Therefore, if one
2880   ** or more frames have already been written to the log (and therefore
2881   ** also copied into the backup databases) as part of this transaction,
2882   ** the backups must be restarted.
2883   */
2884   sqlite3BackupRestart(pPager->pBackup);
2885 
2886   return rc;
2887 }
2888 
2889 /*
2890 ** This function is called to rollback a transaction on a WAL database.
2891 */
2892 static int pagerRollbackWal(Pager *pPager){
2893   int rc;                         /* Return Code */
2894   PgHdr *pList;                   /* List of dirty pages to revert */
2895 
2896   /* For all pages in the cache that are currently dirty or have already
2897   ** been written (but not committed) to the log file, do one of the
2898   ** following:
2899   **
2900   **   + Discard the cached page (if refcount==0), or
2901   **   + Reload page content from the database (if refcount>0).
2902   */
2903   pPager->dbSize = pPager->dbOrigSize;
2904   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
2905   pList = sqlite3PcacheDirtyList(pPager->pPCache);
2906   while( pList && rc==SQLITE_OK ){
2907     PgHdr *pNext = pList->pDirty;
2908     rc = pagerUndoCallback((void *)pPager, pList->pgno);
2909     pList = pNext;
2910   }
2911 
2912   return rc;
2913 }
2914 
2915 /*
2916 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
2917 ** the contents of the list of pages headed by pList (connected by pDirty),
2918 ** this function notifies any active backup processes that the pages have
2919 ** changed.
2920 */
2921 static int pagerWalFrames(
2922   Pager *pPager,                  /* Pager object */
2923   PgHdr *pList,                   /* List of frames to log */
2924   Pgno nTruncate,                 /* Database size after this commit */
2925   int isCommit,                   /* True if this is a commit */
2926   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
2927 ){
2928   int rc;                         /* Return code */
2929 
2930   assert( pPager->pWal );
2931   rc = sqlite3WalFrames(pPager->pWal,
2932       pPager->pageSize, pList, nTruncate, isCommit, sync_flags
2933   );
2934   if( rc==SQLITE_OK && pPager->pBackup ){
2935     PgHdr *p;
2936     for(p=pList; p; p=p->pDirty){
2937       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
2938     }
2939   }
2940 
2941 #ifdef SQLITE_CHECK_PAGES
2942   {
2943     PgHdr *p;
2944     for(p=pList; p; p=p->pDirty) pager_set_pagehash(p);
2945   }
2946 #endif
2947 
2948   return rc;
2949 }
2950 
2951 /*
2952 ** Begin a read transaction on the WAL.
2953 **
2954 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
2955 ** makes a snapshot of the database at the current point in time and preserves
2956 ** that snapshot for use by the reader in spite of concurrently changes by
2957 ** other writers or checkpointers.
2958 */
2959 static int pagerBeginReadTransaction(Pager *pPager){
2960   int rc;                         /* Return code */
2961   int changed = 0;                /* True if cache must be reset */
2962 
2963   assert( pagerUseWal(pPager) );
2964   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
2965 
2966   /* sqlite3WalEndReadTransaction() was not called for the previous
2967   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
2968   ** are in locking_mode=NORMAL and EndRead() was previously called,
2969   ** the duplicate call is harmless.
2970   */
2971   sqlite3WalEndReadTransaction(pPager->pWal);
2972 
2973   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
2974   if( rc==SQLITE_OK && changed ){
2975     pager_reset(pPager);
2976   }
2977 
2978   return rc;
2979 }
2980 #endif
2981 
2982 /*
2983 ** This function is called as part of the transition from PAGER_OPEN
2984 ** to PAGER_READER state to determine the size of the database file
2985 ** in pages (assuming the page size currently stored in Pager.pageSize).
2986 **
2987 ** If no error occurs, SQLITE_OK is returned and the size of the database
2988 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
2989 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
2990 */
2991 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
2992   Pgno nPage;                     /* Value to return via *pnPage */
2993 
2994   /* Query the WAL sub-system for the database size. The WalDbsize()
2995   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
2996   ** if the database size is not available. The database size is not
2997   ** available from the WAL sub-system if the log file is empty or
2998   ** contains no valid committed transactions.
2999   */
3000   assert( pPager->eState==PAGER_OPEN );
3001   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
3002   nPage = sqlite3WalDbsize(pPager->pWal);
3003 
3004   /* If the database size was not available from the WAL sub-system,
3005   ** determine it based on the size of the database file. If the size
3006   ** of the database file is not an integer multiple of the page-size,
3007   ** round down to the nearest page. Except, any file larger than 0
3008   ** bytes in size is considered to contain at least one page.
3009   */
3010   if( nPage==0 ){
3011     i64 n = 0;                    /* Size of db file in bytes */
3012     assert( isOpen(pPager->fd) || pPager->tempFile );
3013     if( isOpen(pPager->fd) ){
3014       int rc = sqlite3OsFileSize(pPager->fd, &n);
3015       if( rc!=SQLITE_OK ){
3016         return rc;
3017       }
3018     }
3019     nPage = (Pgno)(n / pPager->pageSize);
3020     if( nPage==0 && n>0 ){
3021       nPage = 1;
3022     }
3023   }
3024 
3025   /* If the current number of pages in the file is greater than the
3026   ** configured maximum pager number, increase the allowed limit so
3027   ** that the file can be read.
3028   */
3029   if( nPage>pPager->mxPgno ){
3030     pPager->mxPgno = (Pgno)nPage;
3031   }
3032 
3033   *pnPage = nPage;
3034   return SQLITE_OK;
3035 }
3036 
3037 #ifndef SQLITE_OMIT_WAL
3038 /*
3039 ** Check if the *-wal file that corresponds to the database opened by pPager
3040 ** exists if the database is not empy, or verify that the *-wal file does
3041 ** not exist (by deleting it) if the database file is empty.
3042 **
3043 ** If the database is not empty and the *-wal file exists, open the pager
3044 ** in WAL mode.  If the database is empty or if no *-wal file exists and
3045 ** if no error occurs, make sure Pager.journalMode is not set to
3046 ** PAGER_JOURNALMODE_WAL.
3047 **
3048 ** Return SQLITE_OK or an error code.
3049 **
3050 ** The caller must hold a SHARED lock on the database file to call this
3051 ** function. Because an EXCLUSIVE lock on the db file is required to delete
3052 ** a WAL on a none-empty database, this ensures there is no race condition
3053 ** between the xAccess() below and an xDelete() being executed by some
3054 ** other connection.
3055 */
3056 static int pagerOpenWalIfPresent(Pager *pPager){
3057   int rc = SQLITE_OK;
3058   assert( pPager->eState==PAGER_OPEN );
3059   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
3060 
3061   if( !pPager->tempFile ){
3062     int isWal;                    /* True if WAL file exists */
3063     Pgno nPage;                   /* Size of the database file */
3064 
3065     rc = pagerPagecount(pPager, &nPage);
3066     if( rc ) return rc;
3067     if( nPage==0 ){
3068       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
3069       isWal = 0;
3070     }else{
3071       rc = sqlite3OsAccess(
3072           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
3073       );
3074     }
3075     if( rc==SQLITE_OK ){
3076       if( isWal ){
3077         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
3078         rc = sqlite3PagerOpenWal(pPager, 0);
3079       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
3080         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
3081       }
3082     }
3083   }
3084   return rc;
3085 }
3086 #endif
3087 
3088 /*
3089 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
3090 ** the entire master journal file. The case pSavepoint==NULL occurs when
3091 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
3092 ** savepoint.
3093 **
3094 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
3095 ** being rolled back), then the rollback consists of up to three stages,
3096 ** performed in the order specified:
3097 **
3098 **   * Pages are played back from the main journal starting at byte
3099 **     offset PagerSavepoint.iOffset and continuing to
3100 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
3101 **     file if PagerSavepoint.iHdrOffset is zero.
3102 **
3103 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
3104 **     back starting from the journal header immediately following
3105 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
3106 **
3107 **   * Pages are then played back from the sub-journal file, starting
3108 **     with the PagerSavepoint.iSubRec and continuing to the end of
3109 **     the journal file.
3110 **
3111 ** Throughout the rollback process, each time a page is rolled back, the
3112 ** corresponding bit is set in a bitvec structure (variable pDone in the
3113 ** implementation below). This is used to ensure that a page is only
3114 ** rolled back the first time it is encountered in either journal.
3115 **
3116 ** If pSavepoint is NULL, then pages are only played back from the main
3117 ** journal file. There is no need for a bitvec in this case.
3118 **
3119 ** In either case, before playback commences the Pager.dbSize variable
3120 ** is reset to the value that it held at the start of the savepoint
3121 ** (or transaction). No page with a page-number greater than this value
3122 ** is played back. If one is encountered it is simply skipped.
3123 */
3124 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
3125   i64 szJ;                 /* Effective size of the main journal */
3126   i64 iHdrOff;             /* End of first segment of main-journal records */
3127   int rc = SQLITE_OK;      /* Return code */
3128   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
3129 
3130   assert( pPager->eState!=PAGER_ERROR );
3131   assert( pPager->eState>=PAGER_WRITER_LOCKED );
3132 
3133   /* Allocate a bitvec to use to store the set of pages rolled back */
3134   if( pSavepoint ){
3135     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
3136     if( !pDone ){
3137       return SQLITE_NOMEM;
3138     }
3139   }
3140 
3141   /* Set the database size back to the value it was before the savepoint
3142   ** being reverted was opened.
3143   */
3144   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
3145   pPager->changeCountDone = pPager->tempFile;
3146 
3147   if( !pSavepoint && pagerUseWal(pPager) ){
3148     return pagerRollbackWal(pPager);
3149   }
3150 
3151   /* Use pPager->journalOff as the effective size of the main rollback
3152   ** journal.  The actual file might be larger than this in
3153   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
3154   ** past pPager->journalOff is off-limits to us.
3155   */
3156   szJ = pPager->journalOff;
3157   assert( pagerUseWal(pPager)==0 || szJ==0 );
3158 
3159   /* Begin by rolling back records from the main journal starting at
3160   ** PagerSavepoint.iOffset and continuing to the next journal header.
3161   ** There might be records in the main journal that have a page number
3162   ** greater than the current database size (pPager->dbSize) but those
3163   ** will be skipped automatically.  Pages are added to pDone as they
3164   ** are played back.
3165   */
3166   if( pSavepoint && !pagerUseWal(pPager) ){
3167     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
3168     pPager->journalOff = pSavepoint->iOffset;
3169     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
3170       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
3171     }
3172     assert( rc!=SQLITE_DONE );
3173   }else{
3174     pPager->journalOff = 0;
3175   }
3176 
3177   /* Continue rolling back records out of the main journal starting at
3178   ** the first journal header seen and continuing until the effective end
3179   ** of the main journal file.  Continue to skip out-of-range pages and
3180   ** continue adding pages rolled back to pDone.
3181   */
3182   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
3183     u32 ii;            /* Loop counter */
3184     u32 nJRec = 0;     /* Number of Journal Records */
3185     u32 dummy;
3186     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
3187     assert( rc!=SQLITE_DONE );
3188 
3189     /*
3190     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
3191     ** test is related to ticket #2565.  See the discussion in the
3192     ** pager_playback() function for additional information.
3193     */
3194     if( nJRec==0
3195      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
3196     ){
3197       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
3198     }
3199     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
3200       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
3201     }
3202     assert( rc!=SQLITE_DONE );
3203   }
3204   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
3205 
3206   /* Finally,  rollback pages from the sub-journal.  Page that were
3207   ** previously rolled back out of the main journal (and are hence in pDone)
3208   ** will be skipped.  Out-of-range pages are also skipped.
3209   */
3210   if( pSavepoint ){
3211     u32 ii;            /* Loop counter */
3212     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
3213 
3214     if( pagerUseWal(pPager) ){
3215       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
3216     }
3217     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
3218       assert( offset==ii*(4+pPager->pageSize) );
3219       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
3220     }
3221     assert( rc!=SQLITE_DONE );
3222   }
3223 
3224   sqlite3BitvecDestroy(pDone);
3225   if( rc==SQLITE_OK ){
3226     pPager->journalOff = szJ;
3227   }
3228 
3229   return rc;
3230 }
3231 
3232 /*
3233 ** Change the maximum number of in-memory pages that are allowed.
3234 */
3235 void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
3236   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
3237 }
3238 
3239 /*
3240 ** Adjust the robustness of the database to damage due to OS crashes
3241 ** or power failures by changing the number of syncs()s when writing
3242 ** the rollback journal.  There are three levels:
3243 **
3244 **    OFF       sqlite3OsSync() is never called.  This is the default
3245 **              for temporary and transient files.
3246 **
3247 **    NORMAL    The journal is synced once before writes begin on the
3248 **              database.  This is normally adequate protection, but
3249 **              it is theoretically possible, though very unlikely,
3250 **              that an inopertune power failure could leave the journal
3251 **              in a state which would cause damage to the database
3252 **              when it is rolled back.
3253 **
3254 **    FULL      The journal is synced twice before writes begin on the
3255 **              database (with some additional information - the nRec field
3256 **              of the journal header - being written in between the two
3257 **              syncs).  If we assume that writing a
3258 **              single disk sector is atomic, then this mode provides
3259 **              assurance that the journal will not be corrupted to the
3260 **              point of causing damage to the database during rollback.
3261 **
3262 ** Numeric values associated with these states are OFF==1, NORMAL=2,
3263 ** and FULL=3.
3264 */
3265 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
3266 void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
3267   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
3268   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
3269   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
3270 }
3271 #endif
3272 
3273 /*
3274 ** The following global variable is incremented whenever the library
3275 ** attempts to open a temporary file.  This information is used for
3276 ** testing and analysis only.
3277 */
3278 #ifdef SQLITE_TEST
3279 int sqlite3_opentemp_count = 0;
3280 #endif
3281 
3282 /*
3283 ** Open a temporary file.
3284 **
3285 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
3286 ** or some other error code if we fail. The OS will automatically
3287 ** delete the temporary file when it is closed.
3288 **
3289 ** The flags passed to the VFS layer xOpen() call are those specified
3290 ** by parameter vfsFlags ORed with the following:
3291 **
3292 **     SQLITE_OPEN_READWRITE
3293 **     SQLITE_OPEN_CREATE
3294 **     SQLITE_OPEN_EXCLUSIVE
3295 **     SQLITE_OPEN_DELETEONCLOSE
3296 */
3297 static int pagerOpentemp(
3298   Pager *pPager,        /* The pager object */
3299   sqlite3_file *pFile,  /* Write the file descriptor here */
3300   int vfsFlags          /* Flags passed through to the VFS */
3301 ){
3302   int rc;               /* Return code */
3303 
3304 #ifdef SQLITE_TEST
3305   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
3306 #endif
3307 
3308   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
3309             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
3310   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
3311   assert( rc!=SQLITE_OK || isOpen(pFile) );
3312   return rc;
3313 }
3314 
3315 /*
3316 ** Set the busy handler function.
3317 **
3318 ** The pager invokes the busy-handler if sqlite3OsLock() returns
3319 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
3320 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
3321 ** lock. It does *not* invoke the busy handler when upgrading from
3322 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
3323 ** (which occurs during hot-journal rollback). Summary:
3324 **
3325 **   Transition                        | Invokes xBusyHandler
3326 **   --------------------------------------------------------
3327 **   NO_LOCK       -> SHARED_LOCK      | Yes
3328 **   SHARED_LOCK   -> RESERVED_LOCK    | No
3329 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
3330 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
3331 **
3332 ** If the busy-handler callback returns non-zero, the lock is
3333 ** retried. If it returns zero, then the SQLITE_BUSY error is
3334 ** returned to the caller of the pager API function.
3335 */
3336 void sqlite3PagerSetBusyhandler(
3337   Pager *pPager,                       /* Pager object */
3338   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
3339   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
3340 ){
3341   pPager->xBusyHandler = xBusyHandler;
3342   pPager->pBusyHandlerArg = pBusyHandlerArg;
3343 }
3344 
3345 /*
3346 ** Change the page size used by the Pager object. The new page size
3347 ** is passed in *pPageSize.
3348 **
3349 ** If the pager is in the error state when this function is called, it
3350 ** is a no-op. The value returned is the error state error code (i.e.
3351 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
3352 **
3353 ** Otherwise, if all of the following are true:
3354 **
3355 **   * the new page size (value of *pPageSize) is valid (a power
3356 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
3357 **
3358 **   * there are no outstanding page references, and
3359 **
3360 **   * the database is either not an in-memory database or it is
3361 **     an in-memory database that currently consists of zero pages.
3362 **
3363 ** then the pager object page size is set to *pPageSize.
3364 **
3365 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
3366 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
3367 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
3368 ** In all other cases, SQLITE_OK is returned.
3369 **
3370 ** If the page size is not changed, either because one of the enumerated
3371 ** conditions above is not true, the pager was in error state when this
3372 ** function was called, or because the memory allocation attempt failed,
3373 ** then *pPageSize is set to the old, retained page size before returning.
3374 */
3375 int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
3376   int rc = SQLITE_OK;
3377 
3378   /* It is not possible to do a full assert_pager_state() here, as this
3379   ** function may be called from within PagerOpen(), before the state
3380   ** of the Pager object is internally consistent.
3381   **
3382   ** At one point this function returned an error if the pager was in
3383   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
3384   ** there is at least one outstanding page reference, this function
3385   ** is a no-op for that case anyhow.
3386   */
3387 
3388   u32 pageSize = *pPageSize;
3389   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
3390   if( (pPager->memDb==0 || pPager->dbSize==0)
3391    && sqlite3PcacheRefCount(pPager->pPCache)==0
3392    && pageSize && pageSize!=(u32)pPager->pageSize
3393   ){
3394     char *pNew = NULL;             /* New temp space */
3395     i64 nByte = 0;
3396 
3397     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
3398       rc = sqlite3OsFileSize(pPager->fd, &nByte);
3399     }
3400     if( rc==SQLITE_OK ){
3401       pNew = (char *)sqlite3PageMalloc(pageSize);
3402       if( !pNew ) rc = SQLITE_NOMEM;
3403     }
3404 
3405     if( rc==SQLITE_OK ){
3406       pager_reset(pPager);
3407       pPager->dbSize = (Pgno)(nByte/pageSize);
3408       pPager->pageSize = pageSize;
3409       sqlite3PageFree(pPager->pTmpSpace);
3410       pPager->pTmpSpace = pNew;
3411       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
3412     }
3413   }
3414 
3415   *pPageSize = pPager->pageSize;
3416   if( rc==SQLITE_OK ){
3417     if( nReserve<0 ) nReserve = pPager->nReserve;
3418     assert( nReserve>=0 && nReserve<1000 );
3419     pPager->nReserve = (i16)nReserve;
3420     pagerReportSize(pPager);
3421   }
3422   return rc;
3423 }
3424 
3425 /*
3426 ** Return a pointer to the "temporary page" buffer held internally
3427 ** by the pager.  This is a buffer that is big enough to hold the
3428 ** entire content of a database page.  This buffer is used internally
3429 ** during rollback and will be overwritten whenever a rollback
3430 ** occurs.  But other modules are free to use it too, as long as
3431 ** no rollbacks are happening.
3432 */
3433 void *sqlite3PagerTempSpace(Pager *pPager){
3434   return pPager->pTmpSpace;
3435 }
3436 
3437 /*
3438 ** Attempt to set the maximum database page count if mxPage is positive.
3439 ** Make no changes if mxPage is zero or negative.  And never reduce the
3440 ** maximum page count below the current size of the database.
3441 **
3442 ** Regardless of mxPage, return the current maximum page count.
3443 */
3444 int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
3445   if( mxPage>0 ){
3446     pPager->mxPgno = mxPage;
3447   }
3448   if( pPager->eState!=PAGER_OPEN && pPager->mxPgno<pPager->dbSize ){
3449     pPager->mxPgno = pPager->dbSize;
3450   }
3451   return pPager->mxPgno;
3452 }
3453 
3454 /*
3455 ** The following set of routines are used to disable the simulated
3456 ** I/O error mechanism.  These routines are used to avoid simulated
3457 ** errors in places where we do not care about errors.
3458 **
3459 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
3460 ** and generate no code.
3461 */
3462 #ifdef SQLITE_TEST
3463 extern int sqlite3_io_error_pending;
3464 extern int sqlite3_io_error_hit;
3465 static int saved_cnt;
3466 void disable_simulated_io_errors(void){
3467   saved_cnt = sqlite3_io_error_pending;
3468   sqlite3_io_error_pending = -1;
3469 }
3470 void enable_simulated_io_errors(void){
3471   sqlite3_io_error_pending = saved_cnt;
3472 }
3473 #else
3474 # define disable_simulated_io_errors()
3475 # define enable_simulated_io_errors()
3476 #endif
3477 
3478 /*
3479 ** Read the first N bytes from the beginning of the file into memory
3480 ** that pDest points to.
3481 **
3482 ** If the pager was opened on a transient file (zFilename==""), or
3483 ** opened on a file less than N bytes in size, the output buffer is
3484 ** zeroed and SQLITE_OK returned. The rationale for this is that this
3485 ** function is used to read database headers, and a new transient or
3486 ** zero sized database has a header than consists entirely of zeroes.
3487 **
3488 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
3489 ** the error code is returned to the caller and the contents of the
3490 ** output buffer undefined.
3491 */
3492 int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
3493   int rc = SQLITE_OK;
3494   memset(pDest, 0, N);
3495   assert( isOpen(pPager->fd) || pPager->tempFile );
3496 
3497   /* This routine is only called by btree immediately after creating
3498   ** the Pager object.  There has not been an opportunity to transition
3499   ** to WAL mode yet.
3500   */
3501   assert( !pagerUseWal(pPager) );
3502 
3503   if( isOpen(pPager->fd) ){
3504     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
3505     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
3506     if( rc==SQLITE_IOERR_SHORT_READ ){
3507       rc = SQLITE_OK;
3508     }
3509   }
3510   return rc;
3511 }
3512 
3513 /*
3514 ** This function may only be called when a read-transaction is open on
3515 ** the pager. It returns the total number of pages in the database.
3516 **
3517 ** However, if the file is between 1 and <page-size> bytes in size, then
3518 ** this is considered a 1 page file.
3519 */
3520 void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
3521   assert( pPager->eState>=PAGER_READER );
3522   assert( pPager->eState!=PAGER_WRITER_FINISHED );
3523   *pnPage = (int)pPager->dbSize;
3524 }
3525 
3526 
3527 /*
3528 ** Try to obtain a lock of type locktype on the database file. If
3529 ** a similar or greater lock is already held, this function is a no-op
3530 ** (returning SQLITE_OK immediately).
3531 **
3532 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
3533 ** the busy callback if the lock is currently not available. Repeat
3534 ** until the busy callback returns false or until the attempt to
3535 ** obtain the lock succeeds.
3536 **
3537 ** Return SQLITE_OK on success and an error code if we cannot obtain
3538 ** the lock. If the lock is obtained successfully, set the Pager.state
3539 ** variable to locktype before returning.
3540 */
3541 static int pager_wait_on_lock(Pager *pPager, int locktype){
3542   int rc;                              /* Return code */
3543 
3544   /* Check that this is either a no-op (because the requested lock is
3545   ** already held, or one of the transistions that the busy-handler
3546   ** may be invoked during, according to the comment above
3547   ** sqlite3PagerSetBusyhandler().
3548   */
3549   assert( (pPager->eLock>=locktype)
3550        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
3551        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
3552   );
3553 
3554   do {
3555     rc = pagerLockDb(pPager, locktype);
3556   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
3557   return rc;
3558 }
3559 
3560 /*
3561 ** Function assertTruncateConstraint(pPager) checks that one of the
3562 ** following is true for all dirty pages currently in the page-cache:
3563 **
3564 **   a) The page number is less than or equal to the size of the
3565 **      current database image, in pages, OR
3566 **
3567 **   b) if the page content were written at this time, it would not
3568 **      be necessary to write the current content out to the sub-journal
3569 **      (as determined by function subjRequiresPage()).
3570 **
3571 ** If the condition asserted by this function were not true, and the
3572 ** dirty page were to be discarded from the cache via the pagerStress()
3573 ** routine, pagerStress() would not write the current page content to
3574 ** the database file. If a savepoint transaction were rolled back after
3575 ** this happened, the correct behaviour would be to restore the current
3576 ** content of the page. However, since this content is not present in either
3577 ** the database file or the portion of the rollback journal and
3578 ** sub-journal rolled back the content could not be restored and the
3579 ** database image would become corrupt. It is therefore fortunate that
3580 ** this circumstance cannot arise.
3581 */
3582 #if defined(SQLITE_DEBUG)
3583 static void assertTruncateConstraintCb(PgHdr *pPg){
3584   assert( pPg->flags&PGHDR_DIRTY );
3585   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
3586 }
3587 static void assertTruncateConstraint(Pager *pPager){
3588   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
3589 }
3590 #else
3591 # define assertTruncateConstraint(pPager)
3592 #endif
3593 
3594 /*
3595 ** Truncate the in-memory database file image to nPage pages. This
3596 ** function does not actually modify the database file on disk. It
3597 ** just sets the internal state of the pager object so that the
3598 ** truncation will be done when the current transaction is committed.
3599 */
3600 void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
3601   assert( pPager->dbSize>=nPage );
3602   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
3603   pPager->dbSize = nPage;
3604   assertTruncateConstraint(pPager);
3605 }
3606 
3607 
3608 /*
3609 ** This function is called before attempting a hot-journal rollback. It
3610 ** syncs the journal file to disk, then sets pPager->journalHdr to the
3611 ** size of the journal file so that the pager_playback() routine knows
3612 ** that the entire journal file has been synced.
3613 **
3614 ** Syncing a hot-journal to disk before attempting to roll it back ensures
3615 ** that if a power-failure occurs during the rollback, the process that
3616 ** attempts rollback following system recovery sees the same journal
3617 ** content as this process.
3618 **
3619 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
3620 ** an SQLite error code.
3621 */
3622 static int pagerSyncHotJournal(Pager *pPager){
3623   int rc = SQLITE_OK;
3624   if( !pPager->noSync ){
3625     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
3626   }
3627   if( rc==SQLITE_OK ){
3628     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
3629   }
3630   return rc;
3631 }
3632 
3633 /*
3634 ** Shutdown the page cache.  Free all memory and close all files.
3635 **
3636 ** If a transaction was in progress when this routine is called, that
3637 ** transaction is rolled back.  All outstanding pages are invalidated
3638 ** and their memory is freed.  Any attempt to use a page associated
3639 ** with this page cache after this function returns will likely
3640 ** result in a coredump.
3641 **
3642 ** This function always succeeds. If a transaction is active an attempt
3643 ** is made to roll it back. If an error occurs during the rollback
3644 ** a hot journal may be left in the filesystem but no error is returned
3645 ** to the caller.
3646 */
3647 int sqlite3PagerClose(Pager *pPager){
3648   u8 *pTmp = (u8 *)pPager->pTmpSpace;
3649 
3650   disable_simulated_io_errors();
3651   sqlite3BeginBenignMalloc();
3652   /* pPager->errCode = 0; */
3653   pPager->exclusiveMode = 0;
3654 #ifndef SQLITE_OMIT_WAL
3655   sqlite3WalClose(pPager->pWal,
3656     (pPager->noSync ? 0 : pPager->sync_flags),
3657     pPager->pageSize, pTmp
3658   );
3659   pPager->pWal = 0;
3660 #endif
3661   pager_reset(pPager);
3662   if( MEMDB ){
3663     pager_unlock(pPager);
3664   }else{
3665     /* If it is open, sync the journal file before calling UnlockAndRollback.
3666     ** If this is not done, then an unsynced portion of the open journal
3667     ** file may be played back into the database. If a power failure occurs
3668     ** while this is happening, the database could become corrupt.
3669     **
3670     ** If an error occurs while trying to sync the journal, shift the pager
3671     ** into the ERROR state. This causes UnlockAndRollback to unlock the
3672     ** database and close the journal file without attempting to roll it
3673     ** back or finalize it. The next database user will have to do hot-journal
3674     ** rollback before accessing the database file.
3675     */
3676     if( isOpen(pPager->jfd) ){
3677       pager_error(pPager, pagerSyncHotJournal(pPager));
3678     }
3679     pagerUnlockAndRollback(pPager);
3680   }
3681   sqlite3EndBenignMalloc();
3682   enable_simulated_io_errors();
3683   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
3684   IOTRACE(("CLOSE %p\n", pPager))
3685   sqlite3OsClose(pPager->jfd);
3686   sqlite3OsClose(pPager->fd);
3687   sqlite3PageFree(pTmp);
3688   sqlite3PcacheClose(pPager->pPCache);
3689 
3690 #ifdef SQLITE_HAS_CODEC
3691   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
3692 #endif
3693 
3694   assert( !pPager->aSavepoint && !pPager->pInJournal );
3695   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
3696 
3697   sqlite3_free(pPager);
3698   return SQLITE_OK;
3699 }
3700 
3701 #if !defined(NDEBUG) || defined(SQLITE_TEST)
3702 /*
3703 ** Return the page number for page pPg.
3704 */
3705 Pgno sqlite3PagerPagenumber(DbPage *pPg){
3706   return pPg->pgno;
3707 }
3708 #endif
3709 
3710 /*
3711 ** Increment the reference count for page pPg.
3712 */
3713 void sqlite3PagerRef(DbPage *pPg){
3714   sqlite3PcacheRef(pPg);
3715 }
3716 
3717 /*
3718 ** Sync the journal. In other words, make sure all the pages that have
3719 ** been written to the journal have actually reached the surface of the
3720 ** disk and can be restored in the event of a hot-journal rollback.
3721 **
3722 ** If the Pager.noSync flag is set, then this function is a no-op.
3723 ** Otherwise, the actions required depend on the journal-mode and the
3724 ** device characteristics of the the file-system, as follows:
3725 **
3726 **   * If the journal file is an in-memory journal file, no action need
3727 **     be taken.
3728 **
3729 **   * Otherwise, if the device does not support the SAFE_APPEND property,
3730 **     then the nRec field of the most recently written journal header
3731 **     is updated to contain the number of journal records that have
3732 **     been written following it. If the pager is operating in full-sync
3733 **     mode, then the journal file is synced before this field is updated.
3734 **
3735 **   * If the device does not support the SEQUENTIAL property, then
3736 **     journal file is synced.
3737 **
3738 ** Or, in pseudo-code:
3739 **
3740 **   if( NOT <in-memory journal> ){
3741 **     if( NOT SAFE_APPEND ){
3742 **       if( <full-sync mode> ) xSync(<journal file>);
3743 **       <update nRec field>
3744 **     }
3745 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
3746 **   }
3747 **
3748 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
3749 ** page currently held in memory before returning SQLITE_OK. If an IO
3750 ** error is encountered, then the IO error code is returned to the caller.
3751 */
3752 static int syncJournal(Pager *pPager, int newHdr){
3753   int rc;                         /* Return code */
3754 
3755   assert( pPager->eState==PAGER_WRITER_CACHEMOD
3756        || pPager->eState==PAGER_WRITER_DBMOD
3757   );
3758   assert( assert_pager_state(pPager) );
3759   assert( !pagerUseWal(pPager) );
3760 
3761   rc = sqlite3PagerExclusiveLock(pPager);
3762   if( rc!=SQLITE_OK ) return rc;
3763 
3764   if( !pPager->noSync ){
3765     assert( !pPager->tempFile );
3766     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
3767       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
3768       assert( isOpen(pPager->jfd) );
3769 
3770       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
3771         /* This block deals with an obscure problem. If the last connection
3772         ** that wrote to this database was operating in persistent-journal
3773         ** mode, then the journal file may at this point actually be larger
3774         ** than Pager.journalOff bytes. If the next thing in the journal
3775         ** file happens to be a journal-header (written as part of the
3776         ** previous connection's transaction), and a crash or power-failure
3777         ** occurs after nRec is updated but before this connection writes
3778         ** anything else to the journal file (or commits/rolls back its
3779         ** transaction), then SQLite may become confused when doing the
3780         ** hot-journal rollback following recovery. It may roll back all
3781         ** of this connections data, then proceed to rolling back the old,
3782         ** out-of-date data that follows it. Database corruption.
3783         **
3784         ** To work around this, if the journal file does appear to contain
3785         ** a valid header following Pager.journalOff, then write a 0x00
3786         ** byte to the start of it to prevent it from being recognized.
3787         **
3788         ** Variable iNextHdrOffset is set to the offset at which this
3789         ** problematic header will occur, if it exists. aMagic is used
3790         ** as a temporary buffer to inspect the first couple of bytes of
3791         ** the potential journal header.
3792         */
3793         i64 iNextHdrOffset;
3794         u8 aMagic[8];
3795         u8 zHeader[sizeof(aJournalMagic)+4];
3796 
3797         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
3798         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
3799 
3800         iNextHdrOffset = journalHdrOffset(pPager);
3801         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
3802         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
3803           static const u8 zerobyte = 0;
3804           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
3805         }
3806         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
3807           return rc;
3808         }
3809 
3810         /* Write the nRec value into the journal file header. If in
3811         ** full-synchronous mode, sync the journal first. This ensures that
3812         ** all data has really hit the disk before nRec is updated to mark
3813         ** it as a candidate for rollback.
3814         **
3815         ** This is not required if the persistent media supports the
3816         ** SAFE_APPEND property. Because in this case it is not possible
3817         ** for garbage data to be appended to the file, the nRec field
3818         ** is populated with 0xFFFFFFFF when the journal header is written
3819         ** and never needs to be updated.
3820         */
3821         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
3822           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
3823           IOTRACE(("JSYNC %p\n", pPager))
3824           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
3825           if( rc!=SQLITE_OK ) return rc;
3826         }
3827         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
3828         rc = sqlite3OsWrite(
3829             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
3830         );
3831         if( rc!=SQLITE_OK ) return rc;
3832       }
3833       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
3834         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
3835         IOTRACE(("JSYNC %p\n", pPager))
3836         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
3837           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
3838         );
3839         if( rc!=SQLITE_OK ) return rc;
3840       }
3841 
3842       pPager->journalHdr = pPager->journalOff;
3843       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
3844         pPager->nRec = 0;
3845         rc = writeJournalHdr(pPager);
3846         if( rc!=SQLITE_OK ) return rc;
3847       }
3848     }else{
3849       pPager->journalHdr = pPager->journalOff;
3850     }
3851   }
3852 
3853   /* Unless the pager is in noSync mode, the journal file was just
3854   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
3855   ** all pages.
3856   */
3857   sqlite3PcacheClearSyncFlags(pPager->pPCache);
3858   pPager->eState = PAGER_WRITER_DBMOD;
3859   assert( assert_pager_state(pPager) );
3860   return SQLITE_OK;
3861 }
3862 
3863 /*
3864 ** The argument is the first in a linked list of dirty pages connected
3865 ** by the PgHdr.pDirty pointer. This function writes each one of the
3866 ** in-memory pages in the list to the database file. The argument may
3867 ** be NULL, representing an empty list. In this case this function is
3868 ** a no-op.
3869 **
3870 ** The pager must hold at least a RESERVED lock when this function
3871 ** is called. Before writing anything to the database file, this lock
3872 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
3873 ** SQLITE_BUSY is returned and no data is written to the database file.
3874 **
3875 ** If the pager is a temp-file pager and the actual file-system file
3876 ** is not yet open, it is created and opened before any data is
3877 ** written out.
3878 **
3879 ** Once the lock has been upgraded and, if necessary, the file opened,
3880 ** the pages are written out to the database file in list order. Writing
3881 ** a page is skipped if it meets either of the following criteria:
3882 **
3883 **   * The page number is greater than Pager.dbSize, or
3884 **   * The PGHDR_DONT_WRITE flag is set on the page.
3885 **
3886 ** If writing out a page causes the database file to grow, Pager.dbFileSize
3887 ** is updated accordingly. If page 1 is written out, then the value cached
3888 ** in Pager.dbFileVers[] is updated to match the new value stored in
3889 ** the database file.
3890 **
3891 ** If everything is successful, SQLITE_OK is returned. If an IO error
3892 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
3893 ** be obtained, SQLITE_BUSY is returned.
3894 */
3895 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
3896   int rc = SQLITE_OK;                  /* Return code */
3897 
3898   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
3899   assert( !pagerUseWal(pPager) );
3900   assert( pPager->eState==PAGER_WRITER_DBMOD );
3901   assert( pPager->eLock==EXCLUSIVE_LOCK );
3902 
3903   /* If the file is a temp-file has not yet been opened, open it now. It
3904   ** is not possible for rc to be other than SQLITE_OK if this branch
3905   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
3906   */
3907   if( !isOpen(pPager->fd) ){
3908     assert( pPager->tempFile && rc==SQLITE_OK );
3909     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
3910   }
3911 
3912   /* Before the first write, give the VFS a hint of what the final
3913   ** file size will be.
3914   */
3915   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
3916   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
3917     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
3918     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
3919     pPager->dbHintSize = pPager->dbSize;
3920   }
3921 
3922   while( rc==SQLITE_OK && pList ){
3923     Pgno pgno = pList->pgno;
3924 
3925     /* If there are dirty pages in the page cache with page numbers greater
3926     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
3927     ** make the file smaller (presumably by auto-vacuum code). Do not write
3928     ** any such pages to the file.
3929     **
3930     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
3931     ** set (set by sqlite3PagerDontWrite()).
3932     */
3933     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
3934       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
3935       char *pData;                                   /* Data to write */
3936 
3937       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
3938 
3939       /* Encode the database */
3940       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
3941 
3942       /* Write out the page data. */
3943       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
3944 
3945       /* If page 1 was just written, update Pager.dbFileVers to match
3946       ** the value now stored in the database file. If writing this
3947       ** page caused the database file to grow, update dbFileSize.
3948       */
3949       if( pgno==1 ){
3950         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
3951       }
3952       if( pgno>pPager->dbFileSize ){
3953         pPager->dbFileSize = pgno;
3954       }
3955 
3956       /* Update any backup objects copying the contents of this pager. */
3957       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
3958 
3959       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
3960                    PAGERID(pPager), pgno, pager_pagehash(pList)));
3961       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
3962       PAGER_INCR(sqlite3_pager_writedb_count);
3963       PAGER_INCR(pPager->nWrite);
3964     }else{
3965       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
3966     }
3967     pager_set_pagehash(pList);
3968     pList = pList->pDirty;
3969   }
3970 
3971   return rc;
3972 }
3973 
3974 /*
3975 ** Ensure that the sub-journal file is open. If it is already open, this
3976 ** function is a no-op.
3977 **
3978 ** SQLITE_OK is returned if everything goes according to plan. An
3979 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
3980 ** fails.
3981 */
3982 static int openSubJournal(Pager *pPager){
3983   int rc = SQLITE_OK;
3984   if( !isOpen(pPager->sjfd) ){
3985     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
3986       sqlite3MemJournalOpen(pPager->sjfd);
3987     }else{
3988       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
3989     }
3990   }
3991   return rc;
3992 }
3993 
3994 /*
3995 ** Append a record of the current state of page pPg to the sub-journal.
3996 ** It is the callers responsibility to use subjRequiresPage() to check
3997 ** that it is really required before calling this function.
3998 **
3999 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
4000 ** for all open savepoints before returning.
4001 **
4002 ** This function returns SQLITE_OK if everything is successful, an IO
4003 ** error code if the attempt to write to the sub-journal fails, or
4004 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
4005 ** bitvec.
4006 */
4007 static int subjournalPage(PgHdr *pPg){
4008   int rc = SQLITE_OK;
4009   Pager *pPager = pPg->pPager;
4010   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
4011 
4012     /* Open the sub-journal, if it has not already been opened */
4013     assert( pPager->useJournal );
4014     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
4015     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
4016     assert( pagerUseWal(pPager)
4017          || pageInJournal(pPg)
4018          || pPg->pgno>pPager->dbOrigSize
4019     );
4020     rc = openSubJournal(pPager);
4021 
4022     /* If the sub-journal was opened successfully (or was already open),
4023     ** write the journal record into the file.  */
4024     if( rc==SQLITE_OK ){
4025       void *pData = pPg->pData;
4026       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
4027       char *pData2;
4028 
4029       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
4030       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
4031       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
4032       if( rc==SQLITE_OK ){
4033         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
4034       }
4035     }
4036   }
4037   if( rc==SQLITE_OK ){
4038     pPager->nSubRec++;
4039     assert( pPager->nSavepoint>0 );
4040     rc = addToSavepointBitvecs(pPager, pPg->pgno);
4041   }
4042   return rc;
4043 }
4044 
4045 /*
4046 ** This function is called by the pcache layer when it has reached some
4047 ** soft memory limit. The first argument is a pointer to a Pager object
4048 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
4049 ** database). The second argument is a reference to a page that is
4050 ** currently dirty but has no outstanding references. The page
4051 ** is always associated with the Pager object passed as the first
4052 ** argument.
4053 **
4054 ** The job of this function is to make pPg clean by writing its contents
4055 ** out to the database file, if possible. This may involve syncing the
4056 ** journal file.
4057 **
4058 ** If successful, sqlite3PcacheMakeClean() is called on the page and
4059 ** SQLITE_OK returned. If an IO error occurs while trying to make the
4060 ** page clean, the IO error code is returned. If the page cannot be
4061 ** made clean for some other reason, but no error occurs, then SQLITE_OK
4062 ** is returned by sqlite3PcacheMakeClean() is not called.
4063 */
4064 static int pagerStress(void *p, PgHdr *pPg){
4065   Pager *pPager = (Pager *)p;
4066   int rc = SQLITE_OK;
4067 
4068   assert( pPg->pPager==pPager );
4069   assert( pPg->flags&PGHDR_DIRTY );
4070 
4071   /* The doNotSyncSpill flag is set during times when doing a sync of
4072   ** journal (and adding a new header) is not allowed.  This occurs
4073   ** during calls to sqlite3PagerWrite() while trying to journal multiple
4074   ** pages belonging to the same sector.
4075   **
4076   ** The doNotSpill flag inhibits all cache spilling regardless of whether
4077   ** or not a sync is required.  This is set during a rollback.
4078   **
4079   ** Spilling is also prohibited when in an error state since that could
4080   ** lead to database corruption.   In the current implementaton it
4081   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
4082   ** while in the error state, hence it is impossible for this routine to
4083   ** be called in the error state.  Nevertheless, we include a NEVER()
4084   ** test for the error state as a safeguard against future changes.
4085   */
4086   if( NEVER(pPager->errCode) ) return SQLITE_OK;
4087   if( pPager->doNotSpill ) return SQLITE_OK;
4088   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
4089     return SQLITE_OK;
4090   }
4091 
4092   pPg->pDirty = 0;
4093   if( pagerUseWal(pPager) ){
4094     /* Write a single frame for this page to the log. */
4095     if( subjRequiresPage(pPg) ){
4096       rc = subjournalPage(pPg);
4097     }
4098     if( rc==SQLITE_OK ){
4099       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
4100     }
4101   }else{
4102 
4103     /* Sync the journal file if required. */
4104     if( pPg->flags&PGHDR_NEED_SYNC
4105      || pPager->eState==PAGER_WRITER_CACHEMOD
4106     ){
4107       rc = syncJournal(pPager, 1);
4108     }
4109 
4110     /* If the page number of this page is larger than the current size of
4111     ** the database image, it may need to be written to the sub-journal.
4112     ** This is because the call to pager_write_pagelist() below will not
4113     ** actually write data to the file in this case.
4114     **
4115     ** Consider the following sequence of events:
4116     **
4117     **   BEGIN;
4118     **     <journal page X>
4119     **     <modify page X>
4120     **     SAVEPOINT sp;
4121     **       <shrink database file to Y pages>
4122     **       pagerStress(page X)
4123     **     ROLLBACK TO sp;
4124     **
4125     ** If (X>Y), then when pagerStress is called page X will not be written
4126     ** out to the database file, but will be dropped from the cache. Then,
4127     ** following the "ROLLBACK TO sp" statement, reading page X will read
4128     ** data from the database file. This will be the copy of page X as it
4129     ** was when the transaction started, not as it was when "SAVEPOINT sp"
4130     ** was executed.
4131     **
4132     ** The solution is to write the current data for page X into the
4133     ** sub-journal file now (if it is not already there), so that it will
4134     ** be restored to its current value when the "ROLLBACK TO sp" is
4135     ** executed.
4136     */
4137     if( NEVER(
4138         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
4139     ) ){
4140       rc = subjournalPage(pPg);
4141     }
4142 
4143     /* Write the contents of the page out to the database file. */
4144     if( rc==SQLITE_OK ){
4145       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
4146       rc = pager_write_pagelist(pPager, pPg);
4147     }
4148   }
4149 
4150   /* Mark the page as clean. */
4151   if( rc==SQLITE_OK ){
4152     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
4153     sqlite3PcacheMakeClean(pPg);
4154   }
4155 
4156   return pager_error(pPager, rc);
4157 }
4158 
4159 
4160 /*
4161 ** Allocate and initialize a new Pager object and put a pointer to it
4162 ** in *ppPager. The pager should eventually be freed by passing it
4163 ** to sqlite3PagerClose().
4164 **
4165 ** The zFilename argument is the path to the database file to open.
4166 ** If zFilename is NULL then a randomly-named temporary file is created
4167 ** and used as the file to be cached. Temporary files are be deleted
4168 ** automatically when they are closed. If zFilename is ":memory:" then
4169 ** all information is held in cache. It is never written to disk.
4170 ** This can be used to implement an in-memory database.
4171 **
4172 ** The nExtra parameter specifies the number of bytes of space allocated
4173 ** along with each page reference. This space is available to the user
4174 ** via the sqlite3PagerGetExtra() API.
4175 **
4176 ** The flags argument is used to specify properties that affect the
4177 ** operation of the pager. It should be passed some bitwise combination
4178 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
4179 **
4180 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
4181 ** of the xOpen() method of the supplied VFS when opening files.
4182 **
4183 ** If the pager object is allocated and the specified file opened
4184 ** successfully, SQLITE_OK is returned and *ppPager set to point to
4185 ** the new pager object. If an error occurs, *ppPager is set to NULL
4186 ** and error code returned. This function may return SQLITE_NOMEM
4187 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
4188 ** various SQLITE_IO_XXX errors.
4189 */
4190 int sqlite3PagerOpen(
4191   sqlite3_vfs *pVfs,       /* The virtual file system to use */
4192   Pager **ppPager,         /* OUT: Return the Pager structure here */
4193   const char *zFilename,   /* Name of the database file to open */
4194   int nExtra,              /* Extra bytes append to each in-memory page */
4195   int flags,               /* flags controlling this file */
4196   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
4197   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
4198 ){
4199   u8 *pPtr;
4200   Pager *pPager = 0;       /* Pager object to allocate and return */
4201   int rc = SQLITE_OK;      /* Return code */
4202   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
4203   int memDb = 0;           /* True if this is an in-memory file */
4204   int readOnly = 0;        /* True if this is a read-only file */
4205   int journalFileSize;     /* Bytes to allocate for each journal fd */
4206   char *zPathname = 0;     /* Full path to database file */
4207   int nPathname = 0;       /* Number of bytes in zPathname */
4208   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
4209   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
4210   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
4211   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
4212 
4213   /* Figure out how much space is required for each journal file-handle
4214   ** (there are two of them, the main journal and the sub-journal). This
4215   ** is the maximum space required for an in-memory journal file handle
4216   ** and a regular journal file-handle. Note that a "regular journal-handle"
4217   ** may be a wrapper capable of caching the first portion of the journal
4218   ** file in memory to implement the atomic-write optimization (see
4219   ** source file journal.c).
4220   */
4221   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
4222     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
4223   }else{
4224     journalFileSize = ROUND8(sqlite3MemJournalSize());
4225   }
4226 
4227   /* Set the output variable to NULL in case an error occurs. */
4228   *ppPager = 0;
4229 
4230 #ifndef SQLITE_OMIT_MEMORYDB
4231   if( flags & PAGER_MEMORY ){
4232     memDb = 1;
4233     zFilename = 0;
4234   }
4235 #endif
4236 
4237   /* Compute and store the full pathname in an allocated buffer pointed
4238   ** to by zPathname, length nPathname. Or, if this is a temporary file,
4239   ** leave both nPathname and zPathname set to 0.
4240   */
4241   if( zFilename && zFilename[0] ){
4242     nPathname = pVfs->mxPathname+1;
4243     zPathname = sqlite3Malloc(nPathname*2);
4244     if( zPathname==0 ){
4245       return SQLITE_NOMEM;
4246     }
4247     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
4248     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
4249     nPathname = sqlite3Strlen30(zPathname);
4250     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
4251       /* This branch is taken when the journal path required by
4252       ** the database being opened will be more than pVfs->mxPathname
4253       ** bytes in length. This means the database cannot be opened,
4254       ** as it will not be possible to open the journal file or even
4255       ** check for a hot-journal before reading.
4256       */
4257       rc = SQLITE_CANTOPEN_BKPT;
4258     }
4259     if( rc!=SQLITE_OK ){
4260       sqlite3_free(zPathname);
4261       return rc;
4262     }
4263   }
4264 
4265   /* Allocate memory for the Pager structure, PCache object, the
4266   ** three file descriptors, the database file name and the journal
4267   ** file name. The layout in memory is as follows:
4268   **
4269   **     Pager object                    (sizeof(Pager) bytes)
4270   **     PCache object                   (sqlite3PcacheSize() bytes)
4271   **     Database file handle            (pVfs->szOsFile bytes)
4272   **     Sub-journal file handle         (journalFileSize bytes)
4273   **     Main journal file handle        (journalFileSize bytes)
4274   **     Database file name              (nPathname+1 bytes)
4275   **     Journal file name               (nPathname+8+1 bytes)
4276   */
4277   pPtr = (u8 *)sqlite3MallocZero(
4278     ROUND8(sizeof(*pPager)) +      /* Pager structure */
4279     ROUND8(pcacheSize) +           /* PCache object */
4280     ROUND8(pVfs->szOsFile) +       /* The main db file */
4281     journalFileSize * 2 +          /* The two journal files */
4282     nPathname + 1 +                /* zFilename */
4283     nPathname + 8 + 1              /* zJournal */
4284 #ifndef SQLITE_OMIT_WAL
4285     + nPathname + 4 + 1              /* zWal */
4286 #endif
4287   );
4288   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
4289   if( !pPtr ){
4290     sqlite3_free(zPathname);
4291     return SQLITE_NOMEM;
4292   }
4293   pPager =              (Pager*)(pPtr);
4294   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
4295   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
4296   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
4297   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
4298   pPager->zFilename =    (char*)(pPtr += journalFileSize);
4299   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
4300 
4301   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
4302   if( zPathname ){
4303     assert( nPathname>0 );
4304     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
4305     memcpy(pPager->zFilename, zPathname, nPathname);
4306     memcpy(pPager->zJournal, zPathname, nPathname);
4307     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
4308 #ifndef SQLITE_OMIT_WAL
4309     pPager->zWal = &pPager->zJournal[nPathname+8+1];
4310     memcpy(pPager->zWal, zPathname, nPathname);
4311     memcpy(&pPager->zWal[nPathname], "-wal", 4);
4312 #endif
4313     sqlite3_free(zPathname);
4314   }
4315   pPager->pVfs = pVfs;
4316   pPager->vfsFlags = vfsFlags;
4317 
4318   /* Open the pager file.
4319   */
4320   if( zFilename && zFilename[0] ){
4321     int fout = 0;                    /* VFS flags returned by xOpen() */
4322     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
4323     assert( !memDb );
4324     readOnly = (fout&SQLITE_OPEN_READONLY);
4325 
4326     /* If the file was successfully opened for read/write access,
4327     ** choose a default page size in case we have to create the
4328     ** database file. The default page size is the maximum of:
4329     **
4330     **    + SQLITE_DEFAULT_PAGE_SIZE,
4331     **    + The value returned by sqlite3OsSectorSize()
4332     **    + The largest page size that can be written atomically.
4333     */
4334     if( rc==SQLITE_OK && !readOnly ){
4335       setSectorSize(pPager);
4336       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
4337       if( szPageDflt<pPager->sectorSize ){
4338         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
4339           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
4340         }else{
4341           szPageDflt = (u32)pPager->sectorSize;
4342         }
4343       }
4344 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
4345       {
4346         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
4347         int ii;
4348         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
4349         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
4350         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
4351         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
4352           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
4353             szPageDflt = ii;
4354           }
4355         }
4356       }
4357 #endif
4358     }
4359   }else{
4360     /* If a temporary file is requested, it is not opened immediately.
4361     ** In this case we accept the default page size and delay actually
4362     ** opening the file until the first call to OsWrite().
4363     **
4364     ** This branch is also run for an in-memory database. An in-memory
4365     ** database is the same as a temp-file that is never written out to
4366     ** disk and uses an in-memory rollback journal.
4367     */
4368     tempFile = 1;
4369     pPager->eState = PAGER_READER;
4370     pPager->eLock = EXCLUSIVE_LOCK;
4371     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
4372   }
4373 
4374   /* The following call to PagerSetPagesize() serves to set the value of
4375   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
4376   */
4377   if( rc==SQLITE_OK ){
4378     assert( pPager->memDb==0 );
4379     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
4380     testcase( rc!=SQLITE_OK );
4381   }
4382 
4383   /* If an error occurred in either of the blocks above, free the
4384   ** Pager structure and close the file.
4385   */
4386   if( rc!=SQLITE_OK ){
4387     assert( !pPager->pTmpSpace );
4388     sqlite3OsClose(pPager->fd);
4389     sqlite3_free(pPager);
4390     return rc;
4391   }
4392 
4393   /* Initialize the PCache object. */
4394   assert( nExtra<1000 );
4395   nExtra = ROUND8(nExtra);
4396   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
4397                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
4398 
4399   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
4400   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
4401 
4402   pPager->useJournal = (u8)useJournal;
4403   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
4404   /* pPager->stmtOpen = 0; */
4405   /* pPager->stmtInUse = 0; */
4406   /* pPager->nRef = 0; */
4407   /* pPager->stmtSize = 0; */
4408   /* pPager->stmtJSize = 0; */
4409   /* pPager->nPage = 0; */
4410   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
4411   /* pPager->state = PAGER_UNLOCK; */
4412 #if 0
4413   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
4414 #endif
4415   /* pPager->errMask = 0; */
4416   pPager->tempFile = (u8)tempFile;
4417   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
4418           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
4419   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
4420   pPager->exclusiveMode = (u8)tempFile;
4421   pPager->changeCountDone = pPager->tempFile;
4422   pPager->memDb = (u8)memDb;
4423   pPager->readOnly = (u8)readOnly;
4424   assert( useJournal || pPager->tempFile );
4425   pPager->noSync = pPager->tempFile;
4426   pPager->fullSync = pPager->noSync ?0:1;
4427   pPager->sync_flags = SQLITE_SYNC_NORMAL;
4428   /* pPager->pFirst = 0; */
4429   /* pPager->pFirstSynced = 0; */
4430   /* pPager->pLast = 0; */
4431   pPager->nExtra = (u16)nExtra;
4432   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
4433   assert( isOpen(pPager->fd) || tempFile );
4434   setSectorSize(pPager);
4435   if( !useJournal ){
4436     pPager->journalMode = PAGER_JOURNALMODE_OFF;
4437   }else if( memDb ){
4438     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
4439   }
4440   /* pPager->xBusyHandler = 0; */
4441   /* pPager->pBusyHandlerArg = 0; */
4442   pPager->xReiniter = xReinit;
4443   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
4444 
4445   *ppPager = pPager;
4446   return SQLITE_OK;
4447 }
4448 
4449 
4450 
4451 /*
4452 ** This function is called after transitioning from PAGER_UNLOCK to
4453 ** PAGER_SHARED state. It tests if there is a hot journal present in
4454 ** the file-system for the given pager. A hot journal is one that
4455 ** needs to be played back. According to this function, a hot-journal
4456 ** file exists if the following criteria are met:
4457 **
4458 **   * The journal file exists in the file system, and
4459 **   * No process holds a RESERVED or greater lock on the database file, and
4460 **   * The database file itself is greater than 0 bytes in size, and
4461 **   * The first byte of the journal file exists and is not 0x00.
4462 **
4463 ** If the current size of the database file is 0 but a journal file
4464 ** exists, that is probably an old journal left over from a prior
4465 ** database with the same name. In this case the journal file is
4466 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
4467 ** is returned.
4468 **
4469 ** This routine does not check if there is a master journal filename
4470 ** at the end of the file. If there is, and that master journal file
4471 ** does not exist, then the journal file is not really hot. In this
4472 ** case this routine will return a false-positive. The pager_playback()
4473 ** routine will discover that the journal file is not really hot and
4474 ** will not roll it back.
4475 **
4476 ** If a hot-journal file is found to exist, *pExists is set to 1 and
4477 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
4478 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
4479 ** to determine whether or not a hot-journal file exists, the IO error
4480 ** code is returned and the value of *pExists is undefined.
4481 */
4482 static int hasHotJournal(Pager *pPager, int *pExists){
4483   sqlite3_vfs * const pVfs = pPager->pVfs;
4484   int rc = SQLITE_OK;           /* Return code */
4485   int exists = 1;               /* True if a journal file is present */
4486   int jrnlOpen = !!isOpen(pPager->jfd);
4487 
4488   assert( pPager->useJournal );
4489   assert( isOpen(pPager->fd) );
4490   assert( pPager->eState==PAGER_OPEN );
4491 
4492   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
4493     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
4494   ));
4495 
4496   *pExists = 0;
4497   if( !jrnlOpen ){
4498     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
4499   }
4500   if( rc==SQLITE_OK && exists ){
4501     int locked = 0;             /* True if some process holds a RESERVED lock */
4502 
4503     /* Race condition here:  Another process might have been holding the
4504     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
4505     ** call above, but then delete the journal and drop the lock before
4506     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
4507     ** is the case, this routine might think there is a hot journal when
4508     ** in fact there is none.  This results in a false-positive which will
4509     ** be dealt with by the playback routine.  Ticket #3883.
4510     */
4511     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
4512     if( rc==SQLITE_OK && !locked ){
4513       Pgno nPage;                 /* Number of pages in database file */
4514 
4515       /* Check the size of the database file. If it consists of 0 pages,
4516       ** then delete the journal file. See the header comment above for
4517       ** the reasoning here.  Delete the obsolete journal file under
4518       ** a RESERVED lock to avoid race conditions and to avoid violating
4519       ** [H33020].
4520       */
4521       rc = pagerPagecount(pPager, &nPage);
4522       if( rc==SQLITE_OK ){
4523         if( nPage==0 ){
4524           sqlite3BeginBenignMalloc();
4525           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
4526             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
4527             pagerUnlockDb(pPager, SHARED_LOCK);
4528           }
4529           sqlite3EndBenignMalloc();
4530         }else{
4531           /* The journal file exists and no other connection has a reserved
4532           ** or greater lock on the database file. Now check that there is
4533           ** at least one non-zero bytes at the start of the journal file.
4534           ** If there is, then we consider this journal to be hot. If not,
4535           ** it can be ignored.
4536           */
4537           if( !jrnlOpen ){
4538             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
4539             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
4540           }
4541           if( rc==SQLITE_OK ){
4542             u8 first = 0;
4543             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
4544             if( rc==SQLITE_IOERR_SHORT_READ ){
4545               rc = SQLITE_OK;
4546             }
4547             if( !jrnlOpen ){
4548               sqlite3OsClose(pPager->jfd);
4549             }
4550             *pExists = (first!=0);
4551           }else if( rc==SQLITE_CANTOPEN ){
4552             /* If we cannot open the rollback journal file in order to see if
4553             ** its has a zero header, that might be due to an I/O error, or
4554             ** it might be due to the race condition described above and in
4555             ** ticket #3883.  Either way, assume that the journal is hot.
4556             ** This might be a false positive.  But if it is, then the
4557             ** automatic journal playback and recovery mechanism will deal
4558             ** with it under an EXCLUSIVE lock where we do not need to
4559             ** worry so much with race conditions.
4560             */
4561             *pExists = 1;
4562             rc = SQLITE_OK;
4563           }
4564         }
4565       }
4566     }
4567   }
4568 
4569   return rc;
4570 }
4571 
4572 /*
4573 ** This function is called to obtain a shared lock on the database file.
4574 ** It is illegal to call sqlite3PagerAcquire() until after this function
4575 ** has been successfully called. If a shared-lock is already held when
4576 ** this function is called, it is a no-op.
4577 **
4578 ** The following operations are also performed by this function.
4579 **
4580 **   1) If the pager is currently in PAGER_OPEN state (no lock held
4581 **      on the database file), then an attempt is made to obtain a
4582 **      SHARED lock on the database file. Immediately after obtaining
4583 **      the SHARED lock, the file-system is checked for a hot-journal,
4584 **      which is played back if present. Following any hot-journal
4585 **      rollback, the contents of the cache are validated by checking
4586 **      the 'change-counter' field of the database file header and
4587 **      discarded if they are found to be invalid.
4588 **
4589 **   2) If the pager is running in exclusive-mode, and there are currently
4590 **      no outstanding references to any pages, and is in the error state,
4591 **      then an attempt is made to clear the error state by discarding
4592 **      the contents of the page cache and rolling back any open journal
4593 **      file.
4594 **
4595 ** If everything is successful, SQLITE_OK is returned. If an IO error
4596 ** occurs while locking the database, checking for a hot-journal file or
4597 ** rolling back a journal file, the IO error code is returned.
4598 */
4599 int sqlite3PagerSharedLock(Pager *pPager){
4600   int rc = SQLITE_OK;                /* Return code */
4601 
4602   /* This routine is only called from b-tree and only when there are no
4603   ** outstanding pages. This implies that the pager state should either
4604   ** be OPEN or READER. READER is only possible if the pager is or was in
4605   ** exclusive access mode.
4606   */
4607   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
4608   assert( assert_pager_state(pPager) );
4609   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
4610   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
4611 
4612   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
4613     int bHotJournal = 1;          /* True if there exists a hot journal-file */
4614 
4615     assert( !MEMDB );
4616     assert( pPager->noReadlock==0 || pPager->readOnly );
4617 
4618     if( pPager->noReadlock==0 ){
4619       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
4620       if( rc!=SQLITE_OK ){
4621         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
4622         goto failed;
4623       }
4624     }
4625 
4626     /* If a journal file exists, and there is no RESERVED lock on the
4627     ** database file, then it either needs to be played back or deleted.
4628     */
4629     if( pPager->eLock<=SHARED_LOCK ){
4630       rc = hasHotJournal(pPager, &bHotJournal);
4631     }
4632     if( rc!=SQLITE_OK ){
4633       goto failed;
4634     }
4635     if( bHotJournal ){
4636       /* Get an EXCLUSIVE lock on the database file. At this point it is
4637       ** important that a RESERVED lock is not obtained on the way to the
4638       ** EXCLUSIVE lock. If it were, another process might open the
4639       ** database file, detect the RESERVED lock, and conclude that the
4640       ** database is safe to read while this process is still rolling the
4641       ** hot-journal back.
4642       **
4643       ** Because the intermediate RESERVED lock is not requested, any
4644       ** other process attempting to access the database file will get to
4645       ** this point in the code and fail to obtain its own EXCLUSIVE lock
4646       ** on the database file.
4647       **
4648       ** Unless the pager is in locking_mode=exclusive mode, the lock is
4649       ** downgraded to SHARED_LOCK before this function returns.
4650       */
4651       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
4652       if( rc!=SQLITE_OK ){
4653         goto failed;
4654       }
4655 
4656       /* If it is not already open and the file exists on disk, open the
4657       ** journal for read/write access. Write access is required because
4658       ** in exclusive-access mode the file descriptor will be kept open
4659       ** and possibly used for a transaction later on. Also, write-access
4660       ** is usually required to finalize the journal in journal_mode=persist
4661       ** mode (and also for journal_mode=truncate on some systems).
4662       **
4663       ** If the journal does not exist, it usually means that some
4664       ** other connection managed to get in and roll it back before
4665       ** this connection obtained the exclusive lock above. Or, it
4666       ** may mean that the pager was in the error-state when this
4667       ** function was called and the journal file does not exist.
4668       */
4669       if( !isOpen(pPager->jfd) ){
4670         sqlite3_vfs * const pVfs = pPager->pVfs;
4671         int bExists;              /* True if journal file exists */
4672         rc = sqlite3OsAccess(
4673             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
4674         if( rc==SQLITE_OK && bExists ){
4675           int fout = 0;
4676           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
4677           assert( !pPager->tempFile );
4678           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
4679           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
4680           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
4681             rc = SQLITE_CANTOPEN_BKPT;
4682             sqlite3OsClose(pPager->jfd);
4683           }
4684         }
4685       }
4686 
4687       /* Playback and delete the journal.  Drop the database write
4688       ** lock and reacquire the read lock. Purge the cache before
4689       ** playing back the hot-journal so that we don't end up with
4690       ** an inconsistent cache.  Sync the hot journal before playing
4691       ** it back since the process that crashed and left the hot journal
4692       ** probably did not sync it and we are required to always sync
4693       ** the journal before playing it back.
4694       */
4695       if( isOpen(pPager->jfd) ){
4696         assert( rc==SQLITE_OK );
4697         rc = pagerSyncHotJournal(pPager);
4698         if( rc==SQLITE_OK ){
4699           rc = pager_playback(pPager, 1);
4700           pPager->eState = PAGER_OPEN;
4701         }
4702       }else if( !pPager->exclusiveMode ){
4703         pagerUnlockDb(pPager, SHARED_LOCK);
4704       }
4705 
4706       if( rc!=SQLITE_OK ){
4707         /* This branch is taken if an error occurs while trying to open
4708         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
4709         ** pager_unlock() routine will be called before returning to unlock
4710         ** the file. If the unlock attempt fails, then Pager.eLock must be
4711         ** set to UNKNOWN_LOCK (see the comment above the #define for
4712         ** UNKNOWN_LOCK above for an explanation).
4713         **
4714         ** In order to get pager_unlock() to do this, set Pager.eState to
4715         ** PAGER_ERROR now. This is not actually counted as a transition
4716         ** to ERROR state in the state diagram at the top of this file,
4717         ** since we know that the same call to pager_unlock() will very
4718         ** shortly transition the pager object to the OPEN state. Calling
4719         ** assert_pager_state() would fail now, as it should not be possible
4720         ** to be in ERROR state when there are zero outstanding page
4721         ** references.
4722         */
4723         pager_error(pPager, rc);
4724         goto failed;
4725       }
4726 
4727       assert( pPager->eState==PAGER_OPEN );
4728       assert( (pPager->eLock==SHARED_LOCK)
4729            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
4730       );
4731     }
4732 
4733     if( !pPager->tempFile
4734      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
4735     ){
4736       /* The shared-lock has just been acquired on the database file
4737       ** and there are already pages in the cache (from a previous
4738       ** read or write transaction).  Check to see if the database
4739       ** has been modified.  If the database has changed, flush the
4740       ** cache.
4741       **
4742       ** Database changes is detected by looking at 15 bytes beginning
4743       ** at offset 24 into the file.  The first 4 of these 16 bytes are
4744       ** a 32-bit counter that is incremented with each change.  The
4745       ** other bytes change randomly with each file change when
4746       ** a codec is in use.
4747       **
4748       ** There is a vanishingly small chance that a change will not be
4749       ** detected.  The chance of an undetected change is so small that
4750       ** it can be neglected.
4751       */
4752       Pgno nPage = 0;
4753       char dbFileVers[sizeof(pPager->dbFileVers)];
4754 
4755       rc = pagerPagecount(pPager, &nPage);
4756       if( rc ) goto failed;
4757 
4758       if( nPage>0 ){
4759         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
4760         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
4761         if( rc!=SQLITE_OK ){
4762           goto failed;
4763         }
4764       }else{
4765         memset(dbFileVers, 0, sizeof(dbFileVers));
4766       }
4767 
4768       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
4769         pager_reset(pPager);
4770       }
4771     }
4772 
4773     /* If there is a WAL file in the file-system, open this database in WAL
4774     ** mode. Otherwise, the following function call is a no-op.
4775     */
4776     rc = pagerOpenWalIfPresent(pPager);
4777 #ifndef SQLITE_OMIT_WAL
4778     assert( pPager->pWal==0 || rc==SQLITE_OK );
4779 #endif
4780   }
4781 
4782   if( pagerUseWal(pPager) ){
4783     assert( rc==SQLITE_OK );
4784     rc = pagerBeginReadTransaction(pPager);
4785   }
4786 
4787   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
4788     rc = pagerPagecount(pPager, &pPager->dbSize);
4789   }
4790 
4791  failed:
4792   if( rc!=SQLITE_OK ){
4793     assert( !MEMDB );
4794     pager_unlock(pPager);
4795     assert( pPager->eState==PAGER_OPEN );
4796   }else{
4797     pPager->eState = PAGER_READER;
4798   }
4799   return rc;
4800 }
4801 
4802 /*
4803 ** If the reference count has reached zero, rollback any active
4804 ** transaction and unlock the pager.
4805 **
4806 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
4807 ** the rollback journal, the unlock is not performed and there is
4808 ** nothing to rollback, so this routine is a no-op.
4809 */
4810 static void pagerUnlockIfUnused(Pager *pPager){
4811   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
4812     pagerUnlockAndRollback(pPager);
4813   }
4814 }
4815 
4816 /*
4817 ** Acquire a reference to page number pgno in pager pPager (a page
4818 ** reference has type DbPage*). If the requested reference is
4819 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
4820 **
4821 ** If the requested page is already in the cache, it is returned.
4822 ** Otherwise, a new page object is allocated and populated with data
4823 ** read from the database file. In some cases, the pcache module may
4824 ** choose not to allocate a new page object and may reuse an existing
4825 ** object with no outstanding references.
4826 **
4827 ** The extra data appended to a page is always initialized to zeros the
4828 ** first time a page is loaded into memory. If the page requested is
4829 ** already in the cache when this function is called, then the extra
4830 ** data is left as it was when the page object was last used.
4831 **
4832 ** If the database image is smaller than the requested page or if a
4833 ** non-zero value is passed as the noContent parameter and the
4834 ** requested page is not already stored in the cache, then no
4835 ** actual disk read occurs. In this case the memory image of the
4836 ** page is initialized to all zeros.
4837 **
4838 ** If noContent is true, it means that we do not care about the contents
4839 ** of the page. This occurs in two seperate scenarios:
4840 **
4841 **   a) When reading a free-list leaf page from the database, and
4842 **
4843 **   b) When a savepoint is being rolled back and we need to load
4844 **      a new page into the cache to be filled with the data read
4845 **      from the savepoint journal.
4846 **
4847 ** If noContent is true, then the data returned is zeroed instead of
4848 ** being read from the database. Additionally, the bits corresponding
4849 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
4850 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
4851 ** savepoints are set. This means if the page is made writable at any
4852 ** point in the future, using a call to sqlite3PagerWrite(), its contents
4853 ** will not be journaled. This saves IO.
4854 **
4855 ** The acquisition might fail for several reasons.  In all cases,
4856 ** an appropriate error code is returned and *ppPage is set to NULL.
4857 **
4858 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
4859 ** to find a page in the in-memory cache first.  If the page is not already
4860 ** in memory, this routine goes to disk to read it in whereas Lookup()
4861 ** just returns 0.  This routine acquires a read-lock the first time it
4862 ** has to go to disk, and could also playback an old journal if necessary.
4863 ** Since Lookup() never goes to disk, it never has to deal with locks
4864 ** or journal files.
4865 */
4866 int sqlite3PagerAcquire(
4867   Pager *pPager,      /* The pager open on the database file */
4868   Pgno pgno,          /* Page number to fetch */
4869   DbPage **ppPage,    /* Write a pointer to the page here */
4870   int noContent       /* Do not bother reading content from disk if true */
4871 ){
4872   int rc;
4873   PgHdr *pPg;
4874 
4875   assert( pPager->eState>=PAGER_READER );
4876   assert( assert_pager_state(pPager) );
4877 
4878   if( pgno==0 ){
4879     return SQLITE_CORRUPT_BKPT;
4880   }
4881 
4882   /* If the pager is in the error state, return an error immediately.
4883   ** Otherwise, request the page from the PCache layer. */
4884   if( pPager->errCode!=SQLITE_OK ){
4885     rc = pPager->errCode;
4886   }else{
4887     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
4888   }
4889 
4890   if( rc!=SQLITE_OK ){
4891     /* Either the call to sqlite3PcacheFetch() returned an error or the
4892     ** pager was already in the error-state when this function was called.
4893     ** Set pPg to 0 and jump to the exception handler.  */
4894     pPg = 0;
4895     goto pager_acquire_err;
4896   }
4897   assert( (*ppPage)->pgno==pgno );
4898   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
4899 
4900   if( (*ppPage)->pPager && !noContent ){
4901     /* In this case the pcache already contains an initialized copy of
4902     ** the page. Return without further ado.  */
4903     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
4904     PAGER_INCR(pPager->nHit);
4905     return SQLITE_OK;
4906 
4907   }else{
4908     /* The pager cache has created a new page. Its content needs to
4909     ** be initialized.  */
4910 
4911     PAGER_INCR(pPager->nMiss);
4912     pPg = *ppPage;
4913     pPg->pPager = pPager;
4914 
4915     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
4916     ** number greater than this, or the unused locking-page, is requested. */
4917     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
4918       rc = SQLITE_CORRUPT_BKPT;
4919       goto pager_acquire_err;
4920     }
4921 
4922     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
4923       if( pgno>pPager->mxPgno ){
4924         rc = SQLITE_FULL;
4925         goto pager_acquire_err;
4926       }
4927       if( noContent ){
4928         /* Failure to set the bits in the InJournal bit-vectors is benign.
4929         ** It merely means that we might do some extra work to journal a
4930         ** page that does not need to be journaled.  Nevertheless, be sure
4931         ** to test the case where a malloc error occurs while trying to set
4932         ** a bit in a bit vector.
4933         */
4934         sqlite3BeginBenignMalloc();
4935         if( pgno<=pPager->dbOrigSize ){
4936           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
4937           testcase( rc==SQLITE_NOMEM );
4938         }
4939         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
4940         testcase( rc==SQLITE_NOMEM );
4941         sqlite3EndBenignMalloc();
4942       }
4943       memset(pPg->pData, 0, pPager->pageSize);
4944       IOTRACE(("ZERO %p %d\n", pPager, pgno));
4945     }else{
4946       assert( pPg->pPager==pPager );
4947       rc = readDbPage(pPg);
4948       if( rc!=SQLITE_OK ){
4949         goto pager_acquire_err;
4950       }
4951     }
4952     pager_set_pagehash(pPg);
4953   }
4954 
4955   return SQLITE_OK;
4956 
4957 pager_acquire_err:
4958   assert( rc!=SQLITE_OK );
4959   if( pPg ){
4960     sqlite3PcacheDrop(pPg);
4961   }
4962   pagerUnlockIfUnused(pPager);
4963 
4964   *ppPage = 0;
4965   return rc;
4966 }
4967 
4968 /*
4969 ** Acquire a page if it is already in the in-memory cache.  Do
4970 ** not read the page from disk.  Return a pointer to the page,
4971 ** or 0 if the page is not in cache.
4972 **
4973 ** See also sqlite3PagerGet().  The difference between this routine
4974 ** and sqlite3PagerGet() is that _get() will go to the disk and read
4975 ** in the page if the page is not already in cache.  This routine
4976 ** returns NULL if the page is not in cache or if a disk I/O error
4977 ** has ever happened.
4978 */
4979 DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
4980   PgHdr *pPg = 0;
4981   assert( pPager!=0 );
4982   assert( pgno!=0 );
4983   assert( pPager->pPCache!=0 );
4984   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
4985   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
4986   return pPg;
4987 }
4988 
4989 /*
4990 ** Release a page reference.
4991 **
4992 ** If the number of references to the page drop to zero, then the
4993 ** page is added to the LRU list.  When all references to all pages
4994 ** are released, a rollback occurs and the lock on the database is
4995 ** removed.
4996 */
4997 void sqlite3PagerUnref(DbPage *pPg){
4998   if( pPg ){
4999     Pager *pPager = pPg->pPager;
5000     sqlite3PcacheRelease(pPg);
5001     pagerUnlockIfUnused(pPager);
5002   }
5003 }
5004 
5005 /*
5006 ** This function is called at the start of every write transaction.
5007 ** There must already be a RESERVED or EXCLUSIVE lock on the database
5008 ** file when this routine is called.
5009 **
5010 ** Open the journal file for pager pPager and write a journal header
5011 ** to the start of it. If there are active savepoints, open the sub-journal
5012 ** as well. This function is only used when the journal file is being
5013 ** opened to write a rollback log for a transaction. It is not used
5014 ** when opening a hot journal file to roll it back.
5015 **
5016 ** If the journal file is already open (as it may be in exclusive mode),
5017 ** then this function just writes a journal header to the start of the
5018 ** already open file.
5019 **
5020 ** Whether or not the journal file is opened by this function, the
5021 ** Pager.pInJournal bitvec structure is allocated.
5022 **
5023 ** Return SQLITE_OK if everything is successful. Otherwise, return
5024 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
5025 ** an IO error code if opening or writing the journal file fails.
5026 */
5027 static int pager_open_journal(Pager *pPager){
5028   int rc = SQLITE_OK;                        /* Return code */
5029   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
5030 
5031   assert( pPager->eState==PAGER_WRITER_LOCKED );
5032   assert( assert_pager_state(pPager) );
5033   assert( pPager->pInJournal==0 );
5034 
5035   /* If already in the error state, this function is a no-op.  But on
5036   ** the other hand, this routine is never called if we are already in
5037   ** an error state. */
5038   if( NEVER(pPager->errCode) ) return pPager->errCode;
5039 
5040   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
5041     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
5042     if( pPager->pInJournal==0 ){
5043       return SQLITE_NOMEM;
5044     }
5045 
5046     /* Open the journal file if it is not already open. */
5047     if( !isOpen(pPager->jfd) ){
5048       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
5049         sqlite3MemJournalOpen(pPager->jfd);
5050       }else{
5051         const int flags =                   /* VFS flags to open journal file */
5052           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
5053           (pPager->tempFile ?
5054             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
5055             (SQLITE_OPEN_MAIN_JOURNAL)
5056           );
5057   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
5058         rc = sqlite3JournalOpen(
5059             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
5060         );
5061   #else
5062         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
5063   #endif
5064       }
5065       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
5066     }
5067 
5068 
5069     /* Write the first journal header to the journal file and open
5070     ** the sub-journal if necessary.
5071     */
5072     if( rc==SQLITE_OK ){
5073       /* TODO: Check if all of these are really required. */
5074       pPager->nRec = 0;
5075       pPager->journalOff = 0;
5076       pPager->setMaster = 0;
5077       pPager->journalHdr = 0;
5078       rc = writeJournalHdr(pPager);
5079     }
5080   }
5081 
5082   if( rc!=SQLITE_OK ){
5083     sqlite3BitvecDestroy(pPager->pInJournal);
5084     pPager->pInJournal = 0;
5085   }else{
5086     assert( pPager->eState==PAGER_WRITER_LOCKED );
5087     pPager->eState = PAGER_WRITER_CACHEMOD;
5088   }
5089 
5090   return rc;
5091 }
5092 
5093 /*
5094 ** Begin a write-transaction on the specified pager object. If a
5095 ** write-transaction has already been opened, this function is a no-op.
5096 **
5097 ** If the exFlag argument is false, then acquire at least a RESERVED
5098 ** lock on the database file. If exFlag is true, then acquire at least
5099 ** an EXCLUSIVE lock. If such a lock is already held, no locking
5100 ** functions need be called.
5101 **
5102 ** If the subjInMemory argument is non-zero, then any sub-journal opened
5103 ** within this transaction will be opened as an in-memory file. This
5104 ** has no effect if the sub-journal is already opened (as it may be when
5105 ** running in exclusive mode) or if the transaction does not require a
5106 ** sub-journal. If the subjInMemory argument is zero, then any required
5107 ** sub-journal is implemented in-memory if pPager is an in-memory database,
5108 ** or using a temporary file otherwise.
5109 */
5110 int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
5111   int rc = SQLITE_OK;
5112 
5113   if( pPager->errCode ) return pPager->errCode;
5114   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
5115   pPager->subjInMemory = (u8)subjInMemory;
5116 
5117   if( ALWAYS(pPager->eState==PAGER_READER) ){
5118     assert( pPager->pInJournal==0 );
5119 
5120     if( pagerUseWal(pPager) ){
5121       /* If the pager is configured to use locking_mode=exclusive, and an
5122       ** exclusive lock on the database is not already held, obtain it now.
5123       */
5124       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
5125         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
5126         if( rc!=SQLITE_OK ){
5127           return rc;
5128         }
5129         sqlite3WalExclusiveMode(pPager->pWal, 1);
5130       }
5131 
5132       /* Grab the write lock on the log file. If successful, upgrade to
5133       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
5134       ** The busy-handler is not invoked if another connection already
5135       ** holds the write-lock. If possible, the upper layer will call it.
5136       */
5137       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
5138     }else{
5139       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
5140       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
5141       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
5142       ** lock, but not when obtaining the RESERVED lock.
5143       */
5144       rc = pagerLockDb(pPager, RESERVED_LOCK);
5145       if( rc==SQLITE_OK && exFlag ){
5146         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
5147       }
5148     }
5149 
5150     if( rc==SQLITE_OK ){
5151       /* Change to WRITER_LOCKED state.
5152       **
5153       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
5154       ** when it has an open transaction, but never to DBMOD or FINISHED.
5155       ** This is because in those states the code to roll back savepoint
5156       ** transactions may copy data from the sub-journal into the database
5157       ** file as well as into the page cache. Which would be incorrect in
5158       ** WAL mode.
5159       */
5160       pPager->eState = PAGER_WRITER_LOCKED;
5161       pPager->dbHintSize = pPager->dbSize;
5162       pPager->dbFileSize = pPager->dbSize;
5163       pPager->dbOrigSize = pPager->dbSize;
5164       pPager->journalOff = 0;
5165     }
5166 
5167     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
5168     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
5169     assert( assert_pager_state(pPager) );
5170   }
5171 
5172   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
5173   return rc;
5174 }
5175 
5176 /*
5177 ** Mark a single data page as writeable. The page is written into the
5178 ** main journal or sub-journal as required. If the page is written into
5179 ** one of the journals, the corresponding bit is set in the
5180 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
5181 ** of any open savepoints as appropriate.
5182 */
5183 static int pager_write(PgHdr *pPg){
5184   void *pData = pPg->pData;
5185   Pager *pPager = pPg->pPager;
5186   int rc = SQLITE_OK;
5187 
5188   /* This routine is not called unless a write-transaction has already
5189   ** been started. The journal file may or may not be open at this point.
5190   ** It is never called in the ERROR state.
5191   */
5192   assert( pPager->eState==PAGER_WRITER_LOCKED
5193        || pPager->eState==PAGER_WRITER_CACHEMOD
5194        || pPager->eState==PAGER_WRITER_DBMOD
5195   );
5196   assert( assert_pager_state(pPager) );
5197 
5198   /* If an error has been previously detected, report the same error
5199   ** again. This should not happen, but the check provides robustness. */
5200   if( NEVER(pPager->errCode) )  return pPager->errCode;
5201 
5202   /* Higher-level routines never call this function if database is not
5203   ** writable.  But check anyway, just for robustness. */
5204   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
5205 
5206   CHECK_PAGE(pPg);
5207 
5208   /* Mark the page as dirty.  If the page has already been written
5209   ** to the journal then we can return right away.
5210   */
5211   sqlite3PcacheMakeDirty(pPg);
5212   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
5213     assert( !pagerUseWal(pPager) );
5214     assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
5215   }else{
5216 
5217     /* If we get this far, it means that the page needs to be
5218     ** written to the transaction journal or the checkpoint journal
5219     ** or both.
5220     **
5221     ** Higher level routines have already obtained the necessary locks
5222     ** to begin the write-transaction, but the rollback journal might not
5223     ** yet be open. Open it now if this is the case.
5224     */
5225     if( pPager->eState==PAGER_WRITER_LOCKED ){
5226       rc = pager_open_journal(pPager);
5227       if( rc!=SQLITE_OK ) return rc;
5228     }
5229     assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
5230     assert( assert_pager_state(pPager) );
5231 
5232     /* The transaction journal now exists and we have a RESERVED or an
5233     ** EXCLUSIVE lock on the main database file.  Write the current page to
5234     ** the transaction journal if it is not there already.
5235     */
5236     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
5237       assert( pagerUseWal(pPager)==0 );
5238       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
5239         u32 cksum;
5240         char *pData2;
5241         i64 iOff = pPager->journalOff;
5242 
5243         /* We should never write to the journal file the page that
5244         ** contains the database locks.  The following assert verifies
5245         ** that we do not. */
5246         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
5247 
5248         assert( pPager->journalHdr<=pPager->journalOff );
5249         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
5250         cksum = pager_cksum(pPager, (u8*)pData2);
5251 
5252         /* Even if an IO or diskfull error occurs while journalling the
5253         ** page in the block above, set the need-sync flag for the page.
5254         ** Otherwise, when the transaction is rolled back, the logic in
5255         ** playback_one_page() will think that the page needs to be restored
5256         ** in the database file. And if an IO error occurs while doing so,
5257         ** then corruption may follow.
5258         */
5259         pPg->flags |= PGHDR_NEED_SYNC;
5260 
5261         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
5262         if( rc!=SQLITE_OK ) return rc;
5263         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
5264         if( rc!=SQLITE_OK ) return rc;
5265         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
5266         if( rc!=SQLITE_OK ) return rc;
5267 
5268         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
5269                  pPager->journalOff, pPager->pageSize));
5270         PAGER_INCR(sqlite3_pager_writej_count);
5271         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
5272              PAGERID(pPager), pPg->pgno,
5273              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
5274 
5275         pPager->journalOff += 8 + pPager->pageSize;
5276         pPager->nRec++;
5277         assert( pPager->pInJournal!=0 );
5278         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
5279         testcase( rc==SQLITE_NOMEM );
5280         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
5281         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
5282         if( rc!=SQLITE_OK ){
5283           assert( rc==SQLITE_NOMEM );
5284           return rc;
5285         }
5286       }else{
5287         if( pPager->eState!=PAGER_WRITER_DBMOD ){
5288           pPg->flags |= PGHDR_NEED_SYNC;
5289         }
5290         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
5291                 PAGERID(pPager), pPg->pgno,
5292                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
5293       }
5294     }
5295 
5296     /* If the statement journal is open and the page is not in it,
5297     ** then write the current page to the statement journal.  Note that
5298     ** the statement journal format differs from the standard journal format
5299     ** in that it omits the checksums and the header.
5300     */
5301     if( subjRequiresPage(pPg) ){
5302       rc = subjournalPage(pPg);
5303     }
5304   }
5305 
5306   /* Update the database size and return.
5307   */
5308   if( pPager->dbSize<pPg->pgno ){
5309     pPager->dbSize = pPg->pgno;
5310   }
5311   return rc;
5312 }
5313 
5314 /*
5315 ** Mark a data page as writeable. This routine must be called before
5316 ** making changes to a page. The caller must check the return value
5317 ** of this function and be careful not to change any page data unless
5318 ** this routine returns SQLITE_OK.
5319 **
5320 ** The difference between this function and pager_write() is that this
5321 ** function also deals with the special case where 2 or more pages
5322 ** fit on a single disk sector. In this case all co-resident pages
5323 ** must have been written to the journal file before returning.
5324 **
5325 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
5326 ** as appropriate. Otherwise, SQLITE_OK.
5327 */
5328 int sqlite3PagerWrite(DbPage *pDbPage){
5329   int rc = SQLITE_OK;
5330 
5331   PgHdr *pPg = pDbPage;
5332   Pager *pPager = pPg->pPager;
5333   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
5334 
5335   assert( pPager->eState>=PAGER_WRITER_LOCKED );
5336   assert( pPager->eState!=PAGER_ERROR );
5337   assert( assert_pager_state(pPager) );
5338 
5339   if( nPagePerSector>1 ){
5340     Pgno nPageCount;          /* Total number of pages in database file */
5341     Pgno pg1;                 /* First page of the sector pPg is located on. */
5342     int nPage = 0;            /* Number of pages starting at pg1 to journal */
5343     int ii;                   /* Loop counter */
5344     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
5345 
5346     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
5347     ** a journal header to be written between the pages journaled by
5348     ** this function.
5349     */
5350     assert( !MEMDB );
5351     assert( pPager->doNotSyncSpill==0 );
5352     pPager->doNotSyncSpill++;
5353 
5354     /* This trick assumes that both the page-size and sector-size are
5355     ** an integer power of 2. It sets variable pg1 to the identifier
5356     ** of the first page of the sector pPg is located on.
5357     */
5358     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
5359 
5360     nPageCount = pPager->dbSize;
5361     if( pPg->pgno>nPageCount ){
5362       nPage = (pPg->pgno - pg1)+1;
5363     }else if( (pg1+nPagePerSector-1)>nPageCount ){
5364       nPage = nPageCount+1-pg1;
5365     }else{
5366       nPage = nPagePerSector;
5367     }
5368     assert(nPage>0);
5369     assert(pg1<=pPg->pgno);
5370     assert((pg1+nPage)>pPg->pgno);
5371 
5372     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
5373       Pgno pg = pg1+ii;
5374       PgHdr *pPage;
5375       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
5376         if( pg!=PAGER_MJ_PGNO(pPager) ){
5377           rc = sqlite3PagerGet(pPager, pg, &pPage);
5378           if( rc==SQLITE_OK ){
5379             rc = pager_write(pPage);
5380             if( pPage->flags&PGHDR_NEED_SYNC ){
5381               needSync = 1;
5382             }
5383             sqlite3PagerUnref(pPage);
5384           }
5385         }
5386       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
5387         if( pPage->flags&PGHDR_NEED_SYNC ){
5388           needSync = 1;
5389         }
5390         sqlite3PagerUnref(pPage);
5391       }
5392     }
5393 
5394     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
5395     ** starting at pg1, then it needs to be set for all of them. Because
5396     ** writing to any of these nPage pages may damage the others, the
5397     ** journal file must contain sync()ed copies of all of them
5398     ** before any of them can be written out to the database file.
5399     */
5400     if( rc==SQLITE_OK && needSync ){
5401       assert( !MEMDB );
5402       for(ii=0; ii<nPage; ii++){
5403         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
5404         if( pPage ){
5405           pPage->flags |= PGHDR_NEED_SYNC;
5406           sqlite3PagerUnref(pPage);
5407         }
5408       }
5409     }
5410 
5411     assert( pPager->doNotSyncSpill==1 );
5412     pPager->doNotSyncSpill--;
5413   }else{
5414     rc = pager_write(pDbPage);
5415   }
5416   return rc;
5417 }
5418 
5419 /*
5420 ** Return TRUE if the page given in the argument was previously passed
5421 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
5422 ** to change the content of the page.
5423 */
5424 #ifndef NDEBUG
5425 int sqlite3PagerIswriteable(DbPage *pPg){
5426   return pPg->flags&PGHDR_DIRTY;
5427 }
5428 #endif
5429 
5430 /*
5431 ** A call to this routine tells the pager that it is not necessary to
5432 ** write the information on page pPg back to the disk, even though
5433 ** that page might be marked as dirty.  This happens, for example, when
5434 ** the page has been added as a leaf of the freelist and so its
5435 ** content no longer matters.
5436 **
5437 ** The overlying software layer calls this routine when all of the data
5438 ** on the given page is unused. The pager marks the page as clean so
5439 ** that it does not get written to disk.
5440 **
5441 ** Tests show that this optimization can quadruple the speed of large
5442 ** DELETE operations.
5443 */
5444 void sqlite3PagerDontWrite(PgHdr *pPg){
5445   Pager *pPager = pPg->pPager;
5446   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
5447     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
5448     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
5449     pPg->flags |= PGHDR_DONT_WRITE;
5450     pager_set_pagehash(pPg);
5451   }
5452 }
5453 
5454 /*
5455 ** This routine is called to increment the value of the database file
5456 ** change-counter, stored as a 4-byte big-endian integer starting at
5457 ** byte offset 24 of the pager file.
5458 **
5459 ** If the isDirectMode flag is zero, then this is done by calling
5460 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
5461 ** page data. In this case the file will be updated when the current
5462 ** transaction is committed.
5463 **
5464 ** The isDirectMode flag may only be non-zero if the library was compiled
5465 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
5466 ** if isDirect is non-zero, then the database file is updated directly
5467 ** by writing an updated version of page 1 using a call to the
5468 ** sqlite3OsWrite() function.
5469 */
5470 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
5471   int rc = SQLITE_OK;
5472 
5473   assert( pPager->eState==PAGER_WRITER_CACHEMOD
5474        || pPager->eState==PAGER_WRITER_DBMOD
5475   );
5476   assert( assert_pager_state(pPager) );
5477 
5478   /* Declare and initialize constant integer 'isDirect'. If the
5479   ** atomic-write optimization is enabled in this build, then isDirect
5480   ** is initialized to the value passed as the isDirectMode parameter
5481   ** to this function. Otherwise, it is always set to zero.
5482   **
5483   ** The idea is that if the atomic-write optimization is not
5484   ** enabled at compile time, the compiler can omit the tests of
5485   ** 'isDirect' below, as well as the block enclosed in the
5486   ** "if( isDirect )" condition.
5487   */
5488 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
5489 # define DIRECT_MODE 0
5490   assert( isDirectMode==0 );
5491   UNUSED_PARAMETER(isDirectMode);
5492 #else
5493 # define DIRECT_MODE isDirectMode
5494 #endif
5495 
5496   if( !pPager->changeCountDone && pPager->dbSize>0 ){
5497     PgHdr *pPgHdr;                /* Reference to page 1 */
5498     u32 change_counter;           /* Initial value of change-counter field */
5499 
5500     assert( !pPager->tempFile && isOpen(pPager->fd) );
5501 
5502     /* Open page 1 of the file for writing. */
5503     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
5504     assert( pPgHdr==0 || rc==SQLITE_OK );
5505 
5506     /* If page one was fetched successfully, and this function is not
5507     ** operating in direct-mode, make page 1 writable.  When not in
5508     ** direct mode, page 1 is always held in cache and hence the PagerGet()
5509     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
5510     */
5511     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
5512       rc = sqlite3PagerWrite(pPgHdr);
5513     }
5514 
5515     if( rc==SQLITE_OK ){
5516       /* Increment the value just read and write it back to byte 24. */
5517       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
5518       change_counter++;
5519       put32bits(((char*)pPgHdr->pData)+24, change_counter);
5520 
5521       /* Also store the SQLite version number in bytes 96..99 and in
5522       ** bytes 92..95 store the change counter for which the version number
5523       ** is valid. */
5524       put32bits(((char*)pPgHdr->pData)+92, change_counter);
5525       put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
5526 
5527       /* If running in direct mode, write the contents of page 1 to the file. */
5528       if( DIRECT_MODE ){
5529         const void *zBuf;
5530         assert( pPager->dbFileSize>0 );
5531         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
5532         if( rc==SQLITE_OK ){
5533           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
5534         }
5535         if( rc==SQLITE_OK ){
5536           pPager->changeCountDone = 1;
5537         }
5538       }else{
5539         pPager->changeCountDone = 1;
5540       }
5541     }
5542 
5543     /* Release the page reference. */
5544     sqlite3PagerUnref(pPgHdr);
5545   }
5546   return rc;
5547 }
5548 
5549 /*
5550 ** Sync the pager file to disk. This is a no-op for in-memory files
5551 ** or pages with the Pager.noSync flag set.
5552 **
5553 ** If successful, or called on a pager for which it is a no-op, this
5554 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
5555 */
5556 int sqlite3PagerSync(Pager *pPager){
5557   int rc;                              /* Return code */
5558   assert( !MEMDB );
5559   if( pPager->noSync ){
5560     rc = SQLITE_OK;
5561   }else{
5562     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
5563   }
5564   return rc;
5565 }
5566 
5567 /*
5568 ** This function may only be called while a write-transaction is active in
5569 ** rollback. If the connection is in WAL mode, this call is a no-op.
5570 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
5571 ** the database file, an attempt is made to obtain one.
5572 **
5573 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
5574 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
5575 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
5576 ** returned.
5577 */
5578 int sqlite3PagerExclusiveLock(Pager *pPager){
5579   int rc = SQLITE_OK;
5580   assert( pPager->eState==PAGER_WRITER_CACHEMOD
5581        || pPager->eState==PAGER_WRITER_DBMOD
5582        || pPager->eState==PAGER_WRITER_LOCKED
5583   );
5584   assert( assert_pager_state(pPager) );
5585   if( 0==pagerUseWal(pPager) ){
5586     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
5587   }
5588   return rc;
5589 }
5590 
5591 /*
5592 ** Sync the database file for the pager pPager. zMaster points to the name
5593 ** of a master journal file that should be written into the individual
5594 ** journal file. zMaster may be NULL, which is interpreted as no master
5595 ** journal (a single database transaction).
5596 **
5597 ** This routine ensures that:
5598 **
5599 **   * The database file change-counter is updated,
5600 **   * the journal is synced (unless the atomic-write optimization is used),
5601 **   * all dirty pages are written to the database file,
5602 **   * the database file is truncated (if required), and
5603 **   * the database file synced.
5604 **
5605 ** The only thing that remains to commit the transaction is to finalize
5606 ** (delete, truncate or zero the first part of) the journal file (or
5607 ** delete the master journal file if specified).
5608 **
5609 ** Note that if zMaster==NULL, this does not overwrite a previous value
5610 ** passed to an sqlite3PagerCommitPhaseOne() call.
5611 **
5612 ** If the final parameter - noSync - is true, then the database file itself
5613 ** is not synced. The caller must call sqlite3PagerSync() directly to
5614 ** sync the database file before calling CommitPhaseTwo() to delete the
5615 ** journal file in this case.
5616 */
5617 int sqlite3PagerCommitPhaseOne(
5618   Pager *pPager,                  /* Pager object */
5619   const char *zMaster,            /* If not NULL, the master journal name */
5620   int noSync                      /* True to omit the xSync on the db file */
5621 ){
5622   int rc = SQLITE_OK;             /* Return code */
5623 
5624   assert( pPager->eState==PAGER_WRITER_LOCKED
5625        || pPager->eState==PAGER_WRITER_CACHEMOD
5626        || pPager->eState==PAGER_WRITER_DBMOD
5627        || pPager->eState==PAGER_ERROR
5628   );
5629   assert( assert_pager_state(pPager) );
5630 
5631   /* If a prior error occurred, report that error again. */
5632   if( NEVER(pPager->errCode) ) return pPager->errCode;
5633 
5634   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
5635       pPager->zFilename, zMaster, pPager->dbSize));
5636 
5637   /* If no database changes have been made, return early. */
5638   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
5639 
5640   if( MEMDB ){
5641     /* If this is an in-memory db, or no pages have been written to, or this
5642     ** function has already been called, it is mostly a no-op.  However, any
5643     ** backup in progress needs to be restarted.
5644     */
5645     sqlite3BackupRestart(pPager->pBackup);
5646   }else{
5647     if( pagerUseWal(pPager) ){
5648       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
5649       if( pList ){
5650         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
5651             (pPager->fullSync ? pPager->sync_flags : 0)
5652         );
5653       }
5654       if( rc==SQLITE_OK ){
5655         sqlite3PcacheCleanAll(pPager->pPCache);
5656       }
5657     }else{
5658       /* The following block updates the change-counter. Exactly how it
5659       ** does this depends on whether or not the atomic-update optimization
5660       ** was enabled at compile time, and if this transaction meets the
5661       ** runtime criteria to use the operation:
5662       **
5663       **    * The file-system supports the atomic-write property for
5664       **      blocks of size page-size, and
5665       **    * This commit is not part of a multi-file transaction, and
5666       **    * Exactly one page has been modified and store in the journal file.
5667       **
5668       ** If the optimization was not enabled at compile time, then the
5669       ** pager_incr_changecounter() function is called to update the change
5670       ** counter in 'indirect-mode'. If the optimization is compiled in but
5671       ** is not applicable to this transaction, call sqlite3JournalCreate()
5672       ** to make sure the journal file has actually been created, then call
5673       ** pager_incr_changecounter() to update the change-counter in indirect
5674       ** mode.
5675       **
5676       ** Otherwise, if the optimization is both enabled and applicable,
5677       ** then call pager_incr_changecounter() to update the change-counter
5678       ** in 'direct' mode. In this case the journal file will never be
5679       ** created for this transaction.
5680       */
5681   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
5682       PgHdr *pPg;
5683       assert( isOpen(pPager->jfd)
5684            || pPager->journalMode==PAGER_JOURNALMODE_OFF
5685            || pPager->journalMode==PAGER_JOURNALMODE_WAL
5686       );
5687       if( !zMaster && isOpen(pPager->jfd)
5688        && pPager->journalOff==jrnlBufferSize(pPager)
5689        && pPager->dbSize>=pPager->dbOrigSize
5690        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
5691       ){
5692         /* Update the db file change counter via the direct-write method. The
5693         ** following call will modify the in-memory representation of page 1
5694         ** to include the updated change counter and then write page 1
5695         ** directly to the database file. Because of the atomic-write
5696         ** property of the host file-system, this is safe.
5697         */
5698         rc = pager_incr_changecounter(pPager, 1);
5699       }else{
5700         rc = sqlite3JournalCreate(pPager->jfd);
5701         if( rc==SQLITE_OK ){
5702           rc = pager_incr_changecounter(pPager, 0);
5703         }
5704       }
5705   #else
5706       rc = pager_incr_changecounter(pPager, 0);
5707   #endif
5708       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
5709 
5710       /* If this transaction has made the database smaller, then all pages
5711       ** being discarded by the truncation must be written to the journal
5712       ** file. This can only happen in auto-vacuum mode.
5713       **
5714       ** Before reading the pages with page numbers larger than the
5715       ** current value of Pager.dbSize, set dbSize back to the value
5716       ** that it took at the start of the transaction. Otherwise, the
5717       ** calls to sqlite3PagerGet() return zeroed pages instead of
5718       ** reading data from the database file.
5719       */
5720   #ifndef SQLITE_OMIT_AUTOVACUUM
5721       if( pPager->dbSize<pPager->dbOrigSize
5722        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
5723       ){
5724         Pgno i;                                   /* Iterator variable */
5725         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
5726         const Pgno dbSize = pPager->dbSize;       /* Database image size */
5727         pPager->dbSize = pPager->dbOrigSize;
5728         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
5729           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
5730             PgHdr *pPage;             /* Page to journal */
5731             rc = sqlite3PagerGet(pPager, i, &pPage);
5732             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
5733             rc = sqlite3PagerWrite(pPage);
5734             sqlite3PagerUnref(pPage);
5735             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
5736           }
5737         }
5738         pPager->dbSize = dbSize;
5739       }
5740   #endif
5741 
5742       /* Write the master journal name into the journal file. If a master
5743       ** journal file name has already been written to the journal file,
5744       ** or if zMaster is NULL (no master journal), then this call is a no-op.
5745       */
5746       rc = writeMasterJournal(pPager, zMaster);
5747       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
5748 
5749       /* Sync the journal file and write all dirty pages to the database.
5750       ** If the atomic-update optimization is being used, this sync will not
5751       ** create the journal file or perform any real IO.
5752       **
5753       ** Because the change-counter page was just modified, unless the
5754       ** atomic-update optimization is used it is almost certain that the
5755       ** journal requires a sync here. However, in locking_mode=exclusive
5756       ** on a system under memory pressure it is just possible that this is
5757       ** not the case. In this case it is likely enough that the redundant
5758       ** xSync() call will be changed to a no-op by the OS anyhow.
5759       */
5760       rc = syncJournal(pPager, 0);
5761       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
5762 
5763       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
5764       if( rc!=SQLITE_OK ){
5765         assert( rc!=SQLITE_IOERR_BLOCKED );
5766         goto commit_phase_one_exit;
5767       }
5768       sqlite3PcacheCleanAll(pPager->pPCache);
5769 
5770       /* If the file on disk is not the same size as the database image,
5771       ** then use pager_truncate to grow or shrink the file here.
5772       */
5773       if( pPager->dbSize!=pPager->dbFileSize ){
5774         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
5775         assert( pPager->eState==PAGER_WRITER_DBMOD );
5776         rc = pager_truncate(pPager, nNew);
5777         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
5778       }
5779 
5780       /* Finally, sync the database file. */
5781       if( !pPager->noSync && !noSync ){
5782         rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
5783       }
5784       IOTRACE(("DBSYNC %p\n", pPager))
5785     }
5786   }
5787 
5788 commit_phase_one_exit:
5789   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
5790     pPager->eState = PAGER_WRITER_FINISHED;
5791   }
5792   return rc;
5793 }
5794 
5795 
5796 /*
5797 ** When this function is called, the database file has been completely
5798 ** updated to reflect the changes made by the current transaction and
5799 ** synced to disk. The journal file still exists in the file-system
5800 ** though, and if a failure occurs at this point it will eventually
5801 ** be used as a hot-journal and the current transaction rolled back.
5802 **
5803 ** This function finalizes the journal file, either by deleting,
5804 ** truncating or partially zeroing it, so that it cannot be used
5805 ** for hot-journal rollback. Once this is done the transaction is
5806 ** irrevocably committed.
5807 **
5808 ** If an error occurs, an IO error code is returned and the pager
5809 ** moves into the error state. Otherwise, SQLITE_OK is returned.
5810 */
5811 int sqlite3PagerCommitPhaseTwo(Pager *pPager){
5812   int rc = SQLITE_OK;                  /* Return code */
5813 
5814   /* This routine should not be called if a prior error has occurred.
5815   ** But if (due to a coding error elsewhere in the system) it does get
5816   ** called, just return the same error code without doing anything. */
5817   if( NEVER(pPager->errCode) ) return pPager->errCode;
5818 
5819   assert( pPager->eState==PAGER_WRITER_LOCKED
5820        || pPager->eState==PAGER_WRITER_FINISHED
5821        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
5822   );
5823   assert( assert_pager_state(pPager) );
5824 
5825   /* An optimization. If the database was not actually modified during
5826   ** this transaction, the pager is running in exclusive-mode and is
5827   ** using persistent journals, then this function is a no-op.
5828   **
5829   ** The start of the journal file currently contains a single journal
5830   ** header with the nRec field set to 0. If such a journal is used as
5831   ** a hot-journal during hot-journal rollback, 0 changes will be made
5832   ** to the database file. So there is no need to zero the journal
5833   ** header. Since the pager is in exclusive mode, there is no need
5834   ** to drop any locks either.
5835   */
5836   if( pPager->eState==PAGER_WRITER_LOCKED
5837    && pPager->exclusiveMode
5838    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
5839   ){
5840     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
5841     pPager->eState = PAGER_READER;
5842     return SQLITE_OK;
5843   }
5844 
5845   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
5846   rc = pager_end_transaction(pPager, pPager->setMaster);
5847   return pager_error(pPager, rc);
5848 }
5849 
5850 /*
5851 ** If a write transaction is open, then all changes made within the
5852 ** transaction are reverted and the current write-transaction is closed.
5853 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
5854 ** state if an error occurs.
5855 **
5856 ** If the pager is already in PAGER_ERROR state when this function is called,
5857 ** it returns Pager.errCode immediately. No work is performed in this case.
5858 **
5859 ** Otherwise, in rollback mode, this function performs two functions:
5860 **
5861 **   1) It rolls back the journal file, restoring all database file and
5862 **      in-memory cache pages to the state they were in when the transaction
5863 **      was opened, and
5864 **
5865 **   2) It finalizes the journal file, so that it is not used for hot
5866 **      rollback at any point in the future.
5867 **
5868 ** Finalization of the journal file (task 2) is only performed if the
5869 ** rollback is successful.
5870 **
5871 ** In WAL mode, all cache-entries containing data modified within the
5872 ** current transaction are either expelled from the cache or reverted to
5873 ** their pre-transaction state by re-reading data from the database or
5874 ** WAL files. The WAL transaction is then closed.
5875 */
5876 int sqlite3PagerRollback(Pager *pPager){
5877   int rc = SQLITE_OK;                  /* Return code */
5878   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
5879 
5880   /* PagerRollback() is a no-op if called in READER or OPEN state. If
5881   ** the pager is already in the ERROR state, the rollback is not
5882   ** attempted here. Instead, the error code is returned to the caller.
5883   */
5884   assert( assert_pager_state(pPager) );
5885   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
5886   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
5887 
5888   if( pagerUseWal(pPager) ){
5889     int rc2;
5890     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
5891     rc2 = pager_end_transaction(pPager, pPager->setMaster);
5892     if( rc==SQLITE_OK ) rc = rc2;
5893   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
5894     rc = pager_end_transaction(pPager, 0);
5895   }else{
5896     rc = pager_playback(pPager, 0);
5897   }
5898 
5899   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
5900   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
5901 
5902   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
5903   ** cache. So call pager_error() on the way out to make any error persistent.
5904   */
5905   return pager_error(pPager, rc);
5906 }
5907 
5908 /*
5909 ** Return TRUE if the database file is opened read-only.  Return FALSE
5910 ** if the database is (in theory) writable.
5911 */
5912 u8 sqlite3PagerIsreadonly(Pager *pPager){
5913   return pPager->readOnly;
5914 }
5915 
5916 /*
5917 ** Return the number of references to the pager.
5918 */
5919 int sqlite3PagerRefcount(Pager *pPager){
5920   return sqlite3PcacheRefCount(pPager->pPCache);
5921 }
5922 
5923 /*
5924 ** Return the approximate number of bytes of memory currently
5925 ** used by the pager and its associated cache.
5926 */
5927 int sqlite3PagerMemUsed(Pager *pPager){
5928   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
5929                                      + 5*sizeof(void*);
5930   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
5931            + sqlite3MallocSize(pPager)
5932            + pPager->pageSize;
5933 }
5934 
5935 /*
5936 ** Return the number of references to the specified page.
5937 */
5938 int sqlite3PagerPageRefcount(DbPage *pPage){
5939   return sqlite3PcachePageRefcount(pPage);
5940 }
5941 
5942 #ifdef SQLITE_TEST
5943 /*
5944 ** This routine is used for testing and analysis only.
5945 */
5946 int *sqlite3PagerStats(Pager *pPager){
5947   static int a[11];
5948   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
5949   a[1] = sqlite3PcachePagecount(pPager->pPCache);
5950   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
5951   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
5952   a[4] = pPager->eState;
5953   a[5] = pPager->errCode;
5954   a[6] = pPager->nHit;
5955   a[7] = pPager->nMiss;
5956   a[8] = 0;  /* Used to be pPager->nOvfl */
5957   a[9] = pPager->nRead;
5958   a[10] = pPager->nWrite;
5959   return a;
5960 }
5961 #endif
5962 
5963 /*
5964 ** Return true if this is an in-memory pager.
5965 */
5966 int sqlite3PagerIsMemdb(Pager *pPager){
5967   return MEMDB;
5968 }
5969 
5970 /*
5971 ** Check that there are at least nSavepoint savepoints open. If there are
5972 ** currently less than nSavepoints open, then open one or more savepoints
5973 ** to make up the difference. If the number of savepoints is already
5974 ** equal to nSavepoint, then this function is a no-op.
5975 **
5976 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
5977 ** occurs while opening the sub-journal file, then an IO error code is
5978 ** returned. Otherwise, SQLITE_OK.
5979 */
5980 int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
5981   int rc = SQLITE_OK;                       /* Return code */
5982   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
5983 
5984   assert( pPager->eState>=PAGER_WRITER_LOCKED );
5985   assert( assert_pager_state(pPager) );
5986 
5987   if( nSavepoint>nCurrent && pPager->useJournal ){
5988     int ii;                                 /* Iterator variable */
5989     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
5990 
5991     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
5992     ** if the allocation fails. Otherwise, zero the new portion in case a
5993     ** malloc failure occurs while populating it in the for(...) loop below.
5994     */
5995     aNew = (PagerSavepoint *)sqlite3Realloc(
5996         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
5997     );
5998     if( !aNew ){
5999       return SQLITE_NOMEM;
6000     }
6001     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
6002     pPager->aSavepoint = aNew;
6003 
6004     /* Populate the PagerSavepoint structures just allocated. */
6005     for(ii=nCurrent; ii<nSavepoint; ii++){
6006       aNew[ii].nOrig = pPager->dbSize;
6007       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
6008         aNew[ii].iOffset = pPager->journalOff;
6009       }else{
6010         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
6011       }
6012       aNew[ii].iSubRec = pPager->nSubRec;
6013       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
6014       if( !aNew[ii].pInSavepoint ){
6015         return SQLITE_NOMEM;
6016       }
6017       if( pagerUseWal(pPager) ){
6018         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
6019       }
6020       pPager->nSavepoint = ii+1;
6021     }
6022     assert( pPager->nSavepoint==nSavepoint );
6023     assertTruncateConstraint(pPager);
6024   }
6025 
6026   return rc;
6027 }
6028 
6029 /*
6030 ** This function is called to rollback or release (commit) a savepoint.
6031 ** The savepoint to release or rollback need not be the most recently
6032 ** created savepoint.
6033 **
6034 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
6035 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
6036 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
6037 ** that have occurred since the specified savepoint was created.
6038 **
6039 ** The savepoint to rollback or release is identified by parameter
6040 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
6041 ** (the first created). A value of (Pager.nSavepoint-1) means operate
6042 ** on the most recently created savepoint. If iSavepoint is greater than
6043 ** (Pager.nSavepoint-1), then this function is a no-op.
6044 **
6045 ** If a negative value is passed to this function, then the current
6046 ** transaction is rolled back. This is different to calling
6047 ** sqlite3PagerRollback() because this function does not terminate
6048 ** the transaction or unlock the database, it just restores the
6049 ** contents of the database to its original state.
6050 **
6051 ** In any case, all savepoints with an index greater than iSavepoint
6052 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
6053 ** then savepoint iSavepoint is also destroyed.
6054 **
6055 ** This function may return SQLITE_NOMEM if a memory allocation fails,
6056 ** or an IO error code if an IO error occurs while rolling back a
6057 ** savepoint. If no errors occur, SQLITE_OK is returned.
6058 */
6059 int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
6060   int rc = pPager->errCode;       /* Return code */
6061 
6062   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
6063   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
6064 
6065   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
6066     int ii;            /* Iterator variable */
6067     int nNew;          /* Number of remaining savepoints after this op. */
6068 
6069     /* Figure out how many savepoints will still be active after this
6070     ** operation. Store this value in nNew. Then free resources associated
6071     ** with any savepoints that are destroyed by this operation.
6072     */
6073     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
6074     for(ii=nNew; ii<pPager->nSavepoint; ii++){
6075       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
6076     }
6077     pPager->nSavepoint = nNew;
6078 
6079     /* If this is a release of the outermost savepoint, truncate
6080     ** the sub-journal to zero bytes in size. */
6081     if( op==SAVEPOINT_RELEASE ){
6082       if( nNew==0 && isOpen(pPager->sjfd) ){
6083         /* Only truncate if it is an in-memory sub-journal. */
6084         if( sqlite3IsMemJournal(pPager->sjfd) ){
6085           rc = sqlite3OsTruncate(pPager->sjfd, 0);
6086           assert( rc==SQLITE_OK );
6087         }
6088         pPager->nSubRec = 0;
6089       }
6090     }
6091     /* Else this is a rollback operation, playback the specified savepoint.
6092     ** If this is a temp-file, it is possible that the journal file has
6093     ** not yet been opened. In this case there have been no changes to
6094     ** the database file, so the playback operation can be skipped.
6095     */
6096     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
6097       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
6098       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
6099       assert(rc!=SQLITE_DONE);
6100     }
6101   }
6102 
6103   return rc;
6104 }
6105 
6106 /*
6107 ** Return the full pathname of the database file.
6108 */
6109 const char *sqlite3PagerFilename(Pager *pPager){
6110   return pPager->zFilename;
6111 }
6112 
6113 /*
6114 ** Return the VFS structure for the pager.
6115 */
6116 const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
6117   return pPager->pVfs;
6118 }
6119 
6120 /*
6121 ** Return the file handle for the database file associated
6122 ** with the pager.  This might return NULL if the file has
6123 ** not yet been opened.
6124 */
6125 sqlite3_file *sqlite3PagerFile(Pager *pPager){
6126   return pPager->fd;
6127 }
6128 
6129 /*
6130 ** Return the full pathname of the journal file.
6131 */
6132 const char *sqlite3PagerJournalname(Pager *pPager){
6133   return pPager->zJournal;
6134 }
6135 
6136 /*
6137 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
6138 ** if fsync()s are executed normally.
6139 */
6140 int sqlite3PagerNosync(Pager *pPager){
6141   return pPager->noSync;
6142 }
6143 
6144 #ifdef SQLITE_HAS_CODEC
6145 /*
6146 ** Set or retrieve the codec for this pager
6147 */
6148 void sqlite3PagerSetCodec(
6149   Pager *pPager,
6150   void *(*xCodec)(void*,void*,Pgno,int),
6151   void (*xCodecSizeChng)(void*,int,int),
6152   void (*xCodecFree)(void*),
6153   void *pCodec
6154 ){
6155   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
6156   pPager->xCodec = pPager->memDb ? 0 : xCodec;
6157   pPager->xCodecSizeChng = xCodecSizeChng;
6158   pPager->xCodecFree = xCodecFree;
6159   pPager->pCodec = pCodec;
6160   pagerReportSize(pPager);
6161 }
6162 void *sqlite3PagerGetCodec(Pager *pPager){
6163   return pPager->pCodec;
6164 }
6165 #endif
6166 
6167 #ifndef SQLITE_OMIT_AUTOVACUUM
6168 /*
6169 ** Move the page pPg to location pgno in the file.
6170 **
6171 ** There must be no references to the page previously located at
6172 ** pgno (which we call pPgOld) though that page is allowed to be
6173 ** in cache.  If the page previously located at pgno is not already
6174 ** in the rollback journal, it is not put there by by this routine.
6175 **
6176 ** References to the page pPg remain valid. Updating any
6177 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
6178 ** allocated along with the page) is the responsibility of the caller.
6179 **
6180 ** A transaction must be active when this routine is called. It used to be
6181 ** required that a statement transaction was not active, but this restriction
6182 ** has been removed (CREATE INDEX needs to move a page when a statement
6183 ** transaction is active).
6184 **
6185 ** If the fourth argument, isCommit, is non-zero, then this page is being
6186 ** moved as part of a database reorganization just before the transaction
6187 ** is being committed. In this case, it is guaranteed that the database page
6188 ** pPg refers to will not be written to again within this transaction.
6189 **
6190 ** This function may return SQLITE_NOMEM or an IO error code if an error
6191 ** occurs. Otherwise, it returns SQLITE_OK.
6192 */
6193 int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
6194   PgHdr *pPgOld;               /* The page being overwritten. */
6195   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
6196   int rc;                      /* Return code */
6197   Pgno origPgno;               /* The original page number */
6198 
6199   assert( pPg->nRef>0 );
6200   assert( pPager->eState==PAGER_WRITER_CACHEMOD
6201        || pPager->eState==PAGER_WRITER_DBMOD
6202   );
6203   assert( assert_pager_state(pPager) );
6204 
6205   /* In order to be able to rollback, an in-memory database must journal
6206   ** the page we are moving from.
6207   */
6208   if( MEMDB ){
6209     rc = sqlite3PagerWrite(pPg);
6210     if( rc ) return rc;
6211   }
6212 
6213   /* If the page being moved is dirty and has not been saved by the latest
6214   ** savepoint, then save the current contents of the page into the
6215   ** sub-journal now. This is required to handle the following scenario:
6216   **
6217   **   BEGIN;
6218   **     <journal page X, then modify it in memory>
6219   **     SAVEPOINT one;
6220   **       <Move page X to location Y>
6221   **     ROLLBACK TO one;
6222   **
6223   ** If page X were not written to the sub-journal here, it would not
6224   ** be possible to restore its contents when the "ROLLBACK TO one"
6225   ** statement were is processed.
6226   **
6227   ** subjournalPage() may need to allocate space to store pPg->pgno into
6228   ** one or more savepoint bitvecs. This is the reason this function
6229   ** may return SQLITE_NOMEM.
6230   */
6231   if( pPg->flags&PGHDR_DIRTY
6232    && subjRequiresPage(pPg)
6233    && SQLITE_OK!=(rc = subjournalPage(pPg))
6234   ){
6235     return rc;
6236   }
6237 
6238   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
6239       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
6240   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
6241 
6242   /* If the journal needs to be sync()ed before page pPg->pgno can
6243   ** be written to, store pPg->pgno in local variable needSyncPgno.
6244   **
6245   ** If the isCommit flag is set, there is no need to remember that
6246   ** the journal needs to be sync()ed before database page pPg->pgno
6247   ** can be written to. The caller has already promised not to write to it.
6248   */
6249   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
6250     needSyncPgno = pPg->pgno;
6251     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
6252     assert( pPg->flags&PGHDR_DIRTY );
6253   }
6254 
6255   /* If the cache contains a page with page-number pgno, remove it
6256   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
6257   ** page pgno before the 'move' operation, it needs to be retained
6258   ** for the page moved there.
6259   */
6260   pPg->flags &= ~PGHDR_NEED_SYNC;
6261   pPgOld = pager_lookup(pPager, pgno);
6262   assert( !pPgOld || pPgOld->nRef==1 );
6263   if( pPgOld ){
6264     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
6265     if( MEMDB ){
6266       /* Do not discard pages from an in-memory database since we might
6267       ** need to rollback later.  Just move the page out of the way. */
6268       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
6269     }else{
6270       sqlite3PcacheDrop(pPgOld);
6271     }
6272   }
6273 
6274   origPgno = pPg->pgno;
6275   sqlite3PcacheMove(pPg, pgno);
6276   sqlite3PcacheMakeDirty(pPg);
6277 
6278   /* For an in-memory database, make sure the original page continues
6279   ** to exist, in case the transaction needs to roll back.  Use pPgOld
6280   ** as the original page since it has already been allocated.
6281   */
6282   if( MEMDB ){
6283     assert( pPgOld );
6284     sqlite3PcacheMove(pPgOld, origPgno);
6285     sqlite3PagerUnref(pPgOld);
6286   }
6287 
6288   if( needSyncPgno ){
6289     /* If needSyncPgno is non-zero, then the journal file needs to be
6290     ** sync()ed before any data is written to database file page needSyncPgno.
6291     ** Currently, no such page exists in the page-cache and the
6292     ** "is journaled" bitvec flag has been set. This needs to be remedied by
6293     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
6294     ** flag.
6295     **
6296     ** If the attempt to load the page into the page-cache fails, (due
6297     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
6298     ** array. Otherwise, if the page is loaded and written again in
6299     ** this transaction, it may be written to the database file before
6300     ** it is synced into the journal file. This way, it may end up in
6301     ** the journal file twice, but that is not a problem.
6302     */
6303     PgHdr *pPgHdr;
6304     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
6305     if( rc!=SQLITE_OK ){
6306       if( needSyncPgno<=pPager->dbOrigSize ){
6307         assert( pPager->pTmpSpace!=0 );
6308         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
6309       }
6310       return rc;
6311     }
6312     pPgHdr->flags |= PGHDR_NEED_SYNC;
6313     sqlite3PcacheMakeDirty(pPgHdr);
6314     sqlite3PagerUnref(pPgHdr);
6315   }
6316 
6317   return SQLITE_OK;
6318 }
6319 #endif
6320 
6321 /*
6322 ** Return a pointer to the data for the specified page.
6323 */
6324 void *sqlite3PagerGetData(DbPage *pPg){
6325   assert( pPg->nRef>0 || pPg->pPager->memDb );
6326   return pPg->pData;
6327 }
6328 
6329 /*
6330 ** Return a pointer to the Pager.nExtra bytes of "extra" space
6331 ** allocated along with the specified page.
6332 */
6333 void *sqlite3PagerGetExtra(DbPage *pPg){
6334   return pPg->pExtra;
6335 }
6336 
6337 /*
6338 ** Get/set the locking-mode for this pager. Parameter eMode must be one
6339 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
6340 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
6341 ** the locking-mode is set to the value specified.
6342 **
6343 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
6344 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
6345 ** locking-mode.
6346 */
6347 int sqlite3PagerLockingMode(Pager *pPager, int eMode){
6348   assert( eMode==PAGER_LOCKINGMODE_QUERY
6349             || eMode==PAGER_LOCKINGMODE_NORMAL
6350             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
6351   assert( PAGER_LOCKINGMODE_QUERY<0 );
6352   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
6353   if( eMode>=0 && !pPager->tempFile ){
6354     pPager->exclusiveMode = (u8)eMode;
6355   }
6356   return (int)pPager->exclusiveMode;
6357 }
6358 
6359 /*
6360 ** Set the journal-mode for this pager. Parameter eMode must be one of:
6361 **
6362 **    PAGER_JOURNALMODE_DELETE
6363 **    PAGER_JOURNALMODE_TRUNCATE
6364 **    PAGER_JOURNALMODE_PERSIST
6365 **    PAGER_JOURNALMODE_OFF
6366 **    PAGER_JOURNALMODE_MEMORY
6367 **    PAGER_JOURNALMODE_WAL
6368 **
6369 ** The journalmode is set to the value specified if the change is allowed.
6370 ** The change may be disallowed for the following reasons:
6371 **
6372 **   *  An in-memory database can only have its journal_mode set to _OFF
6373 **      or _MEMORY.
6374 **
6375 **   *  Temporary databases cannot have _WAL journalmode.
6376 **
6377 ** The returned indicate the current (possibly updated) journal-mode.
6378 */
6379 int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
6380   u8 eOld = pPager->journalMode;    /* Prior journalmode */
6381 
6382 #ifdef SQLITE_DEBUG
6383   /* The print_pager_state() routine is intended to be used by the debugger
6384   ** only.  We invoke it once here to suppress a compiler warning. */
6385   print_pager_state(pPager);
6386 #endif
6387 
6388 
6389   /* The eMode parameter is always valid */
6390   assert(      eMode==PAGER_JOURNALMODE_DELETE
6391             || eMode==PAGER_JOURNALMODE_TRUNCATE
6392             || eMode==PAGER_JOURNALMODE_PERSIST
6393             || eMode==PAGER_JOURNALMODE_OFF
6394             || eMode==PAGER_JOURNALMODE_WAL
6395             || eMode==PAGER_JOURNALMODE_MEMORY );
6396 
6397   /* This routine is only called from the OP_JournalMode opcode, and
6398   ** the logic there will never allow a temporary file to be changed
6399   ** to WAL mode.
6400   */
6401   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
6402 
6403   /* Do allow the journalmode of an in-memory database to be set to
6404   ** anything other than MEMORY or OFF
6405   */
6406   if( MEMDB ){
6407     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
6408     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
6409       eMode = eOld;
6410     }
6411   }
6412 
6413   if( eMode!=eOld ){
6414 
6415     /* Change the journal mode. */
6416     assert( pPager->eState!=PAGER_ERROR );
6417     pPager->journalMode = (u8)eMode;
6418 
6419     /* When transistioning from TRUNCATE or PERSIST to any other journal
6420     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
6421     ** delete the journal file.
6422     */
6423     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
6424     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
6425     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
6426     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
6427     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
6428     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
6429 
6430     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
6431     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
6432 
6433       /* In this case we would like to delete the journal file. If it is
6434       ** not possible, then that is not a problem. Deleting the journal file
6435       ** here is an optimization only.
6436       **
6437       ** Before deleting the journal file, obtain a RESERVED lock on the
6438       ** database file. This ensures that the journal file is not deleted
6439       ** while it is in use by some other client.
6440       */
6441       sqlite3OsClose(pPager->jfd);
6442       if( pPager->eLock>=RESERVED_LOCK ){
6443         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
6444       }else{
6445         int rc = SQLITE_OK;
6446         int state = pPager->eState;
6447         assert( state==PAGER_OPEN || state==PAGER_READER );
6448         if( state==PAGER_OPEN ){
6449           rc = sqlite3PagerSharedLock(pPager);
6450         }
6451         if( pPager->eState==PAGER_READER ){
6452           assert( rc==SQLITE_OK );
6453           rc = pagerLockDb(pPager, RESERVED_LOCK);
6454         }
6455         if( rc==SQLITE_OK ){
6456           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
6457         }
6458         if( rc==SQLITE_OK && state==PAGER_READER ){
6459           pagerUnlockDb(pPager, SHARED_LOCK);
6460         }else if( state==PAGER_OPEN ){
6461           pager_unlock(pPager);
6462         }
6463         assert( state==pPager->eState );
6464       }
6465     }
6466   }
6467 
6468   /* Return the new journal mode */
6469   return (int)pPager->journalMode;
6470 }
6471 
6472 /*
6473 ** Return the current journal mode.
6474 */
6475 int sqlite3PagerGetJournalMode(Pager *pPager){
6476   return (int)pPager->journalMode;
6477 }
6478 
6479 /*
6480 ** Return TRUE if the pager is in a state where it is OK to change the
6481 ** journalmode.  Journalmode changes can only happen when the database
6482 ** is unmodified.
6483 */
6484 int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
6485   assert( assert_pager_state(pPager) );
6486   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
6487   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
6488   return 1;
6489 }
6490 
6491 /*
6492 ** Get/set the size-limit used for persistent journal files.
6493 **
6494 ** Setting the size limit to -1 means no limit is enforced.
6495 ** An attempt to set a limit smaller than -1 is a no-op.
6496 */
6497 i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
6498   if( iLimit>=-1 ){
6499     pPager->journalSizeLimit = iLimit;
6500   }
6501   return pPager->journalSizeLimit;
6502 }
6503 
6504 /*
6505 ** Return a pointer to the pPager->pBackup variable. The backup module
6506 ** in backup.c maintains the content of this variable. This module
6507 ** uses it opaquely as an argument to sqlite3BackupRestart() and
6508 ** sqlite3BackupUpdate() only.
6509 */
6510 sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
6511   return &pPager->pBackup;
6512 }
6513 
6514 #ifndef SQLITE_OMIT_WAL
6515 /*
6516 ** This function is called when the user invokes "PRAGMA checkpoint".
6517 */
6518 int sqlite3PagerCheckpoint(Pager *pPager){
6519   int rc = SQLITE_OK;
6520   if( pPager->pWal ){
6521     u8 *zBuf = (u8 *)pPager->pTmpSpace;
6522     rc = sqlite3WalCheckpoint(pPager->pWal,
6523         (pPager->noSync ? 0 : pPager->sync_flags),
6524         pPager->pageSize, zBuf
6525     );
6526   }
6527   return rc;
6528 }
6529 
6530 int sqlite3PagerWalCallback(Pager *pPager){
6531   return sqlite3WalCallback(pPager->pWal);
6532 }
6533 
6534 /*
6535 ** Return true if the underlying VFS for the given pager supports the
6536 ** primitives necessary for write-ahead logging.
6537 */
6538 int sqlite3PagerWalSupported(Pager *pPager){
6539   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
6540   return pMethods->iVersion>=2 && pMethods->xShmMap!=0;
6541 }
6542 
6543 /*
6544 ** The caller must be holding a SHARED lock on the database file to call
6545 ** this function.
6546 **
6547 ** If the pager passed as the first argument is open on a real database
6548 ** file (not a temp file or an in-memory database), and the WAL file
6549 ** is not already open, make an attempt to open it now. If successful,
6550 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
6551 ** not support the xShmXXX() methods, return an error code. *pbOpen is
6552 ** not modified in either case.
6553 **
6554 ** If the pager is open on a temp-file (or in-memory database), or if
6555 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
6556 ** without doing anything.
6557 */
6558 int sqlite3PagerOpenWal(
6559   Pager *pPager,                  /* Pager object */
6560   int *pbOpen                     /* OUT: Set to true if call is a no-op */
6561 ){
6562   int rc = SQLITE_OK;             /* Return code */
6563 
6564   assert( assert_pager_state(pPager) );
6565   assert( pPager->eState==PAGER_OPEN   || pbOpen );
6566   assert( pPager->eState==PAGER_READER || !pbOpen );
6567   assert( pbOpen==0 || *pbOpen==0 );
6568   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
6569 
6570   if( !pPager->tempFile && !pPager->pWal ){
6571     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
6572 
6573     /* Close any rollback journal previously open */
6574     sqlite3OsClose(pPager->jfd);
6575 
6576     /* Open the connection to the log file. If this operation fails,
6577     ** (e.g. due to malloc() failure), unlock the database file and
6578     ** return an error code.
6579     */
6580     rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, &pPager->pWal);
6581     if( rc==SQLITE_OK ){
6582       pPager->journalMode = PAGER_JOURNALMODE_WAL;
6583       pPager->eState = PAGER_OPEN;
6584     }
6585   }else{
6586     *pbOpen = 1;
6587   }
6588 
6589   return rc;
6590 }
6591 
6592 /*
6593 ** This function is called to close the connection to the log file prior
6594 ** to switching from WAL to rollback mode.
6595 **
6596 ** Before closing the log file, this function attempts to take an
6597 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
6598 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
6599 ** If successful, the EXCLUSIVE lock is not released before returning.
6600 */
6601 int sqlite3PagerCloseWal(Pager *pPager){
6602   int rc = SQLITE_OK;
6603 
6604   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
6605 
6606   /* If the log file is not already open, but does exist in the file-system,
6607   ** it may need to be checkpointed before the connection can switch to
6608   ** rollback mode. Open it now so this can happen.
6609   */
6610   if( !pPager->pWal ){
6611     int logexists = 0;
6612     rc = pagerLockDb(pPager, SHARED_LOCK);
6613     if( rc==SQLITE_OK ){
6614       rc = sqlite3OsAccess(
6615           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
6616       );
6617     }
6618     if( rc==SQLITE_OK && logexists ){
6619       rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
6620                           pPager->zWal, &pPager->pWal);
6621     }
6622   }
6623 
6624   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
6625   ** the database file, the log and log-summary files will be deleted.
6626   */
6627   if( rc==SQLITE_OK && pPager->pWal ){
6628     rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
6629     if( rc==SQLITE_OK ){
6630       rc = sqlite3WalClose(pPager->pWal,
6631                            (pPager->noSync ? 0 : pPager->sync_flags),
6632         pPager->pageSize, (u8*)pPager->pTmpSpace
6633       );
6634       pPager->pWal = 0;
6635     }else{
6636       /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
6637       ** that we did get back to SHARED. */
6638       pagerUnlockDb(pPager, SQLITE_LOCK_SHARED);
6639     }
6640   }
6641   return rc;
6642 }
6643 
6644 #ifdef SQLITE_HAS_CODEC
6645 /*
6646 ** This function is called by the wal module when writing page content
6647 ** into the log file.
6648 **
6649 ** This function returns a pointer to a buffer containing the encrypted
6650 ** page content. If a malloc fails, this function may return NULL.
6651 */
6652 void *sqlite3PagerCodec(PgHdr *pPg){
6653   void *aData = 0;
6654   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
6655   return aData;
6656 }
6657 #endif /* SQLITE_HAS_CODEC */
6658 
6659 #endif /* !SQLITE_OMIT_WAL */
6660 
6661 #endif /* SQLITE_OMIT_DISKIO */
6662