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