xref: /sqlite-3.40.0/src/pager.c (revision ad617b4d)
1ed7c855cSdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3ed7c855cSdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6ed7c855cSdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10ed7c855cSdrh **
11ed7c855cSdrh *************************************************************************
12b19a2bc6Sdrh ** This is the implementation of the page cache subsystem or "pager".
13ed7c855cSdrh **
14b19a2bc6Sdrh ** The pager is used to access a database disk file.  It implements
15b19a2bc6Sdrh ** atomic commit and rollback through the use of a journal file that
16b19a2bc6Sdrh ** is separate from the database file.  The pager also implements file
17b19a2bc6Sdrh ** locking to prevent two processes from writing the same database
18b19a2bc6Sdrh ** file simultaneously, or one process from reading the database while
19b19a2bc6Sdrh ** another is writing.
20ed7c855cSdrh */
212e66f0b9Sdrh #ifndef SQLITE_OMIT_DISKIO
22d9b0257aSdrh #include "sqliteInt.h"
23c438efd6Sdrh #include "wal.h"
24ed7c855cSdrh 
25e5918c62Sdrh 
26e5918c62Sdrh /******************* NOTES ON THE DESIGN OF THE PAGER ************************
27e5918c62Sdrh **
28e5918c62Sdrh ** This comment block describes invariants that hold when using a rollback
29e5918c62Sdrh ** journal.  These invariants do not apply for journal_mode=WAL,
30e5918c62Sdrh ** journal_mode=MEMORY, or journal_mode=OFF.
3191781bd7Sdrh **
3291781bd7Sdrh ** Within this comment block, a page is deemed to have been synced
3391781bd7Sdrh ** automatically as soon as it is written when PRAGMA synchronous=OFF.
3491781bd7Sdrh ** Otherwise, the page is not synced until the xSync method of the VFS
3591781bd7Sdrh ** is called successfully on the file containing the page.
3691781bd7Sdrh **
3791781bd7Sdrh ** Definition:  A page of the database file is said to be "overwriteable" if
3891781bd7Sdrh ** one or more of the following are true about the page:
3991781bd7Sdrh **
4091781bd7Sdrh **     (a)  The original content of the page as it was at the beginning of
4191781bd7Sdrh **          the transaction has been written into the rollback journal and
4291781bd7Sdrh **          synced.
4391781bd7Sdrh **
4491781bd7Sdrh **     (b)  The page was a freelist leaf page at the start of the transaction.
4591781bd7Sdrh **
4691781bd7Sdrh **     (c)  The page number is greater than the largest page that existed in
4791781bd7Sdrh **          the database file at the start of the transaction.
4891781bd7Sdrh **
4991781bd7Sdrh ** (1) A page of the database file is never overwritten unless one of the
5091781bd7Sdrh **     following are true:
5191781bd7Sdrh **
5291781bd7Sdrh **     (a) The page and all other pages on the same sector are overwriteable.
5391781bd7Sdrh **
5491781bd7Sdrh **     (b) The atomic page write optimization is enabled, and the entire
5591781bd7Sdrh **         transaction other than the update of the transaction sequence
5691781bd7Sdrh **         number consists of a single page change.
5791781bd7Sdrh **
5891781bd7Sdrh ** (2) The content of a page written into the rollback journal exactly matches
5991781bd7Sdrh **     both the content in the database when the rollback journal was written
6091781bd7Sdrh **     and the content in the database at the beginning of the current
6191781bd7Sdrh **     transaction.
6291781bd7Sdrh **
6391781bd7Sdrh ** (3) Writes to the database file are an integer multiple of the page size
64e5918c62Sdrh **     in length and are aligned on a page boundary.
6591781bd7Sdrh **
6691781bd7Sdrh ** (4) Reads from the database file are either aligned on a page boundary and
6791781bd7Sdrh **     an integer multiple of the page size in length or are taken from the
6891781bd7Sdrh **     first 100 bytes of the database file.
6991781bd7Sdrh **
7091781bd7Sdrh ** (5) All writes to the database file are synced prior to the rollback journal
7191781bd7Sdrh **     being deleted, truncated, or zeroed.
7291781bd7Sdrh **
73067b92baSdrh ** (6) If a super-journal file is used, then all writes to the database file
74067b92baSdrh **     are synced prior to the super-journal being deleted.
7591781bd7Sdrh **
7691781bd7Sdrh ** Definition: Two databases (or the same database at two points it time)
7791781bd7Sdrh ** are said to be "logically equivalent" if they give the same answer to
78d5578433Smistachkin ** all queries.  Note in particular the content of freelist leaf
7960ec914cSpeter.d.reid ** pages can be changed arbitrarily without affecting the logical equivalence
8091781bd7Sdrh ** of the database.
8191781bd7Sdrh **
8291781bd7Sdrh ** (7) At any time, if any subset, including the empty set and the total set,
8391781bd7Sdrh **     of the unsynced changes to a rollback journal are removed and the
8460ec914cSpeter.d.reid **     journal is rolled back, the resulting database file will be logically
8591781bd7Sdrh **     equivalent to the database file at the beginning of the transaction.
8691781bd7Sdrh **
8791781bd7Sdrh ** (8) When a transaction is rolled back, the xTruncate method of the VFS
8891781bd7Sdrh **     is called to restore the database file to the same size it was at
8991781bd7Sdrh **     the beginning of the transaction.  (In some VFSes, the xTruncate
9091781bd7Sdrh **     method is a no-op, but that does not change the fact the SQLite will
9191781bd7Sdrh **     invoke it.)
9291781bd7Sdrh **
9391781bd7Sdrh ** (9) Whenever the database file is modified, at least one bit in the range
9491781bd7Sdrh **     of bytes from 24 through 39 inclusive will be changed prior to releasing
95e5918c62Sdrh **     the EXCLUSIVE lock, thus signaling other connections on the same
96e5918c62Sdrh **     database to flush their caches.
9791781bd7Sdrh **
9891781bd7Sdrh ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
9991781bd7Sdrh **      than one billion transactions.
10091781bd7Sdrh **
10191781bd7Sdrh ** (11) A database file is well-formed at the beginning and at the conclusion
10291781bd7Sdrh **      of every transaction.
10391781bd7Sdrh **
10491781bd7Sdrh ** (12) An EXCLUSIVE lock is held on the database file when writing to
10591781bd7Sdrh **      the database file.
10691781bd7Sdrh **
10791781bd7Sdrh ** (13) A SHARED lock is held on the database file while reading any
10891781bd7Sdrh **      content out of the database file.
109e5918c62Sdrh **
110e5918c62Sdrh ******************************************************************************/
11191781bd7Sdrh 
11291781bd7Sdrh /*
113db48ee02Sdrh ** Macros for troubleshooting.  Normally turned off
114db48ee02Sdrh */
115466be56bSdanielk1977 #if 0
116f2c31ad8Sdanielk1977 int sqlite3PagerTrace=1;  /* True to enable tracing */
117d3627afcSdrh #define sqlite3DebugPrintf printf
11830d53701Sdrh #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
119db48ee02Sdrh #else
12030d53701Sdrh #define PAGERTRACE(X)
121db48ee02Sdrh #endif
122db48ee02Sdrh 
123599fcbaeSdanielk1977 /*
12430d53701Sdrh ** The following two macros are used within the PAGERTRACE() macros above
125d86959f5Sdrh ** to print out file-descriptors.
126599fcbaeSdanielk1977 **
12785b623f2Sdrh ** PAGERID() takes a pointer to a Pager struct as its argument. The
12862079060Sdanielk1977 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
12985b623f2Sdrh ** struct as its argument.
130599fcbaeSdanielk1977 */
131b7f4b6ccSdrh #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
132b7f4b6ccSdrh #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
133db48ee02Sdrh 
134db48ee02Sdrh /*
135d0864087Sdan ** The Pager.eState variable stores the current 'state' of a pager. A
136431b0b42Sdan ** pager may be in any one of the seven states shown in the following
137431b0b42Sdan ** state diagram.
138431b0b42Sdan **
139de1ae34eSdan **                            OPEN <------+------+
140431b0b42Sdan **                              |         |      |
141431b0b42Sdan **                              V         |      |
142431b0b42Sdan **               +---------> READER-------+      |
143431b0b42Sdan **               |              |                |
144431b0b42Sdan **               |              V                |
145de1ae34eSdan **               |<-------WRITER_LOCKED------> ERROR
146431b0b42Sdan **               |              |                ^
147431b0b42Sdan **               |              V                |
148431b0b42Sdan **               |<------WRITER_CACHEMOD-------->|
149431b0b42Sdan **               |              |                |
150431b0b42Sdan **               |              V                |
151431b0b42Sdan **               |<-------WRITER_DBMOD---------->|
152431b0b42Sdan **               |              |                |
153431b0b42Sdan **               |              V                |
154431b0b42Sdan **               +<------WRITER_FINISHED-------->+
155d0864087Sdan **
15611f47a9bSdan **
15711f47a9bSdan ** List of state transitions and the C [function] that performs each:
15811f47a9bSdan **
159de1ae34eSdan **   OPEN              -> READER              [sqlite3PagerSharedLock]
160de1ae34eSdan **   READER            -> OPEN                [pager_unlock]
16111f47a9bSdan **
162de1ae34eSdan **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
163de1ae34eSdan **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
16411f47a9bSdan **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
16511f47a9bSdan **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
16611f47a9bSdan **   WRITER_***        -> READER              [pager_end_transaction]
16711f47a9bSdan **
16811f47a9bSdan **   WRITER_***        -> ERROR               [pager_error]
169de1ae34eSdan **   ERROR             -> OPEN                [pager_unlock]
17011f47a9bSdan **
17111f47a9bSdan **
172de1ae34eSdan **  OPEN:
173937ac9daSdan **
174763afe62Sdan **    The pager starts up in this state. Nothing is guaranteed in this
175763afe62Sdan **    state - the file may or may not be locked and the database size is
176763afe62Sdan **    unknown. The database may not be read or written.
177763afe62Sdan **
178d0864087Sdan **    * No read or write transaction is active.
179d0864087Sdan **    * Any lock, or no lock at all, may be held on the database file.
180763afe62Sdan **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
181d0864087Sdan **
182d0864087Sdan **  READER:
183b22aa4a6Sdan **
184763afe62Sdan **    In this state all the requirements for reading the database in
185763afe62Sdan **    rollback (non-WAL) mode are met. Unless the pager is (or recently
186763afe62Sdan **    was) in exclusive-locking mode, a user-level read transaction is
187763afe62Sdan **    open. The database size is known in this state.
188763afe62Sdan **
18954919f82Sdan **    A connection running with locking_mode=normal enters this state when
19054919f82Sdan **    it opens a read-transaction on the database and returns to state
191de1ae34eSdan **    OPEN after the read-transaction is completed. However a connection
19254919f82Sdan **    running in locking_mode=exclusive (including temp databases) remains in
19354919f82Sdan **    this state even after the read-transaction is closed. The only way
194de1ae34eSdan **    a locking_mode=exclusive connection can transition from READER to OPEN
19554919f82Sdan **    is via the ERROR state (see below).
19654919f82Sdan **
19754919f82Sdan **    * A read transaction may be active (but a write-transaction cannot).
198d0864087Sdan **    * A SHARED or greater lock is held on the database file.
199763afe62Sdan **    * The dbSize variable may be trusted (even if a user-level read
200937ac9daSdan **      transaction is not active). The dbOrigSize and dbFileSize variables
201937ac9daSdan **      may not be trusted at this point.
20254919f82Sdan **    * If the database is a WAL database, then the WAL connection is open.
20354919f82Sdan **    * Even if a read-transaction is not open, it is guaranteed that
20454919f82Sdan **      there is no hot-journal in the file-system.
205d0864087Sdan **
206de1ae34eSdan **  WRITER_LOCKED:
207b22aa4a6Sdan **
20811f47a9bSdan **    The pager moves to this state from READER when a write-transaction
209de1ae34eSdan **    is first opened on the database. In WRITER_LOCKED state, all locks
210de1ae34eSdan **    required to start a write-transaction are held, but no actual
211de1ae34eSdan **    modifications to the cache or database have taken place.
212de1ae34eSdan **
213de1ae34eSdan **    In rollback mode, a RESERVED or (if the transaction was opened with
214de1ae34eSdan **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
215de1ae34eSdan **    moving to this state, but the journal file is not written to or opened
216de1ae34eSdan **    to in this state. If the transaction is committed or rolled back while
217de1ae34eSdan **    in WRITER_LOCKED state, all that is required is to unlock the database
218de1ae34eSdan **    file.
219de1ae34eSdan **
220de1ae34eSdan **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
221de1ae34eSdan **    If the connection is running with locking_mode=exclusive, an attempt
222de1ae34eSdan **    is made to obtain an EXCLUSIVE lock on the database file.
22311f47a9bSdan **
224d0864087Sdan **    * A write transaction is active.
22511f47a9bSdan **    * If the connection is open in rollback-mode, a RESERVED or greater
22611f47a9bSdan **      lock is held on the database file.
22711f47a9bSdan **    * If the connection is open in WAL-mode, a WAL write transaction
22811f47a9bSdan **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
22911f47a9bSdan **      called).
230d0864087Sdan **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
231d0864087Sdan **    * The contents of the pager cache have not been modified.
232b22aa4a6Sdan **    * The journal file may or may not be open.
233b22aa4a6Sdan **    * Nothing (not even the first header) has been written to the journal.
234d0864087Sdan **
235d0864087Sdan **  WRITER_CACHEMOD:
236b22aa4a6Sdan **
237de1ae34eSdan **    A pager moves from WRITER_LOCKED state to this state when a page is
238de1ae34eSdan **    first modified by the upper layer. In rollback mode the journal file
239de1ae34eSdan **    is opened (if it is not already open) and a header written to the
240de1ae34eSdan **    start of it. The database file on disk has not been modified.
241de1ae34eSdan **
242d0864087Sdan **    * A write transaction is active.
243d0864087Sdan **    * A RESERVED or greater lock is held on the database file.
244d0864087Sdan **    * The journal file is open and the first header has been written
245d0864087Sdan **      to it, but the header has not been synced to disk.
246d0864087Sdan **    * The contents of the page cache have been modified.
247d0864087Sdan **
248d0864087Sdan **  WRITER_DBMOD:
249b22aa4a6Sdan **
250de5fd22fSdan **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
251de5fd22fSdan **    when it modifies the contents of the database file. WAL connections
252de5fd22fSdan **    never enter this state (since they do not modify the database file,
253de5fd22fSdan **    just the log file).
254de5fd22fSdan **
255d0864087Sdan **    * A write transaction is active.
256d0864087Sdan **    * An EXCLUSIVE or greater lock is held on the database file.
257d0864087Sdan **    * The journal file is open and the first header has been written
258d0864087Sdan **      and synced to disk.
259d0864087Sdan **    * The contents of the page cache have been modified (and possibly
260d0864087Sdan **      written to disk).
261d0864087Sdan **
262d0864087Sdan **  WRITER_FINISHED:
263b22aa4a6Sdan **
264de5fd22fSdan **    It is not possible for a WAL connection to enter this state.
265de5fd22fSdan **
266de5fd22fSdan **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
267de5fd22fSdan **    state after the entire transaction has been successfully written into the
268de5fd22fSdan **    database file. In this state the transaction may be committed simply
269de5fd22fSdan **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
270de5fd22fSdan **    not possible to modify the database further. At this point, the upper
271de5fd22fSdan **    layer must either commit or rollback the transaction.
272de5fd22fSdan **
273d0864087Sdan **    * A write transaction is active.
274d0864087Sdan **    * An EXCLUSIVE or greater lock is held on the database file.
275d0864087Sdan **    * All writing and syncing of journal and database data has finished.
27648864df9Smistachkin **      If no error occurred, all that remains is to finalize the journal to
277d0864087Sdan **      commit the transaction. If an error did occur, the caller will need
278d0864087Sdan **      to rollback the transaction.
279d0864087Sdan **
280b22aa4a6Sdan **  ERROR:
281b22aa4a6Sdan **
28222b328b2Sdan **    The ERROR state is entered when an IO or disk-full error (including
28322b328b2Sdan **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
28422b328b2Sdan **    difficult to be sure that the in-memory pager state (cache contents,
28522b328b2Sdan **    db size etc.) are consistent with the contents of the file-system.
28622b328b2Sdan **
28722b328b2Sdan **    Temporary pager files may enter the ERROR state, but in-memory pagers
28822b328b2Sdan **    cannot.
289b22aa4a6Sdan **
290b22aa4a6Sdan **    For example, if an IO error occurs while performing a rollback,
291b22aa4a6Sdan **    the contents of the page-cache may be left in an inconsistent state.
292b22aa4a6Sdan **    At this point it would be dangerous to change back to READER state
293b22aa4a6Sdan **    (as usually happens after a rollback). Any subsequent readers might
294b22aa4a6Sdan **    report database corruption (due to the inconsistent cache), and if
295b22aa4a6Sdan **    they upgrade to writers, they may inadvertently corrupt the database
296b22aa4a6Sdan **    file. To avoid this hazard, the pager switches into the ERROR state
297b22aa4a6Sdan **    instead of READER following such an error.
298b22aa4a6Sdan **
299b22aa4a6Sdan **    Once it has entered the ERROR state, any attempt to use the pager
300b22aa4a6Sdan **    to read or write data returns an error. Eventually, once all
301b22aa4a6Sdan **    outstanding transactions have been abandoned, the pager is able to
302de1ae34eSdan **    transition back to OPEN state, discarding the contents of the
303b22aa4a6Sdan **    page-cache and any other in-memory state at the same time. Everything
304b22aa4a6Sdan **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
305b22aa4a6Sdan **    when a read-transaction is next opened on the pager (transitioning
306b22aa4a6Sdan **    the pager into READER state). At that point the system has recovered
307b22aa4a6Sdan **    from the error.
308b22aa4a6Sdan **
309b22aa4a6Sdan **    Specifically, the pager jumps into the ERROR state if:
310b22aa4a6Sdan **
311b22aa4a6Sdan **      1. An error occurs while attempting a rollback. This happens in
312b22aa4a6Sdan **         function sqlite3PagerRollback().
313b22aa4a6Sdan **
314b22aa4a6Sdan **      2. An error occurs while attempting to finalize a journal file
315b22aa4a6Sdan **         following a commit in function sqlite3PagerCommitPhaseTwo().
316b22aa4a6Sdan **
317b22aa4a6Sdan **      3. An error occurs while attempting to write to the journal or
318b22aa4a6Sdan **         database file in function pagerStress() in order to free up
319b22aa4a6Sdan **         memory.
320b22aa4a6Sdan **
321b22aa4a6Sdan **    In other cases, the error is returned to the b-tree layer. The b-tree
322b22aa4a6Sdan **    layer then attempts a rollback operation. If the error condition
323b22aa4a6Sdan **    persists, the pager enters the ERROR state via condition (1) above.
324b22aa4a6Sdan **
325b22aa4a6Sdan **    Condition (3) is necessary because it can be triggered by a read-only
326b22aa4a6Sdan **    statement executed within a transaction. In this case, if the error
327b22aa4a6Sdan **    code were simply returned to the user, the b-tree layer would not
328b22aa4a6Sdan **    automatically attempt a rollback, as it assumes that an error in a
329b22aa4a6Sdan **    read-only statement cannot leave the pager in an internally inconsistent
330b22aa4a6Sdan **    state.
331b22aa4a6Sdan **
332de1ae34eSdan **    * The Pager.errCode variable is set to something other than SQLITE_OK.
333de1ae34eSdan **    * There are one or more outstanding references to pages (after the
334de1ae34eSdan **      last reference is dropped the pager should move back to OPEN state).
33522b328b2Sdan **    * The pager is not an in-memory pager.
336de1ae34eSdan **
337b22aa4a6Sdan **
338763afe62Sdan ** Notes:
339763afe62Sdan **
340763afe62Sdan **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
341763afe62Sdan **     connection is open in WAL mode. A WAL connection is always in one
342763afe62Sdan **     of the first four states.
343763afe62Sdan **
344de1ae34eSdan **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
345763afe62Sdan **     state. There are two exceptions: immediately after exclusive-mode has
346763afe62Sdan **     been turned on (and before any read or write transactions are
347763afe62Sdan **     executed), and when the pager is leaving the "error state".
348763afe62Sdan **
349763afe62Sdan **   * See also: assert_pager_state().
350d0864087Sdan */
351de1ae34eSdan #define PAGER_OPEN                  0
352d0864087Sdan #define PAGER_READER                1
353de1ae34eSdan #define PAGER_WRITER_LOCKED         2
354d0864087Sdan #define PAGER_WRITER_CACHEMOD       3
355d0864087Sdan #define PAGER_WRITER_DBMOD          4
356d0864087Sdan #define PAGER_WRITER_FINISHED       5
357a42c66bdSdan #define PAGER_ERROR                 6
358d0864087Sdan 
359d0864087Sdan /*
36054919f82Sdan ** The Pager.eLock variable is almost always set to one of the
36154919f82Sdan ** following locking-states, according to the lock currently held on
36254919f82Sdan ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
36354919f82Sdan ** This variable is kept up to date as locks are taken and released by
36454919f82Sdan ** the pagerLockDb() and pagerUnlockDb() wrappers.
365ed7c855cSdrh **
36654919f82Sdan ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
36754919f82Sdan ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
36854919f82Sdan ** the operation was successful. In these circumstances pagerLockDb() and
36954919f82Sdan ** pagerUnlockDb() take a conservative approach - eLock is always updated
37054919f82Sdan ** when unlocking the file, and only updated when locking the file if the
37154919f82Sdan ** VFS call is successful. This way, the Pager.eLock variable may be set
37254919f82Sdan ** to a less exclusive (lower) value than the lock that is actually held
37354919f82Sdan ** at the system level, but it is never set to a more exclusive value.
374ed7c855cSdrh **
37554919f82Sdan ** This is usually safe. If an xUnlock fails or appears to fail, there may
37654919f82Sdan ** be a few redundant xLock() calls or a lock may be held for longer than
37754919f82Sdan ** required, but nothing really goes wrong.
378ed7c855cSdrh **
37954919f82Sdan ** The exception is when the database file is unlocked as the pager moves
380de1ae34eSdan ** from ERROR to OPEN state. At this point there may be a hot-journal file
38160ec914cSpeter.d.reid ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
38254919f82Sdan ** transition, by the same pager or any other). If the call to xUnlock()
38354919f82Sdan ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
38454919f82Sdan ** can confuse the call to xCheckReservedLock() call made later as part
38554919f82Sdan ** of hot-journal detection.
386a6abd041Sdrh **
38754919f82Sdan ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
38854919f82Sdan ** lock held by this process or any others". So xCheckReservedLock may
38954919f82Sdan ** return true because the caller itself is holding an EXCLUSIVE lock (but
39054919f82Sdan ** doesn't know it because of a previous error in xUnlock). If this happens
39154919f82Sdan ** a hot-journal may be mistaken for a journal being created by an active
39254919f82Sdan ** transaction in another process, causing SQLite to read from the database
39354919f82Sdan ** without rolling it back.
394ed7c855cSdrh **
39554919f82Sdan ** To work around this, if a call to xUnlock() fails when unlocking the
39654919f82Sdan ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
39754919f82Sdan ** is only changed back to a real locking state after a successful call
398de1ae34eSdan ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
39954919f82Sdan ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
40054919f82Sdan ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
40154919f82Sdan ** lock on the database file before attempting to roll it back. See function
40254919f82Sdan ** PagerSharedLock() for more detail.
403aa5ccdf5Sdanielk1977 **
40454919f82Sdan ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
405de1ae34eSdan ** PAGER_OPEN state.
406ed7c855cSdrh */
4074e004aa6Sdan #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
4084e004aa6Sdan 
409684917c2Sdrh /*
4101a5c00f8Sdrh ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
4117cbd589dSdanielk1977 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
4127cbd589dSdanielk1977 ** This could conceivably cause corruption following a power failure on
4137cbd589dSdanielk1977 ** such a system. This is currently an undocumented limit.
4147cbd589dSdanielk1977 */
4151a5c00f8Sdrh #define MAX_SECTOR_SIZE 0x10000
4167cbd589dSdanielk1977 
417164c957bSdrh 
418164c957bSdrh /*
419fd7f0452Sdanielk1977 ** An instance of the following structure is allocated for each active
420fd7f0452Sdanielk1977 ** savepoint and statement transaction in the system. All such structures
421fd7f0452Sdanielk1977 ** are stored in the Pager.aSavepoint[] array, which is allocated and
422fd7f0452Sdanielk1977 ** resized using sqlite3Realloc().
423fd7f0452Sdanielk1977 **
424fd7f0452Sdanielk1977 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
425fd7f0452Sdanielk1977 ** set to 0. If a journal-header is written into the main journal while
426fd7f0452Sdanielk1977 ** the savepoint is active, then iHdrOffset is set to the byte offset
427fd7f0452Sdanielk1977 ** immediately following the last journal record written into the main
428fd7f0452Sdanielk1977 ** journal before the journal-header. This is required during savepoint
429fd7f0452Sdanielk1977 ** rollback (see pagerPlaybackSavepoint()).
430fd7f0452Sdanielk1977 */
431fd7f0452Sdanielk1977 typedef struct PagerSavepoint PagerSavepoint;
432fd7f0452Sdanielk1977 struct PagerSavepoint {
433fd7f0452Sdanielk1977   i64 iOffset;                 /* Starting offset in main journal */
434fd7f0452Sdanielk1977   i64 iHdrOffset;              /* See above */
435fd7f0452Sdanielk1977   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
436fd7f0452Sdanielk1977   Pgno nOrig;                  /* Original number of pages in file */
437fd7f0452Sdanielk1977   Pgno iSubRec;                /* Index of first record in sub-journal */
438f43fef29Sdan   int bTruncateOnRelease;      /* If stmt journal may be truncated on RELEASE */
43938e1a279Sdan #ifndef SQLITE_OMIT_WAL
44071d89919Sdan   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
44138e1a279Sdan #endif
442fd7f0452Sdanielk1977 };
443fd7f0452Sdanielk1977 
444fd7f0452Sdanielk1977 /*
44540c3941cSdrh ** Bits of the Pager.doNotSpill flag.  See further description below.
44640c3941cSdrh */
44740c3941cSdrh #define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
44840c3941cSdrh #define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
44940c3941cSdrh #define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
45040c3941cSdrh 
45140c3941cSdrh /*
45260ec914cSpeter.d.reid ** An open page cache is an instance of struct Pager. A description of
453de1ae34eSdan ** some of the more important member variables follows:
454efaaf579Sdanielk1977 **
455de1ae34eSdan ** eState
456bea2a948Sdanielk1977 **
457de1ae34eSdan **   The current 'state' of the pager object. See the comment and state
458de1ae34eSdan **   diagram above for a description of the pager state.
4593460d19cSdanielk1977 **
460de1ae34eSdan ** eLock
461bea2a948Sdanielk1977 **
462de1ae34eSdan **   For a real on-disk database, the current lock held on the database file -
463de1ae34eSdan **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
464de1ae34eSdan **
465de1ae34eSdan **   For a temporary or in-memory database (neither of which require any
466de1ae34eSdan **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
467de1ae34eSdan **   databases always have Pager.exclusiveMode==1, this tricks the pager
468de1ae34eSdan **   logic into thinking that it already has all the locks it will ever
469de1ae34eSdan **   need (and no reason to release them).
470de1ae34eSdan **
471de1ae34eSdan **   In some (obscure) circumstances, this variable may also be set to
472de1ae34eSdan **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
473de1ae34eSdan **   details.
474bea2a948Sdanielk1977 **
475bea2a948Sdanielk1977 ** changeCountDone
476bea2a948Sdanielk1977 **
477bea2a948Sdanielk1977 **   This boolean variable is used to make sure that the change-counter
478bea2a948Sdanielk1977 **   (the 4-byte header field at byte offset 24 of the database file) is
479bea2a948Sdanielk1977 **   not updated more often than necessary.
480bea2a948Sdanielk1977 **
481bea2a948Sdanielk1977 **   It is set to true when the change-counter field is updated, which
482bea2a948Sdanielk1977 **   can only happen if an exclusive lock is held on the database file.
483bea2a948Sdanielk1977 **   It is cleared (set to false) whenever an exclusive lock is
484bea2a948Sdanielk1977 **   relinquished on the database file. Each time a transaction is committed,
485bea2a948Sdanielk1977 **   The changeCountDone flag is inspected. If it is true, the work of
486bea2a948Sdanielk1977 **   updating the change-counter is omitted for the current transaction.
487bea2a948Sdanielk1977 **
488bea2a948Sdanielk1977 **   This mechanism means that when running in exclusive mode, a connection
489bea2a948Sdanielk1977 **   need only update the change-counter once, for the first transaction
490bea2a948Sdanielk1977 **   committed.
491bea2a948Sdanielk1977 **
492067b92baSdrh ** setSuper
493bea2a948Sdanielk1977 **
4941e01cf1bSdan **   When PagerCommitPhaseOne() is called to commit a transaction, it may
495067b92baSdrh **   (or may not) specify a super-journal name to be written into the
4961e01cf1bSdan **   journal file before it is synced to disk.
497bea2a948Sdanielk1977 **
498067b92baSdrh **   Whether or not a journal file contains a super-journal pointer affects
4991e01cf1bSdan **   the way in which the journal file is finalized after the transaction is
5001e01cf1bSdan **   committed or rolled back when running in "journal_mode=PERSIST" mode.
501067b92baSdrh **   If a journal file does not contain a super-journal pointer, it is
502de1ae34eSdan **   finalized by overwriting the first journal header with zeroes. If
503067b92baSdrh **   it does contain a super-journal pointer the journal file is finalized
504de1ae34eSdan **   by truncating it to zero bytes, just as if the connection were
505de1ae34eSdan **   running in "journal_mode=truncate" mode.
5061e01cf1bSdan **
507067b92baSdrh **   Journal files that contain super-journal pointers cannot be finalized
5081e01cf1bSdan **   simply by overwriting the first journal-header with zeroes, as the
509067b92baSdrh **   super-journal pointer could interfere with hot-journal rollback of any
5101e01cf1bSdan **   subsequently interrupted transaction that reuses the journal file.
5111e01cf1bSdan **
5121e01cf1bSdan **   The flag is cleared as soon as the journal file is finalized (either
5131e01cf1bSdan **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
514067b92baSdrh **   journal file from being successfully finalized, the setSuper flag
515de1ae34eSdan **   is cleared anyway (and the pager will move to ERROR state).
516bea2a948Sdanielk1977 **
51740c3941cSdrh ** doNotSpill
518bea2a948Sdanielk1977 **
51940c3941cSdrh **   This variables control the behavior of cache-spills  (calls made by
52040c3941cSdrh **   the pcache module to the pagerStress() routine to write cached data
52140c3941cSdrh **   to the file-system in order to free up memory).
52285d14ed2Sdan **
52340c3941cSdrh **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
52440c3941cSdrh **   writing to the database from pagerStress() is disabled altogether.
52540c3941cSdrh **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
52685d14ed2Sdan **   comes up during savepoint rollback that requires the pcache module
52785d14ed2Sdan **   to allocate a new page to prevent the journal file from being written
52840c3941cSdrh **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
52940c3941cSdrh **   case is a user preference.
53085d14ed2Sdan **
531e399ac2eSdrh **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
532e399ac2eSdrh **   pagerStress() is permitted, but syncing the journal file is not.
533e399ac2eSdrh **   This flag is set by sqlite3PagerWrite() when the file-system sector-size
534e399ac2eSdrh **   is larger than the database page-size in order to prevent a journal sync
535e399ac2eSdrh **   from happening in between the journalling of two pages on the same sector.
536bea2a948Sdanielk1977 **
537d829335eSdanielk1977 ** subjInMemory
538d829335eSdanielk1977 **
539d829335eSdanielk1977 **   This is a boolean variable. If true, then any required sub-journal
540d829335eSdanielk1977 **   is opened as an in-memory journal file. If false, then in-memory
541d829335eSdanielk1977 **   sub-journals are only used for in-memory pager files.
542de1ae34eSdan **
543de1ae34eSdan **   This variable is updated by the upper layer each time a new
544de1ae34eSdan **   write-transaction is opened.
545de1ae34eSdan **
546de1ae34eSdan ** dbSize, dbOrigSize, dbFileSize
547de1ae34eSdan **
548de1ae34eSdan **   Variable dbSize is set to the number of pages in the database file.
549de1ae34eSdan **   It is valid in PAGER_READER and higher states (all states except for
550de1ae34eSdan **   OPEN and ERROR).
551de1ae34eSdan **
552de1ae34eSdan **   dbSize is set based on the size of the database file, which may be
553de1ae34eSdan **   larger than the size of the database (the value stored at offset
554de1ae34eSdan **   28 of the database header by the btree). If the size of the file
555de1ae34eSdan **   is not an integer multiple of the page-size, the value stored in
556de1ae34eSdan **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
557de1ae34eSdan **   Except, any file that is greater than 0 bytes in size is considered
558de1ae34eSdan **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
559de1ae34eSdan **   to dbSize==1).
560de1ae34eSdan **
561de1ae34eSdan **   During a write-transaction, if pages with page-numbers greater than
562de1ae34eSdan **   dbSize are modified in the cache, dbSize is updated accordingly.
563de1ae34eSdan **   Similarly, if the database is truncated using PagerTruncateImage(),
564de1ae34eSdan **   dbSize is updated.
565de1ae34eSdan **
566de1ae34eSdan **   Variables dbOrigSize and dbFileSize are valid in states
567de1ae34eSdan **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
568de1ae34eSdan **   variable at the start of the transaction. It is used during rollback,
569de1ae34eSdan **   and to determine whether or not pages need to be journalled before
570de1ae34eSdan **   being modified.
571de1ae34eSdan **
572de1ae34eSdan **   Throughout a write-transaction, dbFileSize contains the size of
573de1ae34eSdan **   the file on disk in pages. It is set to a copy of dbSize when the
574de1ae34eSdan **   write-transaction is first opened, and updated when VFS calls are made
575de1ae34eSdan **   to write or truncate the database file on disk.
576de1ae34eSdan **
577c864912aSdan **   The only reason the dbFileSize variable is required is to suppress
578c864912aSdan **   unnecessary calls to xTruncate() after committing a transaction. If,
579c864912aSdan **   when a transaction is committed, the dbFileSize variable indicates
580c864912aSdan **   that the database file is larger than the database image (Pager.dbSize),
581c864912aSdan **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
582c864912aSdan **   to measure the database file on disk, and then truncates it if required.
583c864912aSdan **   dbFileSize is not used when rolling back a transaction. In this case
584c864912aSdan **   pager_truncate() is called unconditionally (which means there may be
585c864912aSdan **   a call to xFilesize() that is not strictly required). In either case,
586c864912aSdan **   pager_truncate() may cause the file to become smaller or larger.
587c864912aSdan **
588c864912aSdan ** dbHintSize
589c864912aSdan **
590c864912aSdan **   The dbHintSize variable is used to limit the number of calls made to
591c864912aSdan **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
592c864912aSdan **
593c864912aSdan **   dbHintSize is set to a copy of the dbSize variable when a
594c864912aSdan **   write-transaction is opened (at the same time as dbFileSize and
595c864912aSdan **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
596c864912aSdan **   dbHintSize is increased to the number of pages that correspond to the
597c864912aSdan **   size-hint passed to the method call. See pager_write_pagelist() for
598c864912aSdan **   details.
599c864912aSdan **
600de1ae34eSdan ** errCode
601de1ae34eSdan **
602de1ae34eSdan **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
603de1ae34eSdan **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
604de1ae34eSdan **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
605de1ae34eSdan **   sub-codes.
606daaae7b9Sdrh **
607daaae7b9Sdrh ** syncFlags, walSyncFlags
608daaae7b9Sdrh **
609daaae7b9Sdrh **   syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
610daaae7b9Sdrh **   syncFlags is used for rollback mode.  walSyncFlags is used for WAL mode
611daaae7b9Sdrh **   and contains the flags used to sync the checkpoint operations in the
612daaae7b9Sdrh **   lower two bits, and sync flags used for transaction commits in the WAL
613daaae7b9Sdrh **   file in bits 0x04 and 0x08.  In other words, to get the correct sync flags
614daaae7b9Sdrh **   for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
615daaae7b9Sdrh **   sync flags for transaction commit, use ((walSyncFlags>>2)&0x03).  Note
616daaae7b9Sdrh **   that with synchronous=NORMAL in WAL mode, transaction commit is not synced
617daaae7b9Sdrh **   meaning that the 0x04 and 0x08 bits are both zero.
618ed7c855cSdrh */
619ed7c855cSdrh struct Pager {
620b4b47411Sdanielk1977   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
621bea2a948Sdanielk1977   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
6224d9c1b7fSdan   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
62334e79ceeSdrh   u8 useJournal;              /* Use a rollback journal on this file */
624603240cfSdrh   u8 noSync;                  /* Do not sync the journal if true */
625968af52aSdrh   u8 fullSync;                /* Do extra syncs of the journal for robustness */
6266841b1cbSdrh   u8 extraSync;               /* sync directory after journal delete */
627c97d8463Sdrh   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
628daaae7b9Sdrh   u8 walSyncFlags;            /* See description above */
62957fe136bSdrh   u8 tempFile;                /* zFilename is a temporary or immutable file */
63057fe136bSdrh   u8 noLock;                  /* Do not lock (except in WAL mode) */
631603240cfSdrh   u8 readOnly;                /* True for a read-only database */
63245d6882fSdanielk1977   u8 memDb;                   /* True to inhibit all file I/O */
633021e228eSdrh   u8 memVfs;                  /* VFS-implemented memory database */
634bea2a948Sdanielk1977 
635e5918c62Sdrh   /**************************************************************************
636e5918c62Sdrh   ** The following block contains those class members that change during
63760ec914cSpeter.d.reid   ** routine operation.  Class members not in this block are either fixed
638e5918c62Sdrh   ** when the pager is first created or else only change when there is a
639e5918c62Sdrh   ** significant mode change (such as changing the page_size, locking_mode,
640e5918c62Sdrh   ** or the journal_mode).  From another view, these class members describe
641e5918c62Sdrh   ** the "state" of the pager, while other class members describe the
642e5918c62Sdrh   ** "configuration" of the pager.
643bea2a948Sdanielk1977   */
644de1ae34eSdan   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
645d0864087Sdan   u8 eLock;                   /* Current lock held on database file */
646bea2a948Sdanielk1977   u8 changeCountDone;         /* Set after incrementing the change-counter */
647067b92baSdrh   u8 setSuper;                /* Super-jrnl name is written into jrnl */
6487cf4c7adSdrh   u8 doNotSpill;              /* Do not spill the cache when non-zero */
649d829335eSdanielk1977   u8 subjInMemory;            /* True to use in-memory sub-journals */
65091618564Sdrh   u8 bUseFetch;               /* True to use xFetch() */
651c98a4cc8Sdrh   u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
6523460d19cSdanielk1977   Pgno dbSize;                /* Number of pages in the database */
6533460d19cSdanielk1977   Pgno dbOrigSize;            /* dbSize before the current transaction */
6543460d19cSdanielk1977   Pgno dbFileSize;            /* Number of pages in the database file */
655c864912aSdan   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
65645d6882fSdanielk1977   int errCode;                /* One of several kinds of errors */
657bea2a948Sdanielk1977   int nRec;                   /* Pages journalled since last j-header written */
65845d6882fSdanielk1977   u32 cksumInit;              /* Quasi-random value added to every checksum */
659bea2a948Sdanielk1977   u32 nSubRec;                /* Number of records written to sub-journal */
66045d6882fSdanielk1977   Bitvec *pInJournal;         /* One bit for each page in the database file */
661bea2a948Sdanielk1977   sqlite3_file *fd;           /* File descriptor for database */
662bea2a948Sdanielk1977   sqlite3_file *jfd;          /* File descriptor for main journal */
663bea2a948Sdanielk1977   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
664bea2a948Sdanielk1977   i64 journalOff;             /* Current write offset in the journal file */
665bea2a948Sdanielk1977   i64 journalHdr;             /* Byte offset to previous journal header */
666e5918c62Sdrh   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
667bea2a948Sdanielk1977   PagerSavepoint *aSavepoint; /* Array of active savepoints */
668bea2a948Sdanielk1977   int nSavepoint;             /* Number of elements in aSavepoint[] */
669d7107b38Sdrh   u32 iDataVersion;           /* Changes whenever database content changes */
670bea2a948Sdanielk1977   char dbFileVers[16];        /* Changes whenever database file changes */
671b2d3de3bSdan 
672b2d3de3bSdan   int nMmapOut;               /* Number of mmap pages currently outstanding */
6739b4c59faSdrh   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
674c86e5135Sdrh   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
675e5918c62Sdrh   /*
676e5918c62Sdrh   ** End of the routinely-changing class members
677e5918c62Sdrh   ***************************************************************************/
678bea2a948Sdanielk1977 
679fa9601a9Sdrh   u16 nExtra;                 /* Add this many bytes to each in-memory page */
680fa9601a9Sdrh   i16 nReserve;               /* Number of unused bytes at end of each page */
681bea2a948Sdanielk1977   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
682e5918c62Sdrh   u32 sectorSize;             /* Assumed sector size during rollback */
683bea2a948Sdanielk1977   Pgno mxPgno;                /* Maximum allowed size of the database */
684584bfcaeSdrh   Pgno lckPgno;               /* Page number for the locking page */
68557dd7e6aSdrh   i64 pageSize;               /* Number of bytes in a page */
686e5918c62Sdrh   i64 journalSizeLimit;       /* Size limit for persistent journal files */
687fcd35c7bSdrh   char *zFilename;            /* Name of the database file */
688fcd35c7bSdrh   char *zJournal;             /* Name of the journal file */
6891ceedd37Sdanielk1977   int (*xBusyHandler)(void*); /* Function to call when busy */
6901ceedd37Sdanielk1977   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
691ffc78a41Sdrh   int aStat[4];               /* Total cache hits, misses, writes, spills */
692fcd35c7bSdrh #ifdef SQLITE_TEST
6939ad3ee40Sdrh   int nRead;                  /* Database pages read */
694fcd35c7bSdrh #endif
695eaa06f69Sdanielk1977   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
69612e6f682Sdrh   int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
6978186df86Sdanielk1977   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
6988c0a791aSdanielk1977   PCache *pPCache;            /* Pointer to page cache object */
6995cf53537Sdan #ifndef SQLITE_OMIT_WAL
7007ed91f23Sdrh   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
7013e875ef3Sdan   char *zWal;                 /* File name for write-ahead log */
7025cf53537Sdan #endif
703d9b0257aSdrh };
704d9b0257aSdrh 
705d9b0257aSdrh /*
7069ad3ee40Sdrh ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
7079ad3ee40Sdrh ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
7089ad3ee40Sdrh ** or CACHE_WRITE to sqlite3_db_status().
7099ad3ee40Sdrh */
7109ad3ee40Sdrh #define PAGER_STAT_HIT   0
7119ad3ee40Sdrh #define PAGER_STAT_MISS  1
7129ad3ee40Sdrh #define PAGER_STAT_WRITE 2
713ffc78a41Sdrh #define PAGER_STAT_SPILL 3
7149ad3ee40Sdrh 
7159ad3ee40Sdrh /*
716538f570cSdrh ** The following global variables hold counters used for
717538f570cSdrh ** testing purposes only.  These variables do not exist in
718538f570cSdrh ** a non-testing build.  These variables are not thread-safe.
719fcd35c7bSdrh */
720fcd35c7bSdrh #ifdef SQLITE_TEST
721538f570cSdrh int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
722538f570cSdrh int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
723538f570cSdrh int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
724538f570cSdrh # define PAGER_INCR(v)  v++
725fcd35c7bSdrh #else
726538f570cSdrh # define PAGER_INCR(v)
727fcd35c7bSdrh #endif
728fcd35c7bSdrh 
729538f570cSdrh 
730538f570cSdrh 
731fcd35c7bSdrh /*
7325e00f6c7Sdrh ** Journal files begin with the following magic string.  The data
7335e00f6c7Sdrh ** was obtained from /dev/random.  It is used only as a sanity check.
73494f3331aSdrh **
735ae2b40c4Sdrh ** Since version 2.8.0, the journal format contains additional sanity
73630d53701Sdrh ** checking information.  If the power fails while the journal is being
737ae2b40c4Sdrh ** written, semi-random garbage data might appear in the journal
738ae2b40c4Sdrh ** file after power is restored.  If an attempt is then made
739968af52aSdrh ** to roll the journal back, the database could be corrupted.  The additional
740968af52aSdrh ** sanity checking data is an attempt to discover the garbage in the
741968af52aSdrh ** journal and ignore it.
742968af52aSdrh **
743ae2b40c4Sdrh ** The sanity checking information for the new journal format consists
744968af52aSdrh ** of a 32-bit checksum on each page of data.  The checksum covers both
74590f5ecb3Sdrh ** the page number and the pPager->pageSize bytes of data for the page.
746968af52aSdrh ** This cksum is initialized to a 32-bit random value that appears in the
747968af52aSdrh ** journal file right after the header.  The random initializer is important,
748968af52aSdrh ** because garbage data that appears at the end of a journal is likely
749968af52aSdrh ** data that was once in other files that have now been deleted.  If the
750968af52aSdrh ** garbage data came from an obsolete journal file, the checksums might
751968af52aSdrh ** be correct.  But by initializing the checksum to random value which
752968af52aSdrh ** is different for every journal, we minimize that risk.
753d9b0257aSdrh */
754ae2b40c4Sdrh static const unsigned char aJournalMagic[] = {
755ae2b40c4Sdrh   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
756ed7c855cSdrh };
757ed7c855cSdrh 
758ed7c855cSdrh /*
759bea2a948Sdanielk1977 ** The size of the of each page record in the journal is given by
760bea2a948Sdanielk1977 ** the following macro.
761968af52aSdrh */
762ae2b40c4Sdrh #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
763968af52aSdrh 
7647657240aSdanielk1977 /*
765bea2a948Sdanielk1977 ** The journal header size for this pager. This is usually the same
766bea2a948Sdanielk1977 ** size as a single disk sector. See also setSectorSize().
7677657240aSdanielk1977 */
7687657240aSdanielk1977 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
7697657240aSdanielk1977 
770b7f9164eSdrh /*
771b7f9164eSdrh ** The macro MEMDB is true if we are dealing with an in-memory database.
772b7f9164eSdrh ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
773b7f9164eSdrh ** the value of MEMDB will be a constant and the compiler will optimize
774b7f9164eSdrh ** out code that would never execute.
775b7f9164eSdrh */
776b7f9164eSdrh #ifdef SQLITE_OMIT_MEMORYDB
777b7f9164eSdrh # define MEMDB 0
778b7f9164eSdrh #else
779b7f9164eSdrh # define MEMDB pPager->memDb
780b7f9164eSdrh #endif
781b7f9164eSdrh 
782b7f9164eSdrh /*
783188d4884Sdrh ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
784188d4884Sdrh ** interfaces to access the database using memory-mapped I/O.
785188d4884Sdrh */
7869b4c59faSdrh #if SQLITE_MAX_MMAP_SIZE>0
787188d4884Sdrh # define USEFETCH(x) ((x)->bUseFetch)
7889b4c59faSdrh #else
7899b4c59faSdrh # define USEFETCH(x) 0
790188d4884Sdrh #endif
791188d4884Sdrh 
792188d4884Sdrh /*
793d0864087Sdan ** The argument to this macro is a file descriptor (type sqlite3_file*).
794d0864087Sdan ** Return 0 if it is not open, or non-zero (but not 1) if it is.
795d0864087Sdan **
796d0864087Sdan ** This is so that expressions can be written as:
797d0864087Sdan **
798d0864087Sdan **   if( isOpen(pPager->jfd) ){ ...
799d0864087Sdan **
800d0864087Sdan ** instead of
801d0864087Sdan **
802d0864087Sdan **   if( pPager->jfd->pMethods ){ ...
803d0864087Sdan */
80482ef8775Sdrh #define isOpen(pFd) ((pFd)->pMethods!=0)
805d0864087Sdan 
80609236755Sdan #ifdef SQLITE_DIRECT_OVERFLOW_READ
80709236755Sdan /*
80809236755Sdan ** Return true if page pgno can be read directly from the database file
80909236755Sdan ** by the b-tree layer. This is the case if:
81009236755Sdan **
81109236755Sdan **   * the database file is open,
81209236755Sdan **   * there are no dirty pages in the cache, and
81309236755Sdan **   * the desired page is not currently in the wal file.
81409236755Sdan */
sqlite3PagerDirectReadOk(Pager * pPager,Pgno pgno)81509236755Sdan int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
81609236755Sdan   if( pPager->fd->pMethods==0 ) return 0;
81709236755Sdan   if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
81809236755Sdan #ifndef SQLITE_OMIT_WAL
81909236755Sdan   if( pPager->pWal ){
82009236755Sdan     u32 iRead = 0;
82109236755Sdan     int rc;
82209236755Sdan     rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
82309236755Sdan     return (rc==SQLITE_OK && iRead==0);
82409236755Sdan   }
82509236755Sdan #endif
82609236755Sdan   return 1;
82709236755Sdan }
82809236755Sdan #endif
82909236755Sdan 
830d930b5cbSdrh #ifndef SQLITE_OMIT_WAL
831d930b5cbSdrh # define pagerUseWal(x) ((x)->pWal!=0)
832d0864087Sdan #else
833d0864087Sdan # define pagerUseWal(x) 0
834d0864087Sdan # define pagerRollbackWal(x) 0
8354eb02a45Sdrh # define pagerWalFrames(v,w,x,y) 0
836d0864087Sdan # define pagerOpenWalIfPresent(z) SQLITE_OK
837d0864087Sdan # define pagerBeginReadTransaction(z) SQLITE_OK
838d0864087Sdan #endif
839d0864087Sdan 
840bea2a948Sdanielk1977 #ifndef NDEBUG
841bea2a948Sdanielk1977 /*
842bea2a948Sdanielk1977 ** Usage:
843bea2a948Sdanielk1977 **
844bea2a948Sdanielk1977 **   assert( assert_pager_state(pPager) );
845de1ae34eSdan **
846de1ae34eSdan ** This function runs many asserts to try to find inconsistencies in
847de1ae34eSdan ** the internal state of the Pager object.
848bea2a948Sdanielk1977 */
assert_pager_state(Pager * p)849d0864087Sdan static int assert_pager_state(Pager *p){
850d0864087Sdan   Pager *pPager = p;
851bea2a948Sdanielk1977 
852d0864087Sdan   /* State must be valid. */
853de1ae34eSdan   assert( p->eState==PAGER_OPEN
854d0864087Sdan        || p->eState==PAGER_READER
855de1ae34eSdan        || p->eState==PAGER_WRITER_LOCKED
856d0864087Sdan        || p->eState==PAGER_WRITER_CACHEMOD
857d0864087Sdan        || p->eState==PAGER_WRITER_DBMOD
858d0864087Sdan        || p->eState==PAGER_WRITER_FINISHED
859a42c66bdSdan        || p->eState==PAGER_ERROR
860d0864087Sdan   );
861bea2a948Sdanielk1977 
862d0864087Sdan   /* Regardless of the current state, a temp-file connection always behaves
863d0864087Sdan   ** as if it has an exclusive lock on the database file. It never updates
864d0864087Sdan   ** the change-counter field, so the changeCountDone flag is always set.
865d0864087Sdan   */
866d0864087Sdan   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
867d0864087Sdan   assert( p->tempFile==0 || pPager->changeCountDone );
868d0864087Sdan 
869d0864087Sdan   /* If the useJournal flag is clear, the journal-mode must be "OFF".
870d0864087Sdan   ** And if the journal-mode is "OFF", the journal file must not be open.
871d0864087Sdan   */
872d0864087Sdan   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
873d0864087Sdan   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
874d0864087Sdan 
87522b328b2Sdan   /* Check that MEMDB implies noSync. And an in-memory journal. Since
87622b328b2Sdan   ** this means an in-memory pager performs no IO at all, it cannot encounter
87722b328b2Sdan   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
87822b328b2Sdan   ** a journal file. (although the in-memory journal implementation may
87922b328b2Sdan   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
88022b328b2Sdan   ** is therefore not possible for an in-memory pager to enter the ERROR
88122b328b2Sdan   ** state.
88222b328b2Sdan   */
88322b328b2Sdan   if( MEMDB ){
884835f22deSdrh     assert( !isOpen(p->fd) );
88522b328b2Sdan     assert( p->noSync );
88622b328b2Sdan     assert( p->journalMode==PAGER_JOURNALMODE_OFF
88722b328b2Sdan          || p->journalMode==PAGER_JOURNALMODE_MEMORY
88822b328b2Sdan     );
88922b328b2Sdan     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
89022b328b2Sdan     assert( pagerUseWal(p)==0 );
89122b328b2Sdan   }
892d0864087Sdan 
893431b0b42Sdan   /* If changeCountDone is set, a RESERVED lock or greater must be held
894431b0b42Sdan   ** on the file.
895431b0b42Sdan   */
896431b0b42Sdan   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
89754919f82Sdan   assert( p->eLock!=PENDING_LOCK );
898431b0b42Sdan 
899d0864087Sdan   switch( p->eState ){
900de1ae34eSdan     case PAGER_OPEN:
901d0864087Sdan       assert( !MEMDB );
902a42c66bdSdan       assert( pPager->errCode==SQLITE_OK );
9034e004aa6Sdan       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
904d0864087Sdan       break;
905d0864087Sdan 
906d0864087Sdan     case PAGER_READER:
907a42c66bdSdan       assert( pPager->errCode==SQLITE_OK );
9084e004aa6Sdan       assert( p->eLock!=UNKNOWN_LOCK );
90933f111dcSdrh       assert( p->eLock>=SHARED_LOCK );
910d0864087Sdan       break;
911d0864087Sdan 
912de1ae34eSdan     case PAGER_WRITER_LOCKED:
9134e004aa6Sdan       assert( p->eLock!=UNKNOWN_LOCK );
914a42c66bdSdan       assert( pPager->errCode==SQLITE_OK );
915d0864087Sdan       if( !pagerUseWal(pPager) ){
916d0864087Sdan         assert( p->eLock>=RESERVED_LOCK );
917d0864087Sdan       }
918937ac9daSdan       assert( pPager->dbSize==pPager->dbOrigSize );
919937ac9daSdan       assert( pPager->dbOrigSize==pPager->dbFileSize );
920c864912aSdan       assert( pPager->dbOrigSize==pPager->dbHintSize );
921067b92baSdrh       assert( pPager->setSuper==0 );
922d0864087Sdan       break;
923d0864087Sdan 
924d0864087Sdan     case PAGER_WRITER_CACHEMOD:
9254e004aa6Sdan       assert( p->eLock!=UNKNOWN_LOCK );
926a42c66bdSdan       assert( pPager->errCode==SQLITE_OK );
927d0864087Sdan       if( !pagerUseWal(pPager) ){
928d0864087Sdan         /* It is possible that if journal_mode=wal here that neither the
929d0864087Sdan         ** journal file nor the WAL file are open. This happens during
930d0864087Sdan         ** a rollback transaction that switches from journal_mode=off
931d0864087Sdan         ** to journal_mode=wal.
932d0864087Sdan         */
933d0864087Sdan         assert( p->eLock>=RESERVED_LOCK );
934d0864087Sdan         assert( isOpen(p->jfd)
935d0864087Sdan              || p->journalMode==PAGER_JOURNALMODE_OFF
936d0864087Sdan              || p->journalMode==PAGER_JOURNALMODE_WAL
937d0864087Sdan         );
938d0864087Sdan       }
939937ac9daSdan       assert( pPager->dbOrigSize==pPager->dbFileSize );
940c864912aSdan       assert( pPager->dbOrigSize==pPager->dbHintSize );
941d0864087Sdan       break;
942d0864087Sdan 
943d0864087Sdan     case PAGER_WRITER_DBMOD:
9444e004aa6Sdan       assert( p->eLock==EXCLUSIVE_LOCK );
945a42c66bdSdan       assert( pPager->errCode==SQLITE_OK );
946d0864087Sdan       assert( !pagerUseWal(pPager) );
9474e004aa6Sdan       assert( p->eLock>=EXCLUSIVE_LOCK );
948d0864087Sdan       assert( isOpen(p->jfd)
949d0864087Sdan            || p->journalMode==PAGER_JOURNALMODE_OFF
950d0864087Sdan            || p->journalMode==PAGER_JOURNALMODE_WAL
951d67a9770Sdan            || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
952d0864087Sdan       );
953c864912aSdan       assert( pPager->dbOrigSize<=pPager->dbHintSize );
954d0864087Sdan       break;
955d0864087Sdan 
956d0864087Sdan     case PAGER_WRITER_FINISHED:
9574e004aa6Sdan       assert( p->eLock==EXCLUSIVE_LOCK );
958a42c66bdSdan       assert( pPager->errCode==SQLITE_OK );
959d0864087Sdan       assert( !pagerUseWal(pPager) );
960d0864087Sdan       assert( isOpen(p->jfd)
961d0864087Sdan            || p->journalMode==PAGER_JOURNALMODE_OFF
962d0864087Sdan            || p->journalMode==PAGER_JOURNALMODE_WAL
963efe16971Sdan            || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
964d0864087Sdan       );
965d0864087Sdan       break;
966a42c66bdSdan 
967a42c66bdSdan     case PAGER_ERROR:
968a42c66bdSdan       /* There must be at least one outstanding reference to the pager if
969a42c66bdSdan       ** in ERROR state. Otherwise the pager should have already dropped
970de1ae34eSdan       ** back to OPEN state.
971a42c66bdSdan       */
972a42c66bdSdan       assert( pPager->errCode!=SQLITE_OK );
97367330a12Sdan       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
974a42c66bdSdan       break;
975d0864087Sdan   }
976bea2a948Sdanielk1977 
977bea2a948Sdanielk1977   return 1;
978bea2a948Sdanielk1977 }
9796a88adcdSdan #endif /* ifndef NDEBUG */
980d0864087Sdan 
9816a88adcdSdan #ifdef SQLITE_DEBUG
982d0864087Sdan /*
983de1ae34eSdan ** Return a pointer to a human readable string in a static buffer
984de1ae34eSdan ** containing the state of the Pager object passed as an argument. This
985de1ae34eSdan ** is intended to be used within debuggers. For example, as an alternative
986de1ae34eSdan ** to "print *pPager" in gdb:
987de1ae34eSdan **
988d0864087Sdan ** (gdb) printf "%s", print_pager_state(pPager)
989ed927215Sdrh **
990ed927215Sdrh ** This routine has external linkage in order to suppress compiler warnings
991ed927215Sdrh ** about an unused function.  It is enclosed within SQLITE_DEBUG and so does
992ed927215Sdrh ** not appear in normal builds.
993d0864087Sdan */
print_pager_state(Pager * p)994ed927215Sdrh char *print_pager_state(Pager *p){
995d0864087Sdan   static char zRet[1024];
996d0864087Sdan 
997d0864087Sdan   sqlite3_snprintf(1024, zRet,
99811f47a9bSdan       "Filename:      %s\n"
9994e004aa6Sdan       "State:         %s errCode=%d\n"
1000d0864087Sdan       "Lock:          %s\n"
1001d0864087Sdan       "Locking mode:  locking_mode=%s\n"
1002937ac9daSdan       "Journal mode:  journal_mode=%s\n"
1003937ac9daSdan       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
10044e004aa6Sdan       "Journal:       journalOff=%lld journalHdr=%lld\n"
100573d66fdbSdan       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
100611f47a9bSdan       , p->zFilename
1007de1ae34eSdan       , p->eState==PAGER_OPEN            ? "OPEN" :
1008d0864087Sdan         p->eState==PAGER_READER          ? "READER" :
1009de1ae34eSdan         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
1010d0864087Sdan         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
1011d0864087Sdan         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
1012a42c66bdSdan         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
1013a42c66bdSdan         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
10144e004aa6Sdan       , (int)p->errCode
10155198beadSdan       , p->eLock==NO_LOCK         ? "NO_LOCK" :
1016d0864087Sdan         p->eLock==RESERVED_LOCK   ? "RESERVED" :
1017d0864087Sdan         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
10184e004aa6Sdan         p->eLock==SHARED_LOCK     ? "SHARED" :
10194e004aa6Sdan         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
1020d0864087Sdan       , p->exclusiveMode ? "exclusive" : "normal"
1021937ac9daSdan       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
1022937ac9daSdan         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
1023937ac9daSdan         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
1024937ac9daSdan         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
1025937ac9daSdan         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
1026937ac9daSdan         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
1027937ac9daSdan       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
10284e004aa6Sdan       , p->journalOff, p->journalHdr
102973d66fdbSdan       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
1030d0864087Sdan   );
1031d0864087Sdan 
1032d0864087Sdan   return zRet;
1033d0864087Sdan }
1034bea2a948Sdanielk1977 #endif
1035bea2a948Sdanielk1977 
103612e6f682Sdrh /* Forward references to the various page getters */
103712e6f682Sdrh static int getPageNormal(Pager*,Pgno,DbPage**,int);
103812e6f682Sdrh static int getPageError(Pager*,Pgno,DbPage**,int);
1039d5df3ff2Sdrh #if SQLITE_MAX_MMAP_SIZE>0
1040d5df3ff2Sdrh static int getPageMMap(Pager*,Pgno,DbPage**,int);
1041d5df3ff2Sdrh #endif
104212e6f682Sdrh 
104312e6f682Sdrh /*
104412e6f682Sdrh ** Set the Pager.xGet method for the appropriate routine used to fetch
104512e6f682Sdrh ** content from the pager.
104612e6f682Sdrh */
setGetterMethod(Pager * pPager)104712e6f682Sdrh static void setGetterMethod(Pager *pPager){
104812e6f682Sdrh   if( pPager->errCode ){
104912e6f682Sdrh     pPager->xGet = getPageError;
1050d5df3ff2Sdrh #if SQLITE_MAX_MMAP_SIZE>0
1051b48c0d59Sdrh   }else if( USEFETCH(pPager) ){
105212e6f682Sdrh     pPager->xGet = getPageMMap;
1053d5df3ff2Sdrh #endif /* SQLITE_MAX_MMAP_SIZE>0 */
105412e6f682Sdrh   }else{
105512e6f682Sdrh     pPager->xGet = getPageNormal;
105612e6f682Sdrh   }
105712e6f682Sdrh }
105812e6f682Sdrh 
105926836654Sdanielk1977 /*
10603460d19cSdanielk1977 ** Return true if it is necessary to write page *pPg into the sub-journal.
10613460d19cSdanielk1977 ** A page needs to be written into the sub-journal if there exists one
10623460d19cSdanielk1977 ** or more open savepoints for which:
1063fd7f0452Sdanielk1977 **
10643460d19cSdanielk1977 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
10653460d19cSdanielk1977 **   * The bit corresponding to the page-number is not set in
10663460d19cSdanielk1977 **     PagerSavepoint.pInSavepoint.
1067f35843b5Sdanielk1977 */
subjRequiresPage(PgHdr * pPg)10683460d19cSdanielk1977 static int subjRequiresPage(PgHdr *pPg){
1069f35843b5Sdanielk1977   Pager *pPager = pPg->pPager;
10709d1ab079Sdrh   PagerSavepoint *p;
107116f9a811Sdrh   Pgno pgno = pPg->pgno;
10723460d19cSdanielk1977   int i;
10733460d19cSdanielk1977   for(i=0; i<pPager->nSavepoint; i++){
10749d1ab079Sdrh     p = &pPager->aSavepoint[i];
107582ef8775Sdrh     if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
1076f43fef29Sdan       for(i=i+1; i<pPager->nSavepoint; i++){
1077f43fef29Sdan         pPager->aSavepoint[i].bTruncateOnRelease = 0;
1078f43fef29Sdan       }
1079fd7f0452Sdanielk1977       return 1;
1080fd7f0452Sdanielk1977     }
10813460d19cSdanielk1977   }
10823460d19cSdanielk1977   return 0;
1083f35843b5Sdanielk1977 }
10848ca0c724Sdrh 
108582ef8775Sdrh #ifdef SQLITE_DEBUG
10863460d19cSdanielk1977 /*
10873460d19cSdanielk1977 ** Return true if the page is already in the journal file.
10883460d19cSdanielk1977 */
pageInJournal(Pager * pPager,PgHdr * pPg)10895dee6afcSdrh static int pageInJournal(Pager *pPager, PgHdr *pPg){
10905dee6afcSdrh   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
1091bc2ca9ebSdanielk1977 }
109282ef8775Sdrh #endif
1093bc2ca9ebSdanielk1977 
10948ca0c724Sdrh /*
109534e79ceeSdrh ** Read a 32-bit integer from the given file descriptor.  Store the integer
109634e79ceeSdrh ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
109734e79ceeSdrh ** error code is something goes wrong.
1098726de599Sdrh **
1099726de599Sdrh ** All values are stored on disk as big-endian.
110094f3331aSdrh */
read32bits(sqlite3_file * fd,i64 offset,u32 * pRes)110162079060Sdanielk1977 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
110294f3331aSdrh   unsigned char ac[4];
110362079060Sdanielk1977   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
11043b59a5ccSdrh   if( rc==SQLITE_OK ){
1105a3152895Sdrh     *pRes = sqlite3Get4byte(ac);
110694f3331aSdrh   }
110794f3331aSdrh   return rc;
110894f3331aSdrh }
110994f3331aSdrh 
111094f3331aSdrh /*
111197b57484Sdrh ** Write a 32-bit integer into a string buffer in big-endian byte order.
111297b57484Sdrh */
1113a3152895Sdrh #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
111497b57484Sdrh 
1115d0864087Sdan 
111697b57484Sdrh /*
111734e79ceeSdrh ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
111834e79ceeSdrh ** on success or an error code is something goes wrong.
111994f3331aSdrh */
write32bits(sqlite3_file * fd,i64 offset,u32 val)112062079060Sdanielk1977 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
1121bab45c64Sdanielk1977   char ac[4];
112297b57484Sdrh   put32bits(ac, val);
112362079060Sdanielk1977   return sqlite3OsWrite(fd, ac, 4, offset);
112494f3331aSdrh }
112594f3331aSdrh 
11262554f8b0Sdrh /*
112754919f82Sdan ** Unlock the database file to level eLock, which must be either NO_LOCK
112854919f82Sdan ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
112954919f82Sdan ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
113054919f82Sdan **
113154919f82Sdan ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
113254919f82Sdan ** called, do not modify it. See the comment above the #define of
113354919f82Sdan ** UNKNOWN_LOCK for an explanation of this.
11347a2b1eebSdanielk1977 */
pagerUnlockDb(Pager * pPager,int eLock)11354e004aa6Sdan static int pagerUnlockDb(Pager *pPager, int eLock){
1136431b0b42Sdan   int rc = SQLITE_OK;
113754919f82Sdan 
11388c408004Sdan   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
113954919f82Sdan   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
114054919f82Sdan   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
114157fe136bSdrh   if( isOpen(pPager->fd) ){
1142d0864087Sdan     assert( pPager->eLock>=eLock );
114357fe136bSdrh     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
11444e004aa6Sdan     if( pPager->eLock!=UNKNOWN_LOCK ){
11451df2db7fSshaneh       pPager->eLock = (u8)eLock;
1146431b0b42Sdan     }
11474e004aa6Sdan     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
1148431b0b42Sdan   }
1149fce8165eSdrh   pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
1150431b0b42Sdan   return rc;
1151431b0b42Sdan }
1152431b0b42Sdan 
115354919f82Sdan /*
115454919f82Sdan ** Lock the database file to level eLock, which must be either SHARED_LOCK,
115554919f82Sdan ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
115654919f82Sdan ** Pager.eLock variable to the new locking state.
115754919f82Sdan **
115854919f82Sdan ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
115954919f82Sdan ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
116054919f82Sdan ** See the comment above the #define of UNKNOWN_LOCK for an explanation
116154919f82Sdan ** of this.
116254919f82Sdan */
pagerLockDb(Pager * pPager,int eLock)11634e004aa6Sdan static int pagerLockDb(Pager *pPager, int eLock){
116454919f82Sdan   int rc = SQLITE_OK;
116554919f82Sdan 
1166431b0b42Sdan   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
116754919f82Sdan   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
116857fe136bSdrh     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
11694e004aa6Sdan     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
11701df2db7fSshaneh       pPager->eLock = (u8)eLock;
11714e004aa6Sdan       IOTRACE(("LOCK %p %d\n", pPager, eLock))
1172431b0b42Sdan     }
1173431b0b42Sdan   }
1174431b0b42Sdan   return rc;
11757a2b1eebSdanielk1977 }
11767a2b1eebSdanielk1977 
11777a2b1eebSdanielk1977 /*
1178d67a9770Sdan ** This function determines whether or not the atomic-write or
1179d67a9770Sdan ** atomic-batch-write optimizations can be used with this pager. The
1180d67a9770Sdan ** atomic-write optimization can be used if:
1181c7b6017cSdanielk1977 **
1182c7b6017cSdanielk1977 **  (a) the value returned by OsDeviceCharacteristics() indicates that
1183c7b6017cSdanielk1977 **      a database page may be written atomically, and
1184c7b6017cSdanielk1977 **  (b) the value returned by OsSectorSize() is less than or equal
1185c7b6017cSdanielk1977 **      to the page size.
1186c7b6017cSdanielk1977 **
1187d67a9770Sdan ** If it can be used, then the value returned is the size of the journal
1188d67a9770Sdan ** file when it contains rollback data for exactly one page.
1189bea2a948Sdanielk1977 **
1190d67a9770Sdan ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
1191d67a9770Sdan ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
1192d67a9770Sdan ** returned in this case.
1193d67a9770Sdan **
1194d67a9770Sdan ** If neither optimization can be used, 0 is returned.
1195c7b6017cSdanielk1977 */
jrnlBufferSize(Pager * pPager)1196c7b6017cSdanielk1977 static int jrnlBufferSize(Pager *pPager){
1197bea2a948Sdanielk1977   assert( !MEMDB );
1198d67a9770Sdan 
1199d67a9770Sdan #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
1200d67a9770Sdan  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
1201c7b6017cSdanielk1977   int dc;                           /* Device characteristics */
1202c7b6017cSdanielk1977 
1203bea2a948Sdanielk1977   assert( isOpen(pPager->fd) );
1204bea2a948Sdanielk1977   dc = sqlite3OsDeviceCharacteristics(pPager->fd);
12056235ee57Sdrh #else
12066235ee57Sdrh   UNUSED_PARAMETER(pPager);
1207d67a9770Sdan #endif
1208d67a9770Sdan 
1209d67a9770Sdan #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
1210b8fff29cSdan   if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
1211efe16971Sdan     return -1;
1212efe16971Sdan   }
1213d67a9770Sdan #endif
1214efe16971Sdan 
1215d67a9770Sdan #ifdef SQLITE_ENABLE_ATOMIC_WRITE
1216d67a9770Sdan   {
1217d67a9770Sdan     int nSector = pPager->sectorSize;
1218d67a9770Sdan     int szPage = pPager->pageSize;
1219c7b6017cSdanielk1977 
1220c7b6017cSdanielk1977     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
1221c7b6017cSdanielk1977     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
1222bea2a948Sdanielk1977     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
122345d6882fSdanielk1977       return 0;
122445d6882fSdanielk1977     }
1225bea2a948Sdanielk1977   }
1226c7b6017cSdanielk1977 
1227bea2a948Sdanielk1977   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
1228bea2a948Sdanielk1977 #endif
1229aef0bf64Sdanielk1977 
1230d67a9770Sdan   return 0;
1231d67a9770Sdan }
1232d67a9770Sdan 
1233477731b5Sdrh /*
1234477731b5Sdrh ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
1235477731b5Sdrh ** on the cache using a hash function.  This is used for testing
1236477731b5Sdrh ** and debugging only.
1237477731b5Sdrh */
12383c407374Sdanielk1977 #ifdef SQLITE_CHECK_PAGES
12393c407374Sdanielk1977 /*
12403c407374Sdanielk1977 ** Return a 32-bit hash of the page data for pPage.
12413c407374Sdanielk1977 */
pager_datahash(int nByte,unsigned char * pData)1242477731b5Sdrh static u32 pager_datahash(int nByte, unsigned char *pData){
12433c407374Sdanielk1977   u32 hash = 0;
12443c407374Sdanielk1977   int i;
1245477731b5Sdrh   for(i=0; i<nByte; i++){
1246477731b5Sdrh     hash = (hash*1039) + pData[i];
12473c407374Sdanielk1977   }
12483c407374Sdanielk1977   return hash;
12493c407374Sdanielk1977 }
pager_pagehash(PgHdr * pPage)1250477731b5Sdrh static u32 pager_pagehash(PgHdr *pPage){
12518c0a791aSdanielk1977   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
12528c0a791aSdanielk1977 }
pager_set_pagehash(PgHdr * pPage)1253bc2ca9ebSdanielk1977 static void pager_set_pagehash(PgHdr *pPage){
12548c0a791aSdanielk1977   pPage->pageHash = pager_pagehash(pPage);
1255477731b5Sdrh }
12563c407374Sdanielk1977 
12573c407374Sdanielk1977 /*
12583c407374Sdanielk1977 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
12593c407374Sdanielk1977 ** is defined, and NDEBUG is not defined, an assert() statement checks
12603c407374Sdanielk1977 ** that the page is either dirty or still matches the calculated page-hash.
12613c407374Sdanielk1977 */
12623c407374Sdanielk1977 #define CHECK_PAGE(x) checkPage(x)
checkPage(PgHdr * pPg)12633c407374Sdanielk1977 static void checkPage(PgHdr *pPg){
12643c407374Sdanielk1977   Pager *pPager = pPg->pPager;
12655f848c3aSdan   assert( pPager->eState!=PAGER_ERROR );
12665f848c3aSdan   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
12673c407374Sdanielk1977 }
12683c407374Sdanielk1977 
12693c407374Sdanielk1977 #else
12708ffa8173Sdrh #define pager_datahash(X,Y)  0
1271477731b5Sdrh #define pager_pagehash(X)  0
12725f848c3aSdan #define pager_set_pagehash(X)
12733c407374Sdanielk1977 #define CHECK_PAGE(x)
127441d3027cSdrh #endif  /* SQLITE_CHECK_PAGES */
12753c407374Sdanielk1977 
1276ed7c855cSdrh /*
12777657240aSdanielk1977 ** When this is called the journal file for pager pPager must be open.
1278067b92baSdrh ** This function attempts to read a super-journal file name from the
1279bea2a948Sdanielk1977 ** end of the file and, if successful, copies it into memory supplied
1280067b92baSdrh ** by the caller. See comments above writeSuperJournal() for the format
1281067b92baSdrh ** used to store a super-journal file name at the end of a journal file.
12827657240aSdanielk1977 **
1283067b92baSdrh ** zSuper must point to a buffer of at least nSuper bytes allocated by
128465839c6aSdanielk1977 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
1285067b92baSdrh ** enough space to write the super-journal name). If the super-journal
1286067b92baSdrh ** name in the journal is longer than nSuper bytes (including a
1287067b92baSdrh ** nul-terminator), then this is handled as if no super-journal name
128865839c6aSdanielk1977 ** were present in the journal.
128965839c6aSdanielk1977 **
1290067b92baSdrh ** If a super-journal file name is present at the end of the journal
1291067b92baSdrh ** file, then it is copied into the buffer pointed to by zSuper. A
1292067b92baSdrh ** nul-terminator byte is appended to the buffer following the
1293067b92baSdrh ** super-journal file name.
1294bea2a948Sdanielk1977 **
1295067b92baSdrh ** If it is determined that no super-journal file name is present
1296067b92baSdrh ** zSuper[0] is set to 0 and SQLITE_OK returned.
1297bea2a948Sdanielk1977 **
1298bea2a948Sdanielk1977 ** If an error occurs while reading from the journal file, an SQLite
1299bea2a948Sdanielk1977 ** error code is returned.
13007657240aSdanielk1977 */
readSuperJournal(sqlite3_file * pJrnl,char * zSuper,u32 nSuper)1301067b92baSdrh static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){
1302bea2a948Sdanielk1977   int rc;                    /* Return code */
1303067b92baSdrh   u32 len;                   /* Length in bytes of super-journal name */
1304bea2a948Sdanielk1977   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
1305bea2a948Sdanielk1977   u32 cksum;                 /* MJ checksum value read from journal */
13060b8d2766Sshane   u32 u;                     /* Unsigned loop counter */
13077657240aSdanielk1977   unsigned char aMagic[8];   /* A buffer to hold the magic header */
1308067b92baSdrh   zSuper[0] = '\0';
13097657240aSdanielk1977 
1310bea2a948Sdanielk1977   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
1311bea2a948Sdanielk1977    || szJ<16
1312bea2a948Sdanielk1977    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
1313067b92baSdrh    || len>=nSuper
131405f1ba0eSdrh    || len>szJ-16
1315999cd08aSdan    || len==0
1316bea2a948Sdanielk1977    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
1317bea2a948Sdanielk1977    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
1318bea2a948Sdanielk1977    || memcmp(aMagic, aJournalMagic, 8)
1319067b92baSdrh    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
1320bea2a948Sdanielk1977   ){
13217657240aSdanielk1977     return rc;
13227657240aSdanielk1977   }
13237657240aSdanielk1977 
1324067b92baSdrh   /* See if the checksum matches the super-journal name */
13250b8d2766Sshane   for(u=0; u<len; u++){
1326067b92baSdrh     cksum -= zSuper[u];
1327cafadbacSdanielk1977   }
13288191bff0Sdanielk1977   if( cksum ){
13298191bff0Sdanielk1977     /* If the checksum doesn't add up, then one or more of the disk sectors
1330067b92baSdrh     ** containing the super-journal filename is corrupted. This means
13318191bff0Sdanielk1977     ** definitely roll back, so just return SQLITE_OK and report a (nul)
1332067b92baSdrh     ** super-journal filename.
13338191bff0Sdanielk1977     */
1334bea2a948Sdanielk1977     len = 0;
1335aca790acSdanielk1977   }
1336067b92baSdrh   zSuper[len] = '\0';
1337067b92baSdrh   zSuper[len+1] = '\0';
1338cafadbacSdanielk1977 
13397657240aSdanielk1977   return SQLITE_OK;
13407657240aSdanielk1977 }
13417657240aSdanielk1977 
13427657240aSdanielk1977 /*
1343bea2a948Sdanielk1977 ** Return the offset of the sector boundary at or immediately
1344bea2a948Sdanielk1977 ** following the value in pPager->journalOff, assuming a sector
1345bea2a948Sdanielk1977 ** size of pPager->sectorSize bytes.
13467657240aSdanielk1977 **
13477657240aSdanielk1977 ** i.e for a sector size of 512:
13487657240aSdanielk1977 **
1349bea2a948Sdanielk1977 **   Pager.journalOff          Return value
13507657240aSdanielk1977 **   ---------------------------------------
13517657240aSdanielk1977 **   0                         0
13527657240aSdanielk1977 **   512                       512
13537657240aSdanielk1977 **   100                       512
13547657240aSdanielk1977 **   2000                      2048
13557657240aSdanielk1977 **
13567657240aSdanielk1977 */
journalHdrOffset(Pager * pPager)1357112f752bSdanielk1977 static i64 journalHdrOffset(Pager *pPager){
1358eb206256Sdrh   i64 offset = 0;
1359eb206256Sdrh   i64 c = pPager->journalOff;
13607657240aSdanielk1977   if( c ){
13617657240aSdanielk1977     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
13627657240aSdanielk1977   }
13637657240aSdanielk1977   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
13647657240aSdanielk1977   assert( offset>=c );
13657657240aSdanielk1977   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
1366112f752bSdanielk1977   return offset;
1367112f752bSdanielk1977 }
13687657240aSdanielk1977 
13697657240aSdanielk1977 /*
1370bea2a948Sdanielk1977 ** The journal file must be open when this function is called.
1371bea2a948Sdanielk1977 **
1372bea2a948Sdanielk1977 ** This function is a no-op if the journal file has not been written to
1373bea2a948Sdanielk1977 ** within the current transaction (i.e. if Pager.journalOff==0).
1374bea2a948Sdanielk1977 **
1375bea2a948Sdanielk1977 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
1376bea2a948Sdanielk1977 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
1377bea2a948Sdanielk1977 ** zero the 28-byte header at the start of the journal file. In either case,
1378bea2a948Sdanielk1977 ** if the pager is not in no-sync mode, sync the journal file immediately
1379bea2a948Sdanielk1977 ** after writing or truncating it.
1380bea2a948Sdanielk1977 **
1381bea2a948Sdanielk1977 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
1382bea2a948Sdanielk1977 ** following the truncation or zeroing described above the size of the
1383bea2a948Sdanielk1977 ** journal file in bytes is larger than this value, then truncate the
1384bea2a948Sdanielk1977 ** journal file to Pager.journalSizeLimit bytes. The journal file does
1385bea2a948Sdanielk1977 ** not need to be synced following this operation.
1386bea2a948Sdanielk1977 **
1387bea2a948Sdanielk1977 ** If an IO error occurs, abandon processing and return the IO error code.
1388bea2a948Sdanielk1977 ** Otherwise, return SQLITE_OK.
1389f3a87624Sdrh */
zeroJournalHdr(Pager * pPager,int doTruncate)1390df2566a3Sdanielk1977 static int zeroJournalHdr(Pager *pPager, int doTruncate){
1391bea2a948Sdanielk1977   int rc = SQLITE_OK;                               /* Return code */
1392bea2a948Sdanielk1977   assert( isOpen(pPager->jfd) );
13935f37ed51Sdan   assert( !sqlite3JournalIsInMemory(pPager->jfd) );
1394df2566a3Sdanielk1977   if( pPager->journalOff ){
1395bea2a948Sdanielk1977     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
1396b53e4960Sdanielk1977 
1397f3a87624Sdrh     IOTRACE(("JZEROHDR %p\n", pPager))
1398b53e4960Sdanielk1977     if( doTruncate || iLimit==0 ){
1399df2566a3Sdanielk1977       rc = sqlite3OsTruncate(pPager->jfd, 0);
1400df2566a3Sdanielk1977     }else{
1401bea2a948Sdanielk1977       static const char zeroHdr[28] = {0};
1402f3a87624Sdrh       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
1403df2566a3Sdanielk1977     }
14048162054bSdanielk1977     if( rc==SQLITE_OK && !pPager->noSync ){
1405c97d8463Sdrh       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
1406a06ecba2Sdrh     }
1407b53e4960Sdanielk1977 
1408b53e4960Sdanielk1977     /* At this point the transaction is committed but the write lock
1409b53e4960Sdanielk1977     ** is still held on the file. If there is a size limit configured for
1410b53e4960Sdanielk1977     ** the persistent journal and the journal file currently consumes more
1411b53e4960Sdanielk1977     ** space than that limit allows for, truncate it now. There is no need
1412b53e4960Sdanielk1977     ** to sync the file following this operation.
1413b53e4960Sdanielk1977     */
1414b53e4960Sdanielk1977     if( rc==SQLITE_OK && iLimit>0 ){
1415b53e4960Sdanielk1977       i64 sz;
1416b53e4960Sdanielk1977       rc = sqlite3OsFileSize(pPager->jfd, &sz);
1417b53e4960Sdanielk1977       if( rc==SQLITE_OK && sz>iLimit ){
1418b53e4960Sdanielk1977         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
1419b53e4960Sdanielk1977       }
1420b53e4960Sdanielk1977     }
1421df2566a3Sdanielk1977   }
1422f3a87624Sdrh   return rc;
1423f3a87624Sdrh }
1424f3a87624Sdrh 
1425f3a87624Sdrh /*
14267657240aSdanielk1977 ** The journal file must be open when this routine is called. A journal
14277657240aSdanielk1977 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
14287657240aSdanielk1977 ** current location.
14297657240aSdanielk1977 **
14307657240aSdanielk1977 ** The format for the journal header is as follows:
14317657240aSdanielk1977 ** - 8 bytes: Magic identifying journal format.
14327657240aSdanielk1977 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
14337657240aSdanielk1977 ** - 4 bytes: Random number used for page hash.
14347657240aSdanielk1977 ** - 4 bytes: Initial database page count.
14357657240aSdanielk1977 ** - 4 bytes: Sector size used by the process that wrote this journal.
143667c007bfSdanielk1977 ** - 4 bytes: Database page size.
14377657240aSdanielk1977 **
143867c007bfSdanielk1977 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
14397657240aSdanielk1977 */
writeJournalHdr(Pager * pPager)14407657240aSdanielk1977 static int writeJournalHdr(Pager *pPager){
1441bea2a948Sdanielk1977   int rc = SQLITE_OK;                 /* Return code */
1442bea2a948Sdanielk1977   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
144343b18e1eSdrh   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
1444bea2a948Sdanielk1977   u32 nWrite;                         /* Bytes of header sector written */
1445bea2a948Sdanielk1977   int ii;                             /* Loop counter */
1446bea2a948Sdanielk1977 
1447bea2a948Sdanielk1977   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
1448a664f8ebSdanielk1977 
1449a664f8ebSdanielk1977   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
1450a664f8ebSdanielk1977     nHeader = JOURNAL_HDR_SZ(pPager);
1451a664f8ebSdanielk1977   }
14527657240aSdanielk1977 
1453bea2a948Sdanielk1977   /* If there are active savepoints and any of them were created
1454bea2a948Sdanielk1977   ** since the most recent journal header was written, update the
1455bea2a948Sdanielk1977   ** PagerSavepoint.iHdrOffset fields now.
1456fd7f0452Sdanielk1977   */
1457fd7f0452Sdanielk1977   for(ii=0; ii<pPager->nSavepoint; ii++){
1458fd7f0452Sdanielk1977     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
1459fd7f0452Sdanielk1977       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
1460fd7f0452Sdanielk1977     }
14614099f6e1Sdanielk1977   }
14624099f6e1Sdanielk1977 
1463bea2a948Sdanielk1977   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
14644cd2cd5cSdanielk1977 
14654cd2cd5cSdanielk1977   /*
14664cd2cd5cSdanielk1977   ** Write the nRec Field - the number of page records that follow this
14674cd2cd5cSdanielk1977   ** journal header. Normally, zero is written to this value at this time.
14684cd2cd5cSdanielk1977   ** After the records are added to the journal (and the journal synced,
14694cd2cd5cSdanielk1977   ** if in full-sync mode), the zero is overwritten with the true number
14704cd2cd5cSdanielk1977   ** of records (see syncJournal()).
14714cd2cd5cSdanielk1977   **
14724cd2cd5cSdanielk1977   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
14734cd2cd5cSdanielk1977   ** reading the journal this value tells SQLite to assume that the
14744cd2cd5cSdanielk1977   ** rest of the journal file contains valid page records. This assumption
1475be217793Sshane   ** is dangerous, as if a failure occurred whilst writing to the journal
14764cd2cd5cSdanielk1977   ** file it may contain some garbage data. There are two scenarios
14774cd2cd5cSdanielk1977   ** where this risk can be ignored:
14784cd2cd5cSdanielk1977   **
14794cd2cd5cSdanielk1977   **   * When the pager is in no-sync mode. Corruption can follow a
14804cd2cd5cSdanielk1977   **     power failure in this case anyway.
14814cd2cd5cSdanielk1977   **
14824cd2cd5cSdanielk1977   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
14834cd2cd5cSdanielk1977   **     that garbage data is never appended to the journal file.
14844cd2cd5cSdanielk1977   */
1485bea2a948Sdanielk1977   assert( isOpen(pPager->fd) || pPager->noSync );
1486d0864087Sdan   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
14874cd2cd5cSdanielk1977    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
14884cd2cd5cSdanielk1977   ){
14896f4c73eeSdanielk1977     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
14904cd2cd5cSdanielk1977     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
14914cd2cd5cSdanielk1977   }else{
14925ec53191Sdrh     memset(zHeader, 0, sizeof(aJournalMagic)+4);
14934cd2cd5cSdanielk1977   }
14944cd2cd5cSdanielk1977 
149548864df9Smistachkin   /* The random check-hash initializer */
14962fa1868fSdrh   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
149797b57484Sdrh   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
14987657240aSdanielk1977   /* The initial database size */
14993460d19cSdanielk1977   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
15007657240aSdanielk1977   /* The assumed sector size for this process */
150197b57484Sdrh   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
150208609ce7Sdrh 
1503bea2a948Sdanielk1977   /* The page size */
1504bea2a948Sdanielk1977   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
1505bea2a948Sdanielk1977 
150608609ce7Sdrh   /* Initializing the tail of the buffer is not necessary.  Everything
150708609ce7Sdrh   ** works find if the following memset() is omitted.  But initializing
150808609ce7Sdrh   ** the memory prevents valgrind from complaining, so we are willing to
150908609ce7Sdrh   ** take the performance hit.
151008609ce7Sdrh   */
1511bea2a948Sdanielk1977   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
1512bea2a948Sdanielk1977          nHeader-(sizeof(aJournalMagic)+20));
151308609ce7Sdrh 
1514bea2a948Sdanielk1977   /* In theory, it is only necessary to write the 28 bytes that the
1515bea2a948Sdanielk1977   ** journal header consumes to the journal file here. Then increment the
1516bea2a948Sdanielk1977   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
1517bea2a948Sdanielk1977   ** record is written to the following sector (leaving a gap in the file
1518bea2a948Sdanielk1977   ** that will be implicitly filled in by the OS).
1519bea2a948Sdanielk1977   **
1520bea2a948Sdanielk1977   ** However it has been discovered that on some systems this pattern can
1521bea2a948Sdanielk1977   ** be significantly slower than contiguously writing data to the file,
1522bea2a948Sdanielk1977   ** even if that means explicitly writing data to the block of
1523bea2a948Sdanielk1977   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
1524bea2a948Sdanielk1977   ** is done.
1525bea2a948Sdanielk1977   **
1526bea2a948Sdanielk1977   ** The loop is required here in case the sector-size is larger than the
1527bea2a948Sdanielk1977   ** database page size. Since the zHeader buffer is only Pager.pageSize
1528bea2a948Sdanielk1977   ** bytes in size, more than one call to sqlite3OsWrite() may be required
1529bea2a948Sdanielk1977   ** to populate the entire journal header sector.
1530bea2a948Sdanielk1977   */
1531a664f8ebSdanielk1977   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
1532a664f8ebSdanielk1977     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
1533a664f8ebSdanielk1977     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
153491781bd7Sdrh     assert( pPager->journalHdr <= pPager->journalOff );
1535a664f8ebSdanielk1977     pPager->journalOff += nHeader;
1536b4746b9eSdrh   }
1537a664f8ebSdanielk1977 
15387657240aSdanielk1977   return rc;
15397657240aSdanielk1977 }
15407657240aSdanielk1977 
15417657240aSdanielk1977 /*
15427657240aSdanielk1977 ** The journal file must be open when this is called. A journal header file
15437657240aSdanielk1977 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
1544d6e5e098Sdrh ** file. The current location in the journal file is given by
1545d6e5e098Sdrh ** pPager->journalOff. See comments above function writeJournalHdr() for
1546d6e5e098Sdrh ** a description of the journal header format.
15477657240aSdanielk1977 **
1548bea2a948Sdanielk1977 ** If the header is read successfully, *pNRec is set to the number of
1549bea2a948Sdanielk1977 ** page records following this header and *pDbSize is set to the size of the
15507657240aSdanielk1977 ** database before the transaction began, in pages. Also, pPager->cksumInit
15517657240aSdanielk1977 ** is set to the value read from the journal header. SQLITE_OK is returned
15527657240aSdanielk1977 ** in this case.
15537657240aSdanielk1977 **
15547657240aSdanielk1977 ** If the journal header file appears to be corrupted, SQLITE_DONE is
1555bea2a948Sdanielk1977 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
15567657240aSdanielk1977 ** cannot be read from the journal file an error code is returned.
15577657240aSdanielk1977 */
readJournalHdr(Pager * pPager,int isHot,i64 journalSize,u32 * pNRec,u32 * pDbSize)15587657240aSdanielk1977 static int readJournalHdr(
1559bea2a948Sdanielk1977   Pager *pPager,               /* Pager object */
15606f4c73eeSdanielk1977   int isHot,
1561bea2a948Sdanielk1977   i64 journalSize,             /* Size of the open journal file in bytes */
1562bea2a948Sdanielk1977   u32 *pNRec,                  /* OUT: Value read from the nRec field */
1563bea2a948Sdanielk1977   u32 *pDbSize                 /* OUT: Value of original database size field */
15647657240aSdanielk1977 ){
1565bea2a948Sdanielk1977   int rc;                      /* Return code */
15667657240aSdanielk1977   unsigned char aMagic[8];     /* A buffer to hold the magic header */
1567bea2a948Sdanielk1977   i64 iHdrOff;                 /* Offset of journal header being read */
15687657240aSdanielk1977 
1569bea2a948Sdanielk1977   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
1570bea2a948Sdanielk1977 
1571bea2a948Sdanielk1977   /* Advance Pager.journalOff to the start of the next sector. If the
1572bea2a948Sdanielk1977   ** journal file is too small for there to be a header stored at this
1573bea2a948Sdanielk1977   ** point, return SQLITE_DONE.
1574bea2a948Sdanielk1977   */
1575bea2a948Sdanielk1977   pPager->journalOff = journalHdrOffset(pPager);
15767657240aSdanielk1977   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
15777657240aSdanielk1977     return SQLITE_DONE;
15787657240aSdanielk1977   }
1579bea2a948Sdanielk1977   iHdrOff = pPager->journalOff;
15807657240aSdanielk1977 
1581bea2a948Sdanielk1977   /* Read in the first 8 bytes of the journal header. If they do not match
1582bea2a948Sdanielk1977   ** the  magic string found at the start of each journal header, return
1583bea2a948Sdanielk1977   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
1584bea2a948Sdanielk1977   ** proceed.
1585bea2a948Sdanielk1977   */
15866f4c73eeSdanielk1977   if( isHot || iHdrOff!=pPager->journalHdr ){
1587bea2a948Sdanielk1977     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
1588bea2a948Sdanielk1977     if( rc ){
1589bea2a948Sdanielk1977       return rc;
1590bea2a948Sdanielk1977     }
15917657240aSdanielk1977     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
15927657240aSdanielk1977       return SQLITE_DONE;
15937657240aSdanielk1977     }
15946f4c73eeSdanielk1977   }
15957657240aSdanielk1977 
1596bea2a948Sdanielk1977   /* Read the first three 32-bit fields of the journal header: The nRec
1597bea2a948Sdanielk1977   ** field, the checksum-initializer and the database size at the start
1598bea2a948Sdanielk1977   ** of the transaction. Return an error code if anything goes wrong.
1599bea2a948Sdanielk1977   */
1600bea2a948Sdanielk1977   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
1601bea2a948Sdanielk1977    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
1602bea2a948Sdanielk1977    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
1603bea2a948Sdanielk1977   ){
1604bea2a948Sdanielk1977     return rc;
1605bea2a948Sdanielk1977   }
16067657240aSdanielk1977 
16077cbd589dSdanielk1977   if( pPager->journalOff==0 ){
1608bea2a948Sdanielk1977     u32 iPageSize;               /* Page-size field of journal header */
1609bea2a948Sdanielk1977     u32 iSectorSize;             /* Sector-size field of journal header */
16107cbd589dSdanielk1977 
1611bea2a948Sdanielk1977     /* Read the page-size and sector-size journal header fields. */
1612bea2a948Sdanielk1977     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
1613bea2a948Sdanielk1977      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
161467c007bfSdanielk1977     ){
1615bea2a948Sdanielk1977       return rc;
161667c007bfSdanielk1977     }
1617bea2a948Sdanielk1977 
1618a35dafcdSdan     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
1619a35dafcdSdan     ** journal header to zero. In this case, assume that the Pager.pageSize
1620a35dafcdSdan     ** variable is already set to the correct page size.
1621a35dafcdSdan     */
1622a35dafcdSdan     if( iPageSize==0 ){
1623a35dafcdSdan       iPageSize = pPager->pageSize;
1624a35dafcdSdan     }
1625a35dafcdSdan 
1626bea2a948Sdanielk1977     /* Check that the values read from the page-size and sector-size fields
1627bea2a948Sdanielk1977     ** are within range. To be 'in range', both values need to be a power
16283c99d68bSdrh     ** of two greater than or equal to 512 or 32, and not greater than their
1629bea2a948Sdanielk1977     ** respective compile time maximum limits.
1630bea2a948Sdanielk1977     */
16313c99d68bSdrh     if( iPageSize<512                  || iSectorSize<32
1632bea2a948Sdanielk1977      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
1633bea2a948Sdanielk1977      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
1634bea2a948Sdanielk1977     ){
1635bea2a948Sdanielk1977       /* If the either the page-size or sector-size in the journal-header is
1636bea2a948Sdanielk1977       ** invalid, then the process that wrote the journal-header must have
1637bea2a948Sdanielk1977       ** crashed before the header was synced. In this case stop reading
1638bea2a948Sdanielk1977       ** the journal file here.
1639bea2a948Sdanielk1977       */
1640bea2a948Sdanielk1977       return SQLITE_DONE;
1641bea2a948Sdanielk1977     }
1642bea2a948Sdanielk1977 
1643bea2a948Sdanielk1977     /* Update the page-size to match the value read from the journal.
1644bea2a948Sdanielk1977     ** Use a testcase() macro to make sure that malloc failure within
1645bea2a948Sdanielk1977     ** PagerSetPagesize() is tested.
1646bea2a948Sdanielk1977     */
1647b2eced5dSdrh     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
1648bea2a948Sdanielk1977     testcase( rc!=SQLITE_OK );
164967c007bfSdanielk1977 
16507657240aSdanielk1977     /* Update the assumed sector-size to match the value used by
16517657240aSdanielk1977     ** the process that created this journal. If this journal was
16527657240aSdanielk1977     ** created by a process other than this one, then this routine
16537657240aSdanielk1977     ** is being called from within pager_playback(). The local value
16547657240aSdanielk1977     ** of Pager.sectorSize is restored at the end of that routine.
16557657240aSdanielk1977     */
16567cbd589dSdanielk1977     pPager->sectorSize = iSectorSize;
16577cbd589dSdanielk1977   }
16587657240aSdanielk1977 
16597657240aSdanielk1977   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
1660bea2a948Sdanielk1977   return rc;
16617657240aSdanielk1977 }
16627657240aSdanielk1977 
16637657240aSdanielk1977 
16647657240aSdanielk1977 /*
1665067b92baSdrh ** Write the supplied super-journal name into the journal file for pager
1666067b92baSdrh ** pPager at the current location. The super-journal name must be the last
1667cafadbacSdanielk1977 ** thing written to a journal file. If the pager is in full-sync mode, the
1668cafadbacSdanielk1977 ** journal file descriptor is advanced to the next sector boundary before
1669cafadbacSdanielk1977 ** anything is written. The format is:
1670cafadbacSdanielk1977 **
1671584bfcaeSdrh **   + 4 bytes: PAGER_SJ_PGNO.
1672067b92baSdrh **   + N bytes: super-journal filename in utf-8.
1673067b92baSdrh **   + 4 bytes: N (length of super-journal name in bytes, no nul-terminator).
1674067b92baSdrh **   + 4 bytes: super-journal name checksum.
1675cafadbacSdanielk1977 **   + 8 bytes: aJournalMagic[].
1676cafadbacSdanielk1977 **
1677067b92baSdrh ** The super-journal page checksum is the sum of the bytes in thesuper-journal
1678067b92baSdrh ** name, where each byte is interpreted as a signed 8-bit integer.
1679aef0bf64Sdanielk1977 **
1680067b92baSdrh ** If zSuper is a NULL pointer (occurs for a single database transaction),
1681aef0bf64Sdanielk1977 ** this call is a no-op.
16827657240aSdanielk1977 */
writeSuperJournal(Pager * pPager,const char * zSuper)1683067b92baSdrh static int writeSuperJournal(Pager *pPager, const char *zSuper){
1684bea2a948Sdanielk1977   int rc;                          /* Return code */
1685067b92baSdrh   int nSuper;                      /* Length of string zSuper */
1686bea2a948Sdanielk1977   i64 iHdrOff;                     /* Offset of header in journal file */
1687bea2a948Sdanielk1977   i64 jrnlSize;                    /* Size of journal file on disk */
1688067b92baSdrh   u32 cksum = 0;                   /* Checksum of string zSuper */
16897657240aSdanielk1977 
1690067b92baSdrh   assert( pPager->setSuper==0 );
1691d0864087Sdan   assert( !pagerUseWal(pPager) );
16921e01cf1bSdan 
1693067b92baSdrh   if( !zSuper
1694bea2a948Sdanielk1977    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
16951fb6a110Sdrh    || !isOpen(pPager->jfd)
1696bea2a948Sdanielk1977   ){
1697bea2a948Sdanielk1977     return SQLITE_OK;
1698bea2a948Sdanielk1977   }
1699067b92baSdrh   pPager->setSuper = 1;
170091781bd7Sdrh   assert( pPager->journalHdr <= pPager->journalOff );
17017657240aSdanielk1977 
1702067b92baSdrh   /* Calculate the length in bytes and the checksum of zSuper */
1703067b92baSdrh   for(nSuper=0; zSuper[nSuper]; nSuper++){
1704067b92baSdrh     cksum += zSuper[nSuper];
1705cafadbacSdanielk1977   }
17067657240aSdanielk1977 
17077657240aSdanielk1977   /* If in full-sync mode, advance to the next disk sector before writing
1708067b92baSdrh   ** the super-journal name. This is in case the previous page written to
17097657240aSdanielk1977   ** the journal has already been synced.
17107657240aSdanielk1977   */
17117657240aSdanielk1977   if( pPager->fullSync ){
1712bea2a948Sdanielk1977     pPager->journalOff = journalHdrOffset(pPager);
17137657240aSdanielk1977   }
1714bea2a948Sdanielk1977   iHdrOff = pPager->journalOff;
17157657240aSdanielk1977 
1716067b92baSdrh   /* Write the super-journal data to the end of the journal file. If
1717bea2a948Sdanielk1977   ** an error occurs, return the error code to the caller.
1718bea2a948Sdanielk1977   */
1719584bfcaeSdrh   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_SJ_PGNO(pPager))))
1720067b92baSdrh    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4)))
1721067b92baSdrh    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper)))
1722067b92baSdrh    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum)))
1723e399ac2eSdrh    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
1724067b92baSdrh                                  iHdrOff+4+nSuper+8)))
1725bea2a948Sdanielk1977   ){
1726bea2a948Sdanielk1977     return rc;
1727bea2a948Sdanielk1977   }
1728067b92baSdrh   pPager->journalOff += (nSuper+20);
1729df2566a3Sdanielk1977 
1730df2566a3Sdanielk1977   /* If the pager is in peristent-journal mode, then the physical
1731067b92baSdrh   ** journal-file may extend past the end of the super-journal name
1732df2566a3Sdanielk1977   ** and 8 bytes of magic data just written to the file. This is
1733df2566a3Sdanielk1977   ** dangerous because the code to rollback a hot-journal file
1734067b92baSdrh   ** will not be able to find the super-journal name to determine
1735df2566a3Sdanielk1977   ** whether or not the journal is hot.
1736df2566a3Sdanielk1977   **
1737df2566a3Sdanielk1977   ** Easiest thing to do in this scenario is to truncate the journal
1738df2566a3Sdanielk1977   ** file to the required size.
1739df2566a3Sdanielk1977   */
1740bea2a948Sdanielk1977   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
1741bea2a948Sdanielk1977    && jrnlSize>pPager->journalOff
1742df2566a3Sdanielk1977   ){
1743bea2a948Sdanielk1977     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
1744df2566a3Sdanielk1977   }
17457657240aSdanielk1977   return rc;
17467657240aSdanielk1977 }
17477657240aSdanielk1977 
17487657240aSdanielk1977 /*
1749a42c66bdSdan ** Discard the entire contents of the in-memory page-cache.
1750ed7c855cSdrh */
pager_reset(Pager * pPager)1751d9b0257aSdrh static void pager_reset(Pager *pPager){
1752d7107b38Sdrh   pPager->iDataVersion++;
17530410302eSdanielk1977   sqlite3BackupRestart(pPager->pBackup);
17548c0a791aSdanielk1977   sqlite3PcacheClear(pPager->pPCache);
1755e277be05Sdanielk1977 }
1756e277be05Sdanielk1977 
175734cf35daSdanielk1977 /*
1758d7107b38Sdrh ** Return the pPager->iDataVersion value
175991618564Sdrh */
sqlite3PagerDataVersion(Pager * pPager)176091618564Sdrh u32 sqlite3PagerDataVersion(Pager *pPager){
1761d7107b38Sdrh   return pPager->iDataVersion;
176291618564Sdrh }
176391618564Sdrh 
176491618564Sdrh /*
176534cf35daSdanielk1977 ** Free all structures in the Pager.aSavepoint[] array and set both
176634cf35daSdanielk1977 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
176734cf35daSdanielk1977 ** if it is open and the pager is not in exclusive mode.
176834cf35daSdanielk1977 */
releaseAllSavepoints(Pager * pPager)1769bea2a948Sdanielk1977 static void releaseAllSavepoints(Pager *pPager){
1770bea2a948Sdanielk1977   int ii;               /* Iterator for looping through Pager.aSavepoint */
1771fd7f0452Sdanielk1977   for(ii=0; ii<pPager->nSavepoint; ii++){
1772fd7f0452Sdanielk1977     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
1773fd7f0452Sdanielk1977   }
17742491de28Sdan   if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
1775fd7f0452Sdanielk1977     sqlite3OsClose(pPager->sjfd);
1776fd7f0452Sdanielk1977   }
1777fd7f0452Sdanielk1977   sqlite3_free(pPager->aSavepoint);
1778fd7f0452Sdanielk1977   pPager->aSavepoint = 0;
1779fd7f0452Sdanielk1977   pPager->nSavepoint = 0;
1780bea2a948Sdanielk1977   pPager->nSubRec = 0;
1781fd7f0452Sdanielk1977 }
1782fd7f0452Sdanielk1977 
178334cf35daSdanielk1977 /*
1784bea2a948Sdanielk1977 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
1785bea2a948Sdanielk1977 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
1786bea2a948Sdanielk1977 ** or SQLITE_NOMEM if a malloc failure occurs.
178734cf35daSdanielk1977 */
addToSavepointBitvecs(Pager * pPager,Pgno pgno)1788fd7f0452Sdanielk1977 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
17897539b6b8Sdrh   int ii;                   /* Loop counter */
17907539b6b8Sdrh   int rc = SQLITE_OK;       /* Result code */
17917539b6b8Sdrh 
1792fd7f0452Sdanielk1977   for(ii=0; ii<pPager->nSavepoint; ii++){
1793fd7f0452Sdanielk1977     PagerSavepoint *p = &pPager->aSavepoint[ii];
1794fd7f0452Sdanielk1977     if( pgno<=p->nOrig ){
17957539b6b8Sdrh       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
1796bea2a948Sdanielk1977       testcase( rc==SQLITE_NOMEM );
17977539b6b8Sdrh       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
1798fd7f0452Sdanielk1977     }
1799fd7f0452Sdanielk1977   }
18007539b6b8Sdrh   return rc;
1801fd7f0452Sdanielk1977 }
1802fd7f0452Sdanielk1977 
1803e277be05Sdanielk1977 /*
1804de5fd22fSdan ** This function is a no-op if the pager is in exclusive mode and not
1805de5fd22fSdan ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
1806de5fd22fSdan ** state.
1807ae72d982Sdanielk1977 **
1808de5fd22fSdan ** If the pager is not in exclusive-access mode, the database file is
1809de5fd22fSdan ** completely unlocked. If the file is unlocked and the file-system does
1810de5fd22fSdan ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
1811de5fd22fSdan ** closed (if it is open).
1812de5fd22fSdan **
1813de5fd22fSdan ** If the pager is in ERROR state when this function is called, the
1814de5fd22fSdan ** contents of the pager cache are discarded before switching back to
1815de5fd22fSdan ** the OPEN state. Regardless of whether the pager is in exclusive-mode
1816de5fd22fSdan ** or not, any journal file left in the file-system will be treated
1817de5fd22fSdan ** as a hot-journal and rolled back the next time a read-transaction
1818de5fd22fSdan ** is opened (by this or by any other connection).
1819ae72d982Sdanielk1977 */
pager_unlock(Pager * pPager)1820ae72d982Sdanielk1977 static void pager_unlock(Pager *pPager){
1821a42c66bdSdan 
1822de5fd22fSdan   assert( pPager->eState==PAGER_READER
1823de5fd22fSdan        || pPager->eState==PAGER_OPEN
1824de5fd22fSdan        || pPager->eState==PAGER_ERROR
1825de5fd22fSdan   );
1826de5fd22fSdan 
1827a42c66bdSdan   sqlite3BitvecDestroy(pPager->pInJournal);
1828a42c66bdSdan   pPager->pInJournal = 0;
1829a42c66bdSdan   releaseAllSavepoints(pPager);
1830a42c66bdSdan 
1831a42c66bdSdan   if( pagerUseWal(pPager) ){
1832a42c66bdSdan     assert( !isOpen(pPager->jfd) );
1833a42c66bdSdan     sqlite3WalEndReadTransaction(pPager->pWal);
1834de1ae34eSdan     pPager->eState = PAGER_OPEN;
1835a42c66bdSdan   }else if( !pPager->exclusiveMode ){
18364e004aa6Sdan     int rc;                       /* Error code returned by pagerUnlockDb() */
1837e08341c6Sdan     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
1838ae72d982Sdanielk1977 
1839de3c301dSdrh     /* If the operating system support deletion of open files, then
1840de3c301dSdrh     ** close the journal file when dropping the database lock.  Otherwise
1841de3c301dSdrh     ** another connection with journal_mode=delete might delete the file
1842de3c301dSdrh     ** out from under us.
184316e45a43Sdrh     */
1844e08341c6Sdan     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
1845e08341c6Sdan     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
1846e08341c6Sdan     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
1847e08341c6Sdan     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
1848e08341c6Sdan     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
1849e08341c6Sdan     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
1850e08341c6Sdan     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
1851e08341c6Sdan      || 1!=(pPager->journalMode & 5)
18522a321c75Sdan     ){
185316e45a43Sdrh       sqlite3OsClose(pPager->jfd);
18542a321c75Sdan     }
18554e004aa6Sdan 
185654919f82Sdan     /* If the pager is in the ERROR state and the call to unlock the database
185754919f82Sdan     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
185854919f82Sdan     ** above the #define for UNKNOWN_LOCK for an explanation of why this
185954919f82Sdan     ** is necessary.
186054919f82Sdan     */
18614e004aa6Sdan     rc = pagerUnlockDb(pPager, NO_LOCK);
18624e004aa6Sdan     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
18634e004aa6Sdan       pPager->eLock = UNKNOWN_LOCK;
18644e004aa6Sdan     }
18652a321c75Sdan 
1866de1ae34eSdan     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
1867a42c66bdSdan     ** without clearing the error code. This is intentional - the error
1868a42c66bdSdan     ** code is cleared and the cache reset in the block below.
1869ae72d982Sdanielk1977     */
1870a42c66bdSdan     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
1871de1ae34eSdan     pPager->eState = PAGER_OPEN;
1872a42c66bdSdan   }
1873a42c66bdSdan 
1874a42c66bdSdan   /* If Pager.errCode is set, the contents of the pager cache cannot be
1875a42c66bdSdan   ** trusted. Now that there are no outstanding references to the pager,
1876de1ae34eSdan   ** it can safely move back to PAGER_OPEN state. This happens in both
1877a42c66bdSdan   ** normal and exclusive-locking mode.
18786c963586Sdrh   */
187967330a12Sdan   assert( pPager->errCode==SQLITE_OK || !MEMDB );
18806572c16aSdan   if( pPager->errCode ){
18816572c16aSdan     if( pPager->tempFile==0 ){
1882a42c66bdSdan       pager_reset(pPager);
188367330a12Sdan       pPager->changeCountDone = 0;
1884de1ae34eSdan       pPager->eState = PAGER_OPEN;
18856572c16aSdan     }else{
18866572c16aSdan       pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
18876572c16aSdan     }
1888789efdb9Sdan     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
18896572c16aSdan     pPager->errCode = SQLITE_OK;
189012e6f682Sdrh     setGetterMethod(pPager);
1891ae72d982Sdanielk1977   }
18924e004aa6Sdan 
18934e004aa6Sdan   pPager->journalOff = 0;
18944e004aa6Sdan   pPager->journalHdr = 0;
1895067b92baSdrh   pPager->setSuper = 0;
1896ae72d982Sdanielk1977 }
1897ae72d982Sdanielk1977 
1898ae72d982Sdanielk1977 /*
1899de5fd22fSdan ** This function is called whenever an IOERR or FULL error that requires
1900de5fd22fSdan ** the pager to transition into the ERROR state may ahve occurred.
1901de5fd22fSdan ** The first argument is a pointer to the pager structure, the second
1902de5fd22fSdan ** the error-code about to be returned by a pager API function. The
1903de5fd22fSdan ** value returned is a copy of the second argument to this function.
1904bea2a948Sdanielk1977 **
1905de5fd22fSdan ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
1906de5fd22fSdan ** IOERR sub-codes, the pager enters the ERROR state and the error code
1907de5fd22fSdan ** is stored in Pager.errCode. While the pager remains in the ERROR state,
1908de5fd22fSdan ** all major API calls on the Pager will immediately return Pager.errCode.
1909bea2a948Sdanielk1977 **
1910de5fd22fSdan ** The ERROR state indicates that the contents of the pager-cache
1911bea2a948Sdanielk1977 ** cannot be trusted. This state can be cleared by completely discarding
1912bea2a948Sdanielk1977 ** the contents of the pager-cache. If a transaction was active when
1913be217793Sshane ** the persistent error occurred, then the rollback journal may need
1914bea2a948Sdanielk1977 ** to be replayed to restore the contents of the database file (as if
1915bea2a948Sdanielk1977 ** it were a hot-journal).
1916bea2a948Sdanielk1977 */
pager_error(Pager * pPager,int rc)1917bea2a948Sdanielk1977 static int pager_error(Pager *pPager, int rc){
1918bea2a948Sdanielk1977   int rc2 = rc & 0xff;
1919c7ca875eSdanielk1977   assert( rc==SQLITE_OK || !MEMDB );
1920bea2a948Sdanielk1977   assert(
1921bea2a948Sdanielk1977        pPager->errCode==SQLITE_FULL ||
1922bea2a948Sdanielk1977        pPager->errCode==SQLITE_OK ||
1923bea2a948Sdanielk1977        (pPager->errCode & 0xff)==SQLITE_IOERR
1924bea2a948Sdanielk1977   );
1925b75d570eSdrh   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
1926bea2a948Sdanielk1977     pPager->errCode = rc;
1927a42c66bdSdan     pPager->eState = PAGER_ERROR;
192812e6f682Sdrh     setGetterMethod(pPager);
1929bea2a948Sdanielk1977   }
1930bea2a948Sdanielk1977   return rc;
1931bea2a948Sdanielk1977 }
1932bea2a948Sdanielk1977 
1933bc1a3c6cSdan static int pager_truncate(Pager *pPager, Pgno nPage);
1934bc1a3c6cSdan 
1935bea2a948Sdanielk1977 /*
19364bf7d21fSdrh ** The write transaction open on pPager is being committed (bCommit==1)
19374bf7d21fSdrh ** or rolled back (bCommit==0).
19380f52455aSdan **
19394bf7d21fSdrh ** Return TRUE if and only if all dirty pages should be flushed to disk.
19400f52455aSdan **
19414bf7d21fSdrh ** Rules:
19420f52455aSdan **
19434bf7d21fSdrh **   *  For non-TEMP databases, always sync to disk.  This is necessary
19444bf7d21fSdrh **      for transactions to be durable.
19454bf7d21fSdrh **
19464bf7d21fSdrh **   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
19474bf7d21fSdrh **      file has been created already (via a spill on pagerStress()) and
19484bf7d21fSdrh **      when the number of dirty pages in memory exceeds 25% of the total
19494bf7d21fSdrh **      cache size.
19500f52455aSdan */
pagerFlushOnCommit(Pager * pPager,int bCommit)19514bf7d21fSdrh static int pagerFlushOnCommit(Pager *pPager, int bCommit){
19520f52455aSdan   if( pPager->tempFile==0 ) return 1;
19534bf7d21fSdrh   if( !bCommit ) return 0;
19540f52455aSdan   if( !isOpen(pPager->fd) ) return 0;
19550f52455aSdan   return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
19560f52455aSdan }
19570f52455aSdan 
19580f52455aSdan /*
1959bea2a948Sdanielk1977 ** This routine ends a transaction. A transaction is usually ended by
1960bea2a948Sdanielk1977 ** either a COMMIT or a ROLLBACK operation. This routine may be called
1961bea2a948Sdanielk1977 ** after rollback of a hot-journal, or if an error occurs while opening
1962bea2a948Sdanielk1977 ** the journal file or writing the very first journal-header of a
1963bea2a948Sdanielk1977 ** database transaction.
196480e35f46Sdrh **
196585d14ed2Sdan ** This routine is never called in PAGER_ERROR state. If it is called
196685d14ed2Sdan ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
196785d14ed2Sdan ** exclusive than a RESERVED lock, it is a no-op.
196880e35f46Sdrh **
1969bea2a948Sdanielk1977 ** Otherwise, any active savepoints are released.
197050457896Sdrh **
1971bea2a948Sdanielk1977 ** If the journal file is open, then it is "finalized". Once a journal
1972bea2a948Sdanielk1977 ** file has been finalized it is not possible to use it to roll back a
1973bea2a948Sdanielk1977 ** transaction. Nor will it be considered to be a hot-journal by this
1974bea2a948Sdanielk1977 ** or any other database connection. Exactly how a journal is finalized
1975bea2a948Sdanielk1977 ** depends on whether or not the pager is running in exclusive mode and
1976bea2a948Sdanielk1977 ** the current journal-mode (Pager.journalMode value), as follows:
1977bea2a948Sdanielk1977 **
1978bea2a948Sdanielk1977 **   journalMode==MEMORY
1979bea2a948Sdanielk1977 **     Journal file descriptor is simply closed. This destroys an
1980bea2a948Sdanielk1977 **     in-memory journal.
1981bea2a948Sdanielk1977 **
1982bea2a948Sdanielk1977 **   journalMode==TRUNCATE
1983bea2a948Sdanielk1977 **     Journal file is truncated to zero bytes in size.
1984bea2a948Sdanielk1977 **
1985bea2a948Sdanielk1977 **   journalMode==PERSIST
1986bea2a948Sdanielk1977 **     The first 28 bytes of the journal file are zeroed. This invalidates
1987bea2a948Sdanielk1977 **     the first journal header in the file, and hence the entire journal
1988bea2a948Sdanielk1977 **     file. An invalid journal file cannot be rolled back.
1989bea2a948Sdanielk1977 **
1990bea2a948Sdanielk1977 **   journalMode==DELETE
1991bea2a948Sdanielk1977 **     The journal file is closed and deleted using sqlite3OsDelete().
1992bea2a948Sdanielk1977 **
1993bea2a948Sdanielk1977 **     If the pager is running in exclusive mode, this method of finalizing
1994bea2a948Sdanielk1977 **     the journal file is never used. Instead, if the journalMode is
1995bea2a948Sdanielk1977 **     DELETE and the pager is in exclusive mode, the method described under
1996bea2a948Sdanielk1977 **     journalMode==PERSIST is used instead.
1997bea2a948Sdanielk1977 **
199885d14ed2Sdan ** After the journal is finalized, the pager moves to PAGER_READER state.
199985d14ed2Sdan ** If running in non-exclusive rollback mode, the lock on the file is
200085d14ed2Sdan ** downgraded to a SHARED_LOCK.
2001bea2a948Sdanielk1977 **
2002bea2a948Sdanielk1977 ** SQLITE_OK is returned if no error occurs. If an error occurs during
2003bea2a948Sdanielk1977 ** any of the IO operations to finalize the journal file or unlock the
2004bea2a948Sdanielk1977 ** database then the IO error code is returned to the user. If the
2005bea2a948Sdanielk1977 ** operation to finalize the journal file fails, then the code still
2006bea2a948Sdanielk1977 ** tries to unlock the database file if not in exclusive mode. If the
2007bea2a948Sdanielk1977 ** unlock operation fails as well, then the first error code related
2008bea2a948Sdanielk1977 ** to the first error encountered (the journal finalization one) is
2009bea2a948Sdanielk1977 ** returned.
2010ed7c855cSdrh */
pager_end_transaction(Pager * pPager,int hasSuper,int bCommit)2011067b92baSdrh static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){
2012bea2a948Sdanielk1977   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
2013bea2a948Sdanielk1977   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
2014bea2a948Sdanielk1977 
201585d14ed2Sdan   /* Do nothing if the pager does not have an open write transaction
201685d14ed2Sdan   ** or at least a RESERVED lock. This function may be called when there
201785d14ed2Sdan   ** is no write-transaction active but a RESERVED or greater lock is
201885d14ed2Sdan   ** held under two circumstances:
201985d14ed2Sdan   **
202085d14ed2Sdan   **   1. After a successful hot-journal rollback, it is called with
202185d14ed2Sdan   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
202285d14ed2Sdan   **
202385d14ed2Sdan   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
202485d14ed2Sdan   **      lock switches back to locking_mode=normal and then executes a
202585d14ed2Sdan   **      read-transaction, this function is called with eState==PAGER_READER
202685d14ed2Sdan   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
202785d14ed2Sdan   */
2028d0864087Sdan   assert( assert_pager_state(pPager) );
2029a42c66bdSdan   assert( pPager->eState!=PAGER_ERROR );
2030de1ae34eSdan   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
2031a6abd041Sdrh     return SQLITE_OK;
2032a6abd041Sdrh   }
2033bea2a948Sdanielk1977 
2034d0864087Sdan   releaseAllSavepoints(pPager);
2035efe16971Sdan   assert( isOpen(pPager->jfd) || pPager->pInJournal==0
2036efe16971Sdan       || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
2037efe16971Sdan   );
2038bea2a948Sdanielk1977   if( isOpen(pPager->jfd) ){
20397ed91f23Sdrh     assert( !pagerUseWal(pPager) );
2040bea2a948Sdanielk1977 
2041bea2a948Sdanielk1977     /* Finalize the journal file. */
20422491de28Sdan     if( sqlite3JournalIsInMemory(pPager->jfd) ){
20432491de28Sdan       /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
2044b3175389Sdanielk1977       sqlite3OsClose(pPager->jfd);
20459e7ba7c6Sdrh     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
204659813953Sdrh       if( pPager->journalOff==0 ){
204759813953Sdrh         rc = SQLITE_OK;
204859813953Sdrh       }else{
20499e7ba7c6Sdrh         rc = sqlite3OsTruncate(pPager->jfd, 0);
2050442c5cd3Sdrh         if( rc==SQLITE_OK && pPager->fullSync ){
2051442c5cd3Sdrh           /* Make sure the new file size is written into the inode right away.
2052442c5cd3Sdrh           ** Otherwise the journal might resurrect following a power loss and
2053442c5cd3Sdrh           ** cause the last transaction to roll back.  See
2054442c5cd3Sdrh           ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
2055442c5cd3Sdrh           */
2056442c5cd3Sdrh           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
2057442c5cd3Sdrh         }
205859813953Sdrh       }
205904335886Sdrh       pPager->journalOff = 0;
20605543759bSdan     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
20615543759bSdan       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
206293f7af97Sdanielk1977     ){
2063067b92baSdrh       rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile);
206441483468Sdanielk1977       pPager->journalOff = 0;
206541483468Sdanielk1977     }else{
2066ded6d0f1Sdanielk1977       /* This branch may be executed with Pager.journalMode==MEMORY if
2067ded6d0f1Sdanielk1977       ** a hot-journal was just rolled back. In this case the journal
2068ded6d0f1Sdanielk1977       ** file should be closed and deleted. If this connection writes to
2069e04dc88bSdan       ** the database file, it will do so using an in-memory journal.
2070e04dc88bSdan       */
20715f37ed51Sdan       int bDelete = !pPager->tempFile;
20725f37ed51Sdan       assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
2073ded6d0f1Sdanielk1977       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
2074ded6d0f1Sdanielk1977            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
2075e04dc88bSdan            || pPager->journalMode==PAGER_JOURNALMODE_WAL
2076ded6d0f1Sdanielk1977       );
2077b4b47411Sdanielk1977       sqlite3OsClose(pPager->jfd);
20783de0f184Sdan       if( bDelete ){
20796841b1cbSdrh         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
208041483468Sdanielk1977       }
20817152de8dSdanielk1977     }
20825f848c3aSdan   }
2083bea2a948Sdanielk1977 
20843c407374Sdanielk1977 #ifdef SQLITE_CHECK_PAGES
2085bc2ca9ebSdanielk1977   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
20865f848c3aSdan   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
2087c137807aSdrh     PgHdr *p = sqlite3PagerLookup(pPager, 1);
20885f848c3aSdan     if( p ){
20895f848c3aSdan       p->pageHash = 0;
2090da8a330aSdrh       sqlite3PagerUnrefNotNull(p);
2091e9c2d34cSdrh     }
20925f848c3aSdan   }
20935f848c3aSdan #endif
20945f848c3aSdan 
2095bea2a948Sdanielk1977   sqlite3BitvecDestroy(pPager->pInJournal);
2096bea2a948Sdanielk1977   pPager->pInJournal = 0;
2097ef317ab5Sdanielk1977   pPager->nRec = 0;
2098a37e0cfbSdrh   if( rc==SQLITE_OK ){
209965e1ba3fSdrh     if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
2100ba726f49Sdrh       sqlite3PcacheCleanAll(pPager->pPCache);
210141113b64Sdan     }else{
210241113b64Sdan       sqlite3PcacheClearWritable(pPager->pPCache);
210341113b64Sdan     }
2104d0864087Sdan     sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
2105a37e0cfbSdrh   }
2106979f38e5Sdanielk1977 
21077ed91f23Sdrh   if( pagerUseWal(pPager) ){
2108d0864087Sdan     /* Drop the WAL write-lock, if any. Also, if the connection was in
2109d0864087Sdan     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
2110d0864087Sdan     ** lock held on the database file.
2111d0864087Sdan     */
211273b64e4dSdrh     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
21130350c7faSdrh     assert( rc2==SQLITE_OK );
2114bc1a3c6cSdan   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
2115bc1a3c6cSdan     /* This branch is taken when committing a transaction in rollback-journal
2116bc1a3c6cSdan     ** mode if the database file on disk is larger than the database image.
2117bc1a3c6cSdan     ** At this point the journal has been finalized and the transaction
2118bc1a3c6cSdan     ** successfully committed, but the EXCLUSIVE lock is still held on the
2119bc1a3c6cSdan     ** file. So it is safe to truncate the database file to its minimum
2120bc1a3c6cSdan     ** required size.  */
2121bc1a3c6cSdan     assert( pPager->eLock==EXCLUSIVE_LOCK );
2122bc1a3c6cSdan     rc = pager_truncate(pPager, pPager->dbSize);
21235543759bSdan   }
2124bc1a3c6cSdan 
2125afb39a4cSdrh   if( rc==SQLITE_OK && bCommit ){
2126999cd08aSdan     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
2127999cd08aSdan     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
2128999cd08aSdan   }
2129999cd08aSdan 
2130431b0b42Sdan   if( !pPager->exclusiveMode
2131431b0b42Sdan    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
2132431b0b42Sdan   ){
21334e004aa6Sdan     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
2134334cdb63Sdanielk1977   }
2135d0864087Sdan   pPager->eState = PAGER_READER;
2136067b92baSdrh   pPager->setSuper = 0;
2137979f38e5Sdanielk1977 
2138979f38e5Sdanielk1977   return (rc==SQLITE_OK?rc2:rc);
2139ed7c855cSdrh }
2140ed7c855cSdrh 
2141ed7c855cSdrh /*
2142d0864087Sdan ** Execute a rollback if a transaction is active and unlock the
2143d0864087Sdan ** database file.
2144d0864087Sdan **
214585d14ed2Sdan ** If the pager has already entered the ERROR state, do not attempt
2146d0864087Sdan ** the rollback at this time. Instead, pager_unlock() is called. The
2147d0864087Sdan ** call to pager_unlock() will discard all in-memory pages, unlock
214885d14ed2Sdan ** the database file and move the pager back to OPEN state. If this
214985d14ed2Sdan ** means that there is a hot-journal left in the file-system, the next
215085d14ed2Sdan ** connection to obtain a shared lock on the pager (which may be this one)
215185d14ed2Sdan ** will roll it back.
2152d0864087Sdan **
215385d14ed2Sdan ** If the pager has not already entered the ERROR state, but an IO or
2154d0864087Sdan ** malloc error occurs during a rollback, then this will itself cause
215585d14ed2Sdan ** the pager to enter the ERROR state. Which will be cleared by the
2156d0864087Sdan ** call to pager_unlock(), as described above.
2157d0864087Sdan */
pagerUnlockAndRollback(Pager * pPager)2158d0864087Sdan static void pagerUnlockAndRollback(Pager *pPager){
2159de1ae34eSdan   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
2160a42c66bdSdan     assert( assert_pager_state(pPager) );
2161de1ae34eSdan     if( pPager->eState>=PAGER_WRITER_LOCKED ){
2162d0864087Sdan       sqlite3BeginBenignMalloc();
2163d0864087Sdan       sqlite3PagerRollback(pPager);
2164d0864087Sdan       sqlite3EndBenignMalloc();
216585d14ed2Sdan     }else if( !pPager->exclusiveMode ){
216611f47a9bSdan       assert( pPager->eState==PAGER_READER );
2167bc1a3c6cSdan       pager_end_transaction(pPager, 0, 0);
2168d0864087Sdan     }
2169d0864087Sdan   }
2170d0864087Sdan   pager_unlock(pPager);
2171d0864087Sdan }
2172d0864087Sdan 
2173d0864087Sdan /*
2174bea2a948Sdanielk1977 ** Parameter aData must point to a buffer of pPager->pageSize bytes
2175bea2a948Sdanielk1977 ** of data. Compute and return a checksum based ont the contents of the
2176bea2a948Sdanielk1977 ** page of data and the current value of pPager->cksumInit.
217734e79ceeSdrh **
217834e79ceeSdrh ** This is not a real checksum. It is really just the sum of the
2179bea2a948Sdanielk1977 ** random initial value (pPager->cksumInit) and every 200th byte
2180bea2a948Sdanielk1977 ** of the page data, starting with byte offset (pPager->pageSize%200).
2181bea2a948Sdanielk1977 ** Each byte is interpreted as an 8-bit unsigned integer.
2182726de599Sdrh **
2183bea2a948Sdanielk1977 ** Changing the formula used to compute this checksum results in an
2184bea2a948Sdanielk1977 ** incompatible journal file format.
2185bea2a948Sdanielk1977 **
2186bea2a948Sdanielk1977 ** If journal corruption occurs due to a power failure, the most likely
2187bea2a948Sdanielk1977 ** scenario is that one end or the other of the record will be changed.
2188bea2a948Sdanielk1977 ** It is much less likely that the two ends of the journal record will be
2189726de599Sdrh ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
2190726de599Sdrh ** though fast and simple, catches the mostly likely kind of corruption.
2191968af52aSdrh */
pager_cksum(Pager * pPager,const u8 * aData)219274161705Sdrh static u32 pager_cksum(Pager *pPager, const u8 *aData){
2193bea2a948Sdanielk1977   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
2194bea2a948Sdanielk1977   int i = pPager->pageSize-200;          /* Loop counter */
2195ef317ab5Sdanielk1977   while( i>0 ){
2196ef317ab5Sdanielk1977     cksum += aData[i];
2197ef317ab5Sdanielk1977     i -= 200;
2198ef317ab5Sdanielk1977   }
2199968af52aSdrh   return cksum;
2200968af52aSdrh }
2201968af52aSdrh 
2202968af52aSdrh /*
2203d6e5e098Sdrh ** Read a single page from either the journal file (if isMainJrnl==1) or
2204d6e5e098Sdrh ** from the sub-journal (if isMainJrnl==0) and playback that page.
2205d6e5e098Sdrh ** The page begins at offset *pOffset into the file. The *pOffset
2206d6e5e098Sdrh ** value is increased to the start of the next page in the journal.
2207968af52aSdrh **
220885d14ed2Sdan ** The main rollback journal uses checksums - the statement journal does
220985d14ed2Sdan ** not.
2210d6e5e098Sdrh **
2211bea2a948Sdanielk1977 ** If the page number of the page record read from the (sub-)journal file
2212bea2a948Sdanielk1977 ** is greater than the current value of Pager.dbSize, then playback is
2213bea2a948Sdanielk1977 ** skipped and SQLITE_OK is returned.
2214bea2a948Sdanielk1977 **
2215d6e5e098Sdrh ** If pDone is not NULL, then it is a record of pages that have already
2216d6e5e098Sdrh ** been played back.  If the page at *pOffset has already been played back
2217d6e5e098Sdrh ** (if the corresponding pDone bit is set) then skip the playback.
2218d6e5e098Sdrh ** Make sure the pDone bit corresponding to the *pOffset page is set
2219d6e5e098Sdrh ** prior to returning.
2220bea2a948Sdanielk1977 **
2221bea2a948Sdanielk1977 ** If the page record is successfully read from the (sub-)journal file
2222bea2a948Sdanielk1977 ** and played back, then SQLITE_OK is returned. If an IO error occurs
2223bea2a948Sdanielk1977 ** while reading the record from the (sub-)journal file or while writing
2224bea2a948Sdanielk1977 ** to the database file, then the IO error code is returned. If data
2225bea2a948Sdanielk1977 ** is successfully read from the (sub-)journal file but appears to be
2226bea2a948Sdanielk1977 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
2227bea2a948Sdanielk1977 ** two circumstances:
2228bea2a948Sdanielk1977 **
2229584bfcaeSdrh **   * If the record page-number is illegal (0 or PAGER_SJ_PGNO), or
2230bea2a948Sdanielk1977 **   * If the record is being rolled back from the main journal file
2231bea2a948Sdanielk1977 **     and the checksum field does not match the record content.
2232bea2a948Sdanielk1977 **
2233bea2a948Sdanielk1977 ** Neither of these two scenarios are possible during a savepoint rollback.
2234bea2a948Sdanielk1977 **
2235bea2a948Sdanielk1977 ** If this is a savepoint rollback, then memory may have to be dynamically
2236bea2a948Sdanielk1977 ** allocated by this function. If this is the case and an allocation fails,
2237bea2a948Sdanielk1977 ** SQLITE_NOMEM is returned.
2238fa86c412Sdrh */
pager_playback_one_page(Pager * pPager,i64 * pOffset,Bitvec * pDone,int isMainJrnl,int isSavepnt)223962079060Sdanielk1977 static int pager_playback_one_page(
2240c13148ffSdrh   Pager *pPager,                /* The pager being played back */
2241d6e5e098Sdrh   i64 *pOffset,                 /* Offset of record to playback */
224291781bd7Sdrh   Bitvec *pDone,                /* Bitvec of pages already played back */
224391781bd7Sdrh   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
224491781bd7Sdrh   int isSavepnt                 /* True for a savepoint rollback */
224562079060Sdanielk1977 ){
2246fa86c412Sdrh   int rc;
2247fa86c412Sdrh   PgHdr *pPg;                   /* An existing page in the cache */
2248ae2b40c4Sdrh   Pgno pgno;                    /* The page number of a page in journal */
2249ae2b40c4Sdrh   u32 cksum;                    /* Checksum used for sanity checking */
2250bfcb4adaSdrh   char *aData;                  /* Temporary storage for the page */
2251d6e5e098Sdrh   sqlite3_file *jfd;            /* The file descriptor for the journal file */
225291781bd7Sdrh   int isSynced;                 /* True if journal page is synced */
2253fa86c412Sdrh 
2254d6e5e098Sdrh   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
2255d6e5e098Sdrh   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
2256d6e5e098Sdrh   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
2257d6e5e098Sdrh   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
22589636284eSdrh 
2259bfcb4adaSdrh   aData = pPager->pTmpSpace;
2260d6e5e098Sdrh   assert( aData );         /* Temp storage must have already been allocated */
22617ed91f23Sdrh   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
2262d6e5e098Sdrh 
226385d14ed2Sdan   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
226485d14ed2Sdan   ** or savepoint rollback done at the request of the caller) or this is
226585d14ed2Sdan   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
226685d14ed2Sdan   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
226785d14ed2Sdan   ** only reads from the main journal, not the sub-journal.
226885d14ed2Sdan   */
226985d14ed2Sdan   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
227085d14ed2Sdan        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
227185d14ed2Sdan   );
227285d14ed2Sdan   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
227385d14ed2Sdan 
2274bea2a948Sdanielk1977   /* Read the page number and page data from the journal or sub-journal
2275bea2a948Sdanielk1977   ** file. Return an error code to the caller if an IO error occurs.
2276bea2a948Sdanielk1977   */
2277d6e5e098Sdrh   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
2278d6e5e098Sdrh   rc = read32bits(jfd, *pOffset, &pgno);
227999ee3600Sdrh   if( rc!=SQLITE_OK ) return rc;
2280bfcb4adaSdrh   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
228199ee3600Sdrh   if( rc!=SQLITE_OK ) return rc;
2282d6e5e098Sdrh   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
2283fa86c412Sdrh 
2284968af52aSdrh   /* Sanity checking on the page.  This is more important that I originally
2285968af52aSdrh   ** thought.  If a power failure occurs while the journal is being written,
2286968af52aSdrh   ** it could cause invalid data to be written into the journal.  We need to
2287968af52aSdrh   ** detect this invalid data (with high probability) and ignore it.
2288968af52aSdrh   */
2289584bfcaeSdrh   if( pgno==0 || pgno==PAGER_SJ_PGNO(pPager) ){
2290bea2a948Sdanielk1977     assert( !isSavepnt );
2291968af52aSdrh     return SQLITE_DONE;
2292968af52aSdrh   }
2293fd7f0452Sdanielk1977   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
2294968af52aSdrh     return SQLITE_OK;
2295968af52aSdrh   }
2296c13148ffSdrh   if( isMainJrnl ){
2297d6e5e098Sdrh     rc = read32bits(jfd, (*pOffset)-4, &cksum);
229899ee3600Sdrh     if( rc ) return rc;
2299bfcb4adaSdrh     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
2300968af52aSdrh       return SQLITE_DONE;
2301968af52aSdrh     }
2302968af52aSdrh   }
2303bea2a948Sdanielk1977 
2304b3475530Sdrh   /* If this page has already been played back before during the current
23058220da7bSdrh   ** rollback, then don't bother to play it back again.
23068220da7bSdrh   */
2307859546caSdanielk1977   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
2308fd7f0452Sdanielk1977     return rc;
2309fd7f0452Sdanielk1977   }
2310a3f3a5f3Sdanielk1977 
23118220da7bSdrh   /* When playing back page 1, restore the nReserve setting
23128220da7bSdrh   */
23138220da7bSdrh   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
23148220da7bSdrh     pPager->nReserve = ((u8*)aData)[20];
23158220da7bSdrh   }
23168220da7bSdrh 
2317de5fd22fSdan   /* If the pager is in CACHEMOD state, then there must be a copy of this
2318a3f3a5f3Sdanielk1977   ** page in the pager cache. In this case just update the pager cache,
23190de0bb33Sdanielk1977   ** not the database file. The page is left marked dirty in this case.
23200de0bb33Sdanielk1977   **
23212df71c74Sdanielk1977   ** An exception to the above rule: If the database is in no-sync mode
23222df71c74Sdanielk1977   ** and a page is moved during an incremental vacuum then the page may
2323369f3a05Sdanielk1977   ** not be in the pager cache. Later: if a malloc() or IO error occurs
2324369f3a05Sdanielk1977   ** during a Movepage() call, then the page may not be in the cache
2325369f3a05Sdanielk1977   ** either. So the condition described in the above paragraph is not
2326369f3a05Sdanielk1977   ** assert()able.
23272df71c74Sdanielk1977   **
2328de5fd22fSdan   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
2329de5fd22fSdan   ** pager cache if it exists and the main file. The page is then marked
2330de5fd22fSdan   ** not dirty. Since this code is only executed in PAGER_OPEN state for
2331de5fd22fSdan   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
2332de5fd22fSdan   ** if the pager is in OPEN state.
23339636284eSdrh   **
23349636284eSdrh   ** Ticket #1171:  The statement journal might contain page content that is
23359636284eSdrh   ** different from the page content at the start of the transaction.
23369636284eSdrh   ** This occurs when a page is changed prior to the start of a statement
23379636284eSdrh   ** then changed again within the statement.  When rolling back such a
23389636284eSdrh   ** statement we must not write to the original database unless we know
23395e385311Sdrh   ** for certain that original page contents are synced into the main rollback
23405e385311Sdrh   ** journal.  Otherwise, a power loss might leave modified data in the
23415e385311Sdrh   ** database file without an entry in the rollback journal that can
23425e385311Sdrh   ** restore the database to its original form.  Two conditions must be
23435e385311Sdrh   ** met before writing to the database files. (1) the database must be
23445e385311Sdrh   ** locked.  (2) we know that the original page content is fully synced
23455e385311Sdrh   ** in the main journal either because the page is not in cache or else
23465e385311Sdrh   ** the page is marked as needSync==0.
23474c02a235Sdrh   **
23484c02a235Sdrh   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
23494c02a235Sdrh   ** is possible to fail a statement on a database that does not yet exist.
23504c02a235Sdrh   ** Do not attempt to write if database file has never been opened.
2351fa86c412Sdrh   */
23527ed91f23Sdrh   if( pagerUseWal(pPager) ){
23534cd78b4dSdan     pPg = 0;
23544cd78b4dSdan   }else{
2355c137807aSdrh     pPg = sqlite3PagerLookup(pPager, pgno);
23564cd78b4dSdan   }
235786655a1dSdrh   assert( pPg || !MEMDB );
23586572c16aSdan   assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
235930d53701Sdrh   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
2360bfcb4adaSdrh            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
2361ecfef985Sdanielk1977            (isMainJrnl?"main-journal":"sub-journal")
236230d53701Sdrh   ));
236391781bd7Sdrh   if( isMainJrnl ){
236491781bd7Sdrh     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
236591781bd7Sdrh   }else{
236691781bd7Sdrh     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
236791781bd7Sdrh   }
2368719e3a7aSdrh   if( isOpen(pPager->fd)
2369719e3a7aSdrh    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
237091781bd7Sdrh    && isSynced
23718c0a791aSdanielk1977   ){
2372281b21daSdrh     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
237305f69dd3Sdrh     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
23747ed91f23Sdrh     assert( !pagerUseWal(pPager) );
23752617c9bdSdan 
23762617c9bdSdan     /* Write the data read from the journal back into the database file.
23772617c9bdSdan     ** This is usually safe even for an encrypted database - as the data
23782617c9bdSdan     ** was encrypted before it was written to the journal file. The exception
23792617c9bdSdan     ** is if the data was just read from an in-memory sub-journal. In that
23802617c9bdSdan     ** case it must be encrypted here before it is copied into the database
23812617c9bdSdan     ** file.  */
2382614c6a09Sdrh     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
23832617c9bdSdan 
23843460d19cSdanielk1977     if( pgno>pPager->dbFileSize ){
23853460d19cSdanielk1977       pPager->dbFileSize = pgno;
23863460d19cSdanielk1977     }
23870719ee29Sdrh     if( pPager->pBackup ){
2388614c6a09Sdrh       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
23890719ee29Sdrh     }
2390f2c31ad8Sdanielk1977   }else if( !isMainJrnl && pPg==0 ){
2391f2c31ad8Sdanielk1977     /* If this is a rollback of a savepoint and data was not written to
2392f2c31ad8Sdanielk1977     ** the database and the page is not in-memory, there is a potential
2393f2c31ad8Sdanielk1977     ** problem. When the page is next fetched by the b-tree layer, it
2394f2c31ad8Sdanielk1977     ** will be read from the database file, which may or may not be
2395f2c31ad8Sdanielk1977     ** current.
2396f2c31ad8Sdanielk1977     **
2397f2c31ad8Sdanielk1977     ** There are a couple of different ways this can happen. All are quite
2398401b65edSdanielk1977     ** obscure. When running in synchronous mode, this can only happen
2399f2c31ad8Sdanielk1977     ** if the page is on the free-list at the start of the transaction, then
2400f2c31ad8Sdanielk1977     ** populated, then moved using sqlite3PagerMovepage().
2401f2c31ad8Sdanielk1977     **
2402f2c31ad8Sdanielk1977     ** The solution is to add an in-memory page to the cache containing
2403f2c31ad8Sdanielk1977     ** the data just read from the sub-journal. Mark the page as dirty
2404f2c31ad8Sdanielk1977     ** and if the pager requires a journal-sync, then mark the page as
2405f2c31ad8Sdanielk1977     ** requiring a journal-sync before it is written.
2406f2c31ad8Sdanielk1977     */
2407f2c31ad8Sdanielk1977     assert( isSavepnt );
240840c3941cSdrh     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
240940c3941cSdrh     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
24109584f58cSdrh     rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
241140c3941cSdrh     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
241240c3941cSdrh     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
24137cf4c7adSdrh     if( rc!=SQLITE_OK ) return rc;
2414f2c31ad8Sdanielk1977     sqlite3PcacheMakeDirty(pPg);
2415a3f3a5f3Sdanielk1977   }
2416fa86c412Sdrh   if( pPg ){
24172812956bSdanielk1977     /* No page should ever be explicitly rolled back that is in use, except
24182812956bSdanielk1977     ** for page 1 which is held in use in order to keep the lock on the
24192812956bSdanielk1977     ** database active. However such a page may be rolled back as a result
24202812956bSdanielk1977     ** of an internal error resulting in an automatic call to
24213b8a05f6Sdanielk1977     ** sqlite3PagerRollback().
24223a84069dSdrh     */
2423b6f41486Sdrh     void *pData;
24248c0a791aSdanielk1977     pData = pPg->pData;
2425bfcb4adaSdrh     memcpy(pData, (u8*)aData, pPager->pageSize);
2426eaa06f69Sdanielk1977     pPager->xReiniter(pPg);
242742bee5f4Sdrh     /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
242842bee5f4Sdrh     ** that call was dangerous and had no detectable benefit since the cache
242942bee5f4Sdrh     ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
243042bee5f4Sdrh     ** has been removed. */
24315f848c3aSdan     pager_set_pagehash(pPg);
24325f848c3aSdan 
243386a88114Sdrh     /* If this was page 1, then restore the value of Pager.dbFileVers.
243486a88114Sdrh     ** Do this before any decoding. */
243541483468Sdanielk1977     if( pgno==1 ){
243686a88114Sdrh       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
243741483468Sdanielk1977     }
24388c0a791aSdanielk1977     sqlite3PcacheRelease(pPg);
2439fa86c412Sdrh   }
2440fa86c412Sdrh   return rc;
2441fa86c412Sdrh }
2442fa86c412Sdrh 
2443fa86c412Sdrh /*
2444067b92baSdrh ** Parameter zSuper is the name of a super-journal file. A single journal
2445067b92baSdrh ** file that referred to the super-journal file has just been rolled back.
2446067b92baSdrh ** This routine checks if it is possible to delete the super-journal file,
244713adf8a0Sdanielk1977 ** and does so if it is.
2448726de599Sdrh **
2449067b92baSdrh ** Argument zSuper may point to Pager.pTmpSpace. So that buffer is not
245065839c6aSdanielk1977 ** available for use within this function.
245165839c6aSdanielk1977 **
2452067b92baSdrh ** When a super-journal file is created, it is populated with the names
2453bea2a948Sdanielk1977 ** of all of its child journals, one after another, formatted as utf-8
2454bea2a948Sdanielk1977 ** encoded text. The end of each child journal file is marked with a
2455067b92baSdrh ** nul-terminator byte (0x00). i.e. the entire contents of a super-journal
2456bea2a948Sdanielk1977 ** file for a transaction involving two databases might be:
245765839c6aSdanielk1977 **
2458bea2a948Sdanielk1977 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
2459bea2a948Sdanielk1977 **
2460067b92baSdrh ** A super-journal file may only be deleted once all of its child
2461bea2a948Sdanielk1977 ** journals have been rolled back.
2462bea2a948Sdanielk1977 **
2463067b92baSdrh ** This function reads the contents of the super-journal file into
2464bea2a948Sdanielk1977 ** memory and loops through each of the child journal names. For
2465bea2a948Sdanielk1977 ** each child journal, it checks if:
2466bea2a948Sdanielk1977 **
2467bea2a948Sdanielk1977 **   * if the child journal exists, and if so
2468067b92baSdrh **   * if the child journal contains a reference to super-journal
2469067b92baSdrh **     file zSuper
2470bea2a948Sdanielk1977 **
2471bea2a948Sdanielk1977 ** If a child journal can be found that matches both of the criteria
2472bea2a948Sdanielk1977 ** above, this function returns without doing anything. Otherwise, if
2473067b92baSdrh ** no such child journal can be found, file zSuper is deleted from
2474bea2a948Sdanielk1977 ** the file-system using sqlite3OsDelete().
2475bea2a948Sdanielk1977 **
2476bea2a948Sdanielk1977 ** If an IO error within this function, an error code is returned. This
2477bea2a948Sdanielk1977 ** function allocates memory by calling sqlite3Malloc(). If an allocation
2478bea2a948Sdanielk1977 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
2479bea2a948Sdanielk1977 ** occur, SQLITE_OK is returned.
2480bea2a948Sdanielk1977 **
2481bea2a948Sdanielk1977 ** TODO: This function allocates a single block of memory to load
2482067b92baSdrh ** the entire contents of the super-journal file. This could be
2483bea2a948Sdanielk1977 ** a couple of kilobytes or so - potentially larger than the page
2484bea2a948Sdanielk1977 ** size.
248513adf8a0Sdanielk1977 */
pager_delsuper(Pager * pPager,const char * zSuper)2486067b92baSdrh static int pager_delsuper(Pager *pPager, const char *zSuper){
2487b4b47411Sdanielk1977   sqlite3_vfs *pVfs = pPager->pVfs;
2488bea2a948Sdanielk1977   int rc;                   /* Return code */
2489067b92baSdrh   sqlite3_file *pSuper;     /* Malloc'd super-journal file descriptor */
2490bea2a948Sdanielk1977   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
2491067b92baSdrh   char *zSuperJournal = 0;  /* Contents of super-journal file */
2492067b92baSdrh   i64 nSuperJournal;        /* Size of super-journal file */
2493a64febe1Sdrh   char *zJournal;           /* Pointer to one journal within MJ file */
2494067b92baSdrh   char *zSuperPtr;          /* Space to hold super-journal filename */
24952e3cb138Sdan   char *zFree = 0;          /* Free this buffer */
2496067b92baSdrh   int nSuperPtr;            /* Amount of space allocated to zSuperPtr[] */
249713adf8a0Sdanielk1977 
2498067b92baSdrh   /* Allocate space for both the pJournal and pSuper file descriptors.
2499067b92baSdrh   ** If successful, open the super-journal file for reading.
250013adf8a0Sdanielk1977   */
2501067b92baSdrh   pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
2502067b92baSdrh   if( !pSuper ){
2503fad3039cSmistachkin     rc = SQLITE_NOMEM_BKPT;
250414d093f8Sdrh     pJournal = 0;
2505b4b47411Sdanielk1977   }else{
2506ccb2113aSdrh     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
2507067b92baSdrh     rc = sqlite3OsOpen(pVfs, zSuper, pSuper, flags, 0);
25088afc09deSdrh     pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile);
2509b4b47411Sdanielk1977   }
2510067b92baSdrh   if( rc!=SQLITE_OK ) goto delsuper_out;
2511b4b47411Sdanielk1977 
2512067b92baSdrh   /* Load the entire super-journal file into space obtained from
2513067b92baSdrh   ** sqlite3_malloc() and pointed to by zSuperJournal.   Also obtain
2514067b92baSdrh   ** sufficient space (in zSuperPtr) to hold the names of super-journal
2515067b92baSdrh   ** files extracted from regular rollback-journals.
2516a64febe1Sdrh   */
2517067b92baSdrh   rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
2518067b92baSdrh   if( rc!=SQLITE_OK ) goto delsuper_out;
2519067b92baSdrh   nSuperPtr = pVfs->mxPathname+1;
25202e3cb138Sdan   zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2);
2521f5c3a75bSdan   if( !zFree ){
2522fad3039cSmistachkin     rc = SQLITE_NOMEM_BKPT;
2523067b92baSdrh     goto delsuper_out;
252413adf8a0Sdanielk1977   }
2525f5c3a75bSdan   zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;
2526f5c3a75bSdan   zSuperJournal = &zFree[4];
2527067b92baSdrh   zSuperPtr = &zSuperJournal[nSuperJournal+2];
2528067b92baSdrh   rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
2529067b92baSdrh   if( rc!=SQLITE_OK ) goto delsuper_out;
2530067b92baSdrh   zSuperJournal[nSuperJournal] = 0;
2531067b92baSdrh   zSuperJournal[nSuperJournal+1] = 0;
253213adf8a0Sdanielk1977 
2533067b92baSdrh   zJournal = zSuperJournal;
2534067b92baSdrh   while( (zJournal-zSuperJournal)<nSuperJournal ){
2535861f7456Sdanielk1977     int exists;
2536861f7456Sdanielk1977     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
2537861f7456Sdanielk1977     if( rc!=SQLITE_OK ){
2538067b92baSdrh       goto delsuper_out;
253919db9352Sdrh     }
2540861f7456Sdanielk1977     if( exists ){
2541067b92baSdrh       /* One of the journals pointed to by the super-journal exists.
2542067b92baSdrh       ** Open it and check if it points at the super-journal. If
2543067b92baSdrh       ** so, return without deleting the super-journal file.
2544ab2172e6Sdrh       ** NB:  zJournal is really a MAIN_JOURNAL.  But call it a
2545ccb2113aSdrh       ** SUPER_JOURNAL here so that the VFS will not send the zJournal
2546ab2172e6Sdrh       ** name into sqlite3_database_file_object().
254713adf8a0Sdanielk1977       */
25483b7b78b3Sdrh       int c;
2549ccb2113aSdrh       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
2550fee2d25aSdanielk1977       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
255113adf8a0Sdanielk1977       if( rc!=SQLITE_OK ){
2552067b92baSdrh         goto delsuper_out;
255313adf8a0Sdanielk1977       }
25549eed5057Sdanielk1977 
2555067b92baSdrh       rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr);
2556b4b47411Sdanielk1977       sqlite3OsClose(pJournal);
25579eed5057Sdanielk1977       if( rc!=SQLITE_OK ){
2558067b92baSdrh         goto delsuper_out;
25599eed5057Sdanielk1977       }
256013adf8a0Sdanielk1977 
2561067b92baSdrh       c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0;
25623b7b78b3Sdrh       if( c ){
2563067b92baSdrh         /* We have a match. Do not delete the super-journal file. */
2564067b92baSdrh         goto delsuper_out;
256513adf8a0Sdanielk1977       }
256613adf8a0Sdanielk1977     }
2567ea678832Sdrh     zJournal += (sqlite3Strlen30(zJournal)+1);
256813adf8a0Sdanielk1977   }
256913adf8a0Sdanielk1977 
2570067b92baSdrh   sqlite3OsClose(pSuper);
2571067b92baSdrh   rc = sqlite3OsDelete(pVfs, zSuper, 0);
257213adf8a0Sdanielk1977 
2573067b92baSdrh delsuper_out:
25742e3cb138Sdan   sqlite3_free(zFree);
2575067b92baSdrh   if( pSuper ){
2576067b92baSdrh     sqlite3OsClose(pSuper);
2577bea2a948Sdanielk1977     assert( !isOpen(pJournal) );
2578067b92baSdrh     sqlite3_free(pSuper);
2579de3c301dSdrh   }
258013adf8a0Sdanielk1977   return rc;
258113adf8a0Sdanielk1977 }
258213adf8a0Sdanielk1977 
2583a6abd041Sdrh 
2584a6abd041Sdrh /*
2585bea2a948Sdanielk1977 ** This function is used to change the actual size of the database
2586bea2a948Sdanielk1977 ** file in the file-system. This only happens when committing a transaction,
2587bea2a948Sdanielk1977 ** or rolling back a transaction (including rolling back a hot-journal).
25887fe3f7e9Sdrh **
2589de5fd22fSdan ** If the main database file is not open, or the pager is not in either
2590de5fd22fSdan ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
2591de5fd22fSdan ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
2592de5fd22fSdan ** If the file on disk is currently larger than nPage pages, then use the VFS
2593bea2a948Sdanielk1977 ** xTruncate() method to truncate it.
2594bea2a948Sdanielk1977 **
259560ec914cSpeter.d.reid ** Or, it might be the case that the file on disk is smaller than
2596bea2a948Sdanielk1977 ** nPage pages. Some operating system implementations can get confused if
2597bea2a948Sdanielk1977 ** you try to truncate a file to some size that is larger than it
2598bea2a948Sdanielk1977 ** currently is, so detect this case and write a single zero byte to
2599bea2a948Sdanielk1977 ** the end of the new file instead.
2600bea2a948Sdanielk1977 **
2601bea2a948Sdanielk1977 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
2602bea2a948Sdanielk1977 ** the database file, return the error code to the caller.
2603cb4c40baSdrh */
pager_truncate(Pager * pPager,Pgno nPage)2604d92db531Sdanielk1977 static int pager_truncate(Pager *pPager, Pgno nPage){
2605e180dd93Sdanielk1977   int rc = SQLITE_OK;
2606a42c66bdSdan   assert( pPager->eState!=PAGER_ERROR );
26074e004aa6Sdan   assert( pPager->eState!=PAGER_READER );
26084e004aa6Sdan 
26094e004aa6Sdan   if( isOpen(pPager->fd)
2610de1ae34eSdan    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
26114e004aa6Sdan   ){
26127fe3f7e9Sdrh     i64 currentSize, newSize;
2613bd1334dfSdrh     int szPage = pPager->pageSize;
2614de5fd22fSdan     assert( pPager->eLock==EXCLUSIVE_LOCK );
2615bea2a948Sdanielk1977     /* TODO: Is it safe to use Pager.dbFileSize here? */
26167fe3f7e9Sdrh     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
2617bd1334dfSdrh     newSize = szPage*(i64)nPage;
261806e11af9Sdanielk1977     if( rc==SQLITE_OK && currentSize!=newSize ){
261906e11af9Sdanielk1977       if( currentSize>newSize ){
26207fe3f7e9Sdrh         rc = sqlite3OsTruncate(pPager->fd, newSize);
2621935de7e8Sdrh       }else if( (currentSize+szPage)<=newSize ){
2622fb3828c2Sdan         char *pTmp = pPager->pTmpSpace;
2623bd1334dfSdrh         memset(pTmp, 0, szPage);
2624bd1334dfSdrh         testcase( (newSize-szPage) == currentSize );
2625bd1334dfSdrh         testcase( (newSize-szPage) >  currentSize );
2626bbf71138Sdan         sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &newSize);
2627bd1334dfSdrh         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
262806e11af9Sdanielk1977       }
26293460d19cSdanielk1977       if( rc==SQLITE_OK ){
26303460d19cSdanielk1977         pPager->dbFileSize = nPage;
26313460d19cSdanielk1977       }
26327fe3f7e9Sdrh     }
2633e180dd93Sdanielk1977   }
2634e180dd93Sdanielk1977   return rc;
2635cb4c40baSdrh }
2636cb4c40baSdrh 
2637cb4c40baSdrh /*
2638c9a53269Sdan ** Return a sanitized version of the sector-size of OS file pFile. The
2639c9a53269Sdan ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
2640c9a53269Sdan */
sqlite3SectorSize(sqlite3_file * pFile)2641c9a53269Sdan int sqlite3SectorSize(sqlite3_file *pFile){
2642c9a53269Sdan   int iRet = sqlite3OsSectorSize(pFile);
2643c9a53269Sdan   if( iRet<32 ){
2644c9a53269Sdan     iRet = 512;
2645c9a53269Sdan   }else if( iRet>MAX_SECTOR_SIZE ){
2646c9a53269Sdan     assert( MAX_SECTOR_SIZE>=512 );
2647c9a53269Sdan     iRet = MAX_SECTOR_SIZE;
2648c9a53269Sdan   }
2649c9a53269Sdan   return iRet;
2650c9a53269Sdan }
2651c9a53269Sdan 
2652c9a53269Sdan /*
2653bea2a948Sdanielk1977 ** Set the value of the Pager.sectorSize variable for the given
2654bea2a948Sdanielk1977 ** pager based on the value returned by the xSectorSize method
265560ec914cSpeter.d.reid ** of the open database file. The sector size will be used
2656bea2a948Sdanielk1977 ** to determine the size and alignment of journal header and
2657067b92baSdrh ** super-journal pointers within created journal files.
2658c80f058dSdrh **
2659bea2a948Sdanielk1977 ** For temporary files the effective sector size is always 512 bytes.
2660bea2a948Sdanielk1977 **
2661bea2a948Sdanielk1977 ** Otherwise, for non-temporary files, the effective sector size is
26623c99d68bSdrh ** the value returned by the xSectorSize() method rounded up to 32 if
26633c99d68bSdrh ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
2664bea2a948Sdanielk1977 ** is greater than MAX_SECTOR_SIZE.
26658bbaa89dSdrh **
2666cb15f35fSdrh ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
2667cb15f35fSdrh ** the effective sector size to its minimum value (512).  The purpose of
26688bbaa89dSdrh ** pPager->sectorSize is to define the "blast radius" of bytes that
26698bbaa89dSdrh ** might change if a crash occurs while writing to a single byte in
2670cb15f35fSdrh ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
2671cb15f35fSdrh ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
2672cb15f35fSdrh ** size.  For backwards compatibility of the rollback journal file format,
2673cb15f35fSdrh ** we cannot reduce the effective sector size below 512.
2674c80f058dSdrh */
setSectorSize(Pager * pPager)2675c80f058dSdrh static void setSectorSize(Pager *pPager){
2676bea2a948Sdanielk1977   assert( isOpen(pPager->fd) || pPager->tempFile );
2677bea2a948Sdanielk1977 
2678374f4a04Sdrh   if( pPager->tempFile
2679cb15f35fSdrh    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
2680cb15f35fSdrh               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
26818bbaa89dSdrh   ){
26827a2b1eebSdanielk1977     /* Sector size doesn't matter for temporary files. Also, the file
2683bea2a948Sdanielk1977     ** may not have been opened yet, in which case the OsSectorSize()
2684374f4a04Sdrh     ** call will segfault. */
2685374f4a04Sdrh     pPager->sectorSize = 512;
2686374f4a04Sdrh   }else{
2687c9a53269Sdan     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
2688c80f058dSdrh   }
2689374f4a04Sdrh }
2690c80f058dSdrh 
2691c80f058dSdrh /*
2692ed7c855cSdrh ** Playback the journal and thus restore the database file to
2693ed7c855cSdrh ** the state it was in before we started making changes.
2694ed7c855cSdrh **
269534e79ceeSdrh ** The journal file format is as follows:
269634e79ceeSdrh **
2697ae2b40c4Sdrh **  (1)  8 byte prefix.  A copy of aJournalMagic[].
2698ae2b40c4Sdrh **  (2)  4 byte big-endian integer which is the number of valid page records
269934e79ceeSdrh **       in the journal.  If this value is 0xffffffff, then compute the
2700ae2b40c4Sdrh **       number of page records from the journal size.
2701ae2b40c4Sdrh **  (3)  4 byte big-endian integer which is the initial value for the
2702ae2b40c4Sdrh **       sanity checksum.
2703ae2b40c4Sdrh **  (4)  4 byte integer which is the number of pages to truncate the
270434e79ceeSdrh **       database to during a rollback.
2705334c80d6Sdrh **  (5)  4 byte big-endian integer which is the sector size.  The header
2706334c80d6Sdrh **       is this many bytes in size.
2707e7ae4e2cSdrh **  (6)  4 byte big-endian integer which is the page size.
2708e7ae4e2cSdrh **  (7)  zero padding out to the next sector size.
2709e7ae4e2cSdrh **  (8)  Zero or more pages instances, each as follows:
271034e79ceeSdrh **        +  4 byte page number.
2711ae2b40c4Sdrh **        +  pPager->pageSize bytes of data.
2712ae2b40c4Sdrh **        +  4 byte checksum
271334e79ceeSdrh **
2714e7ae4e2cSdrh ** When we speak of the journal header, we mean the first 7 items above.
2715e7ae4e2cSdrh ** Each entry in the journal is an instance of the 8th item.
271634e79ceeSdrh **
271734e79ceeSdrh ** Call the value from the second bullet "nRec".  nRec is the number of
271834e79ceeSdrh ** valid page entries in the journal.  In most cases, you can compute the
271934e79ceeSdrh ** value of nRec from the size of the journal file.  But if a power
272034e79ceeSdrh ** failure occurred while the journal was being written, it could be the
272134e79ceeSdrh ** case that the size of the journal file had already been increased but
272234e79ceeSdrh ** the extra entries had not yet made it safely to disk.  In such a case,
272334e79ceeSdrh ** the value of nRec computed from the file size would be too large.  For
272434e79ceeSdrh ** that reason, we always use the nRec value in the header.
272534e79ceeSdrh **
272634e79ceeSdrh ** If the nRec value is 0xffffffff it means that nRec should be computed
272734e79ceeSdrh ** from the file size.  This value is used when the user selects the
272834e79ceeSdrh ** no-sync option for the journal.  A power failure could lead to corruption
272934e79ceeSdrh ** in this case.  But for things like temporary table (which will be
273034e79ceeSdrh ** deleted when the power is restored) we don't care.
273134e79ceeSdrh **
2732d9b0257aSdrh ** If the file opened as the journal file is not a well-formed
2733ece80f1eSdanielk1977 ** journal file then all pages up to the first corrupted page are rolled
2734ece80f1eSdanielk1977 ** back (or no pages if the journal header is corrupted). The journal file
2735ece80f1eSdanielk1977 ** is then deleted and SQLITE_OK returned, just as if no corruption had
2736ece80f1eSdanielk1977 ** been encountered.
2737ece80f1eSdanielk1977 **
2738ece80f1eSdanielk1977 ** If an I/O or malloc() error occurs, the journal-file is not deleted
2739ece80f1eSdanielk1977 ** and an error code is returned.
2740d3a5c50eSdrh **
2741d3a5c50eSdrh ** The isHot parameter indicates that we are trying to rollback a journal
2742d3a5c50eSdrh ** that might be a hot journal.  Or, it could be that the journal is
2743d3a5c50eSdrh ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
2744d3a5c50eSdrh ** If the journal really is hot, reset the pager cache prior rolling
2745d3a5c50eSdrh ** back any content.  If the journal is merely persistent, no reset is
2746d3a5c50eSdrh ** needed.
2747ed7c855cSdrh */
pager_playback(Pager * pPager,int isHot)2748e277be05Sdanielk1977 static int pager_playback(Pager *pPager, int isHot){
2749b4b47411Sdanielk1977   sqlite3_vfs *pVfs = pPager->pVfs;
2750eb206256Sdrh   i64 szJ;                 /* Size of the journal file in bytes */
2751c3e8f5efSdanielk1977   u32 nRec;                /* Number of Records in the journal */
27520b8d2766Sshane   u32 u;                   /* Unsigned loop counter */
2753ed7c855cSdrh   Pgno mxPg = 0;           /* Size of the original file in pages */
2754ae2b40c4Sdrh   int rc;                  /* Result code of a subroutine */
2755861f7456Sdanielk1977   int res = 1;             /* Value returned by sqlite3OsAccess() */
2756067b92baSdrh   char *zSuper = 0;        /* Name of super-journal file if any */
2757d3a5c50eSdrh   int needPagerReset;      /* True to reset page prior to first page rollback */
2758ab755ac8Sdrh   int nPlayback = 0;       /* Total number of pages restored from journal */
2759edea4a7cSdrh   u32 savedPageSize = pPager->pageSize;
2760ed7c855cSdrh 
2761c3a64ba0Sdrh   /* Figure out how many records are in the journal.  Abort early if
2762c3a64ba0Sdrh   ** the journal is empty.
2763ed7c855cSdrh   */
276422b328b2Sdan   assert( isOpen(pPager->jfd) );
2765054889ecSdrh   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
2766719e3a7aSdrh   if( rc!=SQLITE_OK ){
2767c3a64ba0Sdrh     goto end_playback;
2768c3a64ba0Sdrh   }
2769240c5795Sdrh 
2770067b92baSdrh   /* Read the super-journal name from the journal, if it is present.
2771067b92baSdrh   ** If a super-journal file name is specified, but the file is not
27727657240aSdanielk1977   ** present on disk, then the journal is not hot and does not need to be
27737657240aSdanielk1977   ** played back.
2774bea2a948Sdanielk1977   **
2775bea2a948Sdanielk1977   ** TODO: Technically the following is an error because it assumes that
2776bea2a948Sdanielk1977   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
2777bea2a948Sdanielk1977   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
2778bea2a948Sdanielk1977   ** mxPathname is 512, which is the same as the minimum allowable value
2779bea2a948Sdanielk1977   ** for pageSize.
2780240c5795Sdrh   */
2781067b92baSdrh   zSuper = pPager->pTmpSpace;
2782067b92baSdrh   rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
2783067b92baSdrh   if( rc==SQLITE_OK && zSuper[0] ){
2784067b92baSdrh     rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
27857657240aSdanielk1977   }
2786067b92baSdrh   zSuper = 0;
2787861f7456Sdanielk1977   if( rc!=SQLITE_OK || !res ){
2788ce98bba2Sdanielk1977     goto end_playback;
2789ce98bba2Sdanielk1977   }
2790ce98bba2Sdanielk1977   pPager->journalOff = 0;
2791d3a5c50eSdrh   needPagerReset = isHot;
27927657240aSdanielk1977 
2793bea2a948Sdanielk1977   /* This loop terminates either when a readJournalHdr() or
2794bea2a948Sdanielk1977   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
2795bea2a948Sdanielk1977   ** occurs.
2796bea2a948Sdanielk1977   */
2797edea4a7cSdrh   while( 1 ){
27987657240aSdanielk1977     /* Read the next journal header from the journal file.  If there are
27997657240aSdanielk1977     ** not enough bytes left in the journal file for a complete header, or
2800719e3a7aSdrh     ** it is corrupted, then a process must have failed while writing it.
28017657240aSdanielk1977     ** This indicates nothing more needs to be rolled back.
28027657240aSdanielk1977     */
28036f4c73eeSdanielk1977     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
28047657240aSdanielk1977     if( rc!=SQLITE_OK ){
28057657240aSdanielk1977       if( rc==SQLITE_DONE ){
28067657240aSdanielk1977         rc = SQLITE_OK;
28077657240aSdanielk1977       }
2808c3a64ba0Sdrh       goto end_playback;
2809c3a64ba0Sdrh     }
2810c3a64ba0Sdrh 
28117657240aSdanielk1977     /* If nRec is 0xffffffff, then this journal was created by a process
28127657240aSdanielk1977     ** working in no-sync mode. This means that the rest of the journal
28137657240aSdanielk1977     ** file consists of pages, there are no more journal headers. Compute
28147657240aSdanielk1977     ** the value of nRec based on this assumption.
28157657240aSdanielk1977     */
28167657240aSdanielk1977     if( nRec==0xffffffff ){
28177657240aSdanielk1977       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
28184f21c4afSdrh       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
281913adf8a0Sdanielk1977     }
282013adf8a0Sdanielk1977 
2821e277be05Sdanielk1977     /* If nRec is 0 and this rollback is of a transaction created by this
28228940f4eeSdrh     ** process and if this is the final header in the journal, then it means
28238940f4eeSdrh     ** that this part of the journal was being filled but has not yet been
28248940f4eeSdrh     ** synced to disk.  Compute the number of pages based on the remaining
28258940f4eeSdrh     ** size of the file.
28268940f4eeSdrh     **
28278940f4eeSdrh     ** The third term of the test was added to fix ticket #2565.
2828d6e5e098Sdrh     ** When rolling back a hot journal, nRec==0 always means that the next
2829d6e5e098Sdrh     ** chunk of the journal contains zero pages to be rolled back.  But
2830d6e5e098Sdrh     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
2831d6e5e098Sdrh     ** the journal, it means that the journal might contain additional
2832d6e5e098Sdrh     ** pages that need to be rolled back and that the number of pages
2833d6e5e098Sdrh     ** should be computed based on the journal file size.
2834e277be05Sdanielk1977     */
28358940f4eeSdrh     if( nRec==0 && !isHot &&
28368940f4eeSdrh         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
28374f21c4afSdrh       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
2838e277be05Sdanielk1977     }
2839e277be05Sdanielk1977 
28407657240aSdanielk1977     /* If this is the first header read from the journal, truncate the
284185b623f2Sdrh     ** database file back to its original size.
28427657240aSdanielk1977     */
2843e180dd93Sdanielk1977     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
2844cb4c40baSdrh       rc = pager_truncate(pPager, mxPg);
284581a20f21Sdrh       if( rc!=SQLITE_OK ){
284681a20f21Sdrh         goto end_playback;
284781a20f21Sdrh       }
2848f90b7260Sdanielk1977       pPager->dbSize = mxPg;
284990368c5dSdrh       if( pPager->mxPgno<mxPg ){
285090368c5dSdrh         pPager->mxPgno = mxPg;
285190368c5dSdrh       }
28527657240aSdanielk1977     }
28537657240aSdanielk1977 
2854bea2a948Sdanielk1977     /* Copy original pages out of the journal and back into the
2855bea2a948Sdanielk1977     ** database file and/or page cache.
2856ed7c855cSdrh     */
28570b8d2766Sshane     for(u=0; u<nRec; u++){
2858d3a5c50eSdrh       if( needPagerReset ){
2859d3a5c50eSdrh         pager_reset(pPager);
2860d3a5c50eSdrh         needPagerReset = 0;
2861d3a5c50eSdrh       }
286291781bd7Sdrh       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
2863ab755ac8Sdrh       if( rc==SQLITE_OK ){
2864ab755ac8Sdrh         nPlayback++;
2865ab755ac8Sdrh       }else{
2866968af52aSdrh         if( rc==SQLITE_DONE ){
28677657240aSdanielk1977           pPager->journalOff = szJ;
2868968af52aSdrh           break;
28698d83c0fdSdrh         }else if( rc==SQLITE_IOERR_SHORT_READ ){
28708d83c0fdSdrh           /* If the journal has been truncated, simply stop reading and
28718d83c0fdSdrh           ** processing the journal. This might happen if the journal was
28728d83c0fdSdrh           ** not completely written and synced prior to a crash.  In that
28738d83c0fdSdrh           ** case, the database should have never been written in the
28748d83c0fdSdrh           ** first place so it is OK to simply abandon the rollback. */
28758d83c0fdSdrh           rc = SQLITE_OK;
28768d83c0fdSdrh           goto end_playback;
28777657240aSdanielk1977         }else{
287866fd2160Sdrh           /* If we are unable to rollback, quit and return the error
287966fd2160Sdrh           ** code.  This will cause the pager to enter the error state
288066fd2160Sdrh           ** so that no further harm will be done.  Perhaps the next
288166fd2160Sdrh           ** process to come along will be able to rollback the database.
2882a9625eaeSdrh           */
28837657240aSdanielk1977           goto end_playback;
28847657240aSdanielk1977         }
28857657240aSdanielk1977       }
2886968af52aSdrh     }
2887edea4a7cSdrh   }
2888edea4a7cSdrh   /*NOTREACHED*/
2889edea4a7cSdrh   assert( 0 );
28904a0681efSdrh 
28914a0681efSdrh end_playback:
2892edea4a7cSdrh   if( rc==SQLITE_OK ){
2893edea4a7cSdrh     rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
2894edea4a7cSdrh   }
28958f941bc7Sdrh   /* Following a rollback, the database file should be back in its original
28968f941bc7Sdrh   ** state prior to the start of the transaction, so invoke the
28978f941bc7Sdrh   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
28988f941bc7Sdrh   ** assertion that the transaction counter was modified.
28998f941bc7Sdrh   */
2900c02372ceSdrh #ifdef SQLITE_DEBUG
2901c02372ceSdrh   sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
2902c02372ceSdrh #endif
29038f941bc7Sdrh 
2904db340397Sdanielk1977   /* If this playback is happening automatically as a result of an IO or
2905be217793Sshane   ** malloc error that occurred after the change-counter was updated but
2906db340397Sdanielk1977   ** before the transaction was committed, then the change-counter
2907db340397Sdanielk1977   ** modification may just have been reverted. If this happens in exclusive
2908db340397Sdanielk1977   ** mode, then subsequent transactions performed by the connection will not
2909db340397Sdanielk1977   ** update the change-counter at all. This may lead to cache inconsistency
2910db340397Sdanielk1977   ** problems for other processes at some point in the future. So, just
2911db340397Sdanielk1977   ** in case this has happened, clear the changeCountDone flag now.
2912db340397Sdanielk1977   */
2913bea2a948Sdanielk1977   pPager->changeCountDone = pPager->tempFile;
2914db340397Sdanielk1977 
29158191bff0Sdanielk1977   if( rc==SQLITE_OK ){
29162e3cb138Sdan     /* Leave 4 bytes of space before the super-journal filename in memory.
29172e3cb138Sdan     ** This is because it may end up being passed to sqlite3OsOpen(), in
29182e3cb138Sdan     ** which case it requires 4 0x00 bytes in memory immediately before
29192e3cb138Sdan     ** the filename. */
29202e3cb138Sdan     zSuper = &pPager->pTmpSpace[4];
2921067b92baSdrh     rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
2922bea2a948Sdanielk1977     testcase( rc!=SQLITE_OK );
292365839c6aSdanielk1977   }
2924354bfe03Sdan   if( rc==SQLITE_OK
29257e684238Sdan    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
29267e684238Sdan   ){
2927999cd08aSdan     rc = sqlite3PagerSync(pPager, 0);
29287c24610eSdan   }
292965839c6aSdanielk1977   if( rc==SQLITE_OK ){
2930067b92baSdrh     rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0);
2931bea2a948Sdanielk1977     testcase( rc!=SQLITE_OK );
29328191bff0Sdanielk1977   }
2933067b92baSdrh   if( rc==SQLITE_OK && zSuper[0] && res ){
2934067b92baSdrh     /* If there was a super-journal and this routine will return success,
2935067b92baSdrh     ** see if it is possible to delete the super-journal.
293613adf8a0Sdanielk1977     */
29372e3cb138Sdan     assert( zSuper==&pPager->pTmpSpace[4] );
29382e3cb138Sdan     memset(&zSuper[-4], 0, 4);
2939067b92baSdrh     rc = pager_delsuper(pPager, zSuper);
2940bea2a948Sdanielk1977     testcase( rc!=SQLITE_OK );
294113adf8a0Sdanielk1977   }
2942ab755ac8Sdrh   if( isHot && nPlayback ){
2943d040e764Sdrh     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
2944ab755ac8Sdrh                 nPlayback, pPager->zJournal);
2945ab755ac8Sdrh   }
29467657240aSdanielk1977 
29477657240aSdanielk1977   /* The Pager.sectorSize variable may have been updated while rolling
29483ceeb756Sdrh   ** back a journal created by a process with a different sector size
29497657240aSdanielk1977   ** value. Reset it to the correct value for this process.
29507657240aSdanielk1977   */
2951c80f058dSdrh   setSectorSize(pPager);
2952d9b0257aSdrh   return rc;
2953ed7c855cSdrh }
2954ed7c855cSdrh 
29557c24610eSdan 
29567c24610eSdan /*
295756520ab8Sdrh ** Read the content for page pPg out of the database file (or out of
295856520ab8Sdrh ** the WAL if that is where the most recent copy if found) into
29597c24610eSdan ** pPg->pData. A shared lock or greater must be held on the database
29607c24610eSdan ** file before this function is called.
29617c24610eSdan **
29627c24610eSdan ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
29637c24610eSdan ** the value read from the database file.
29647c24610eSdan **
29657c24610eSdan ** If an IO error occurs, then the IO error is returned to the caller.
29667c24610eSdan ** Otherwise, SQLITE_OK is returned.
29677c24610eSdan */
readDbPage(PgHdr * pPg)296856520ab8Sdrh static int readDbPage(PgHdr *pPg){
29697c24610eSdan   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
2970622194c0Sdrh   int rc = SQLITE_OK;          /* Return code */
29715f54e2b5Sdan 
29725f54e2b5Sdan #ifndef SQLITE_OMIT_WAL
297356520ab8Sdrh   u32 iFrame = 0;              /* Frame of WAL containing pgno */
29747c24610eSdan 
2975d0864087Sdan   assert( pPager->eState>=PAGER_READER && !MEMDB );
29767c24610eSdan   assert( isOpen(pPager->fd) );
29777c24610eSdan 
297856520ab8Sdrh   if( pagerUseWal(pPager) ){
2979251866d0Sdrh     rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
298056520ab8Sdrh     if( rc ) return rc;
298156520ab8Sdrh   }
298299bd1097Sdan   if( iFrame ){
2983251866d0Sdrh     rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
29845f54e2b5Sdan   }else
29855f54e2b5Sdan #endif
29865f54e2b5Sdan   {
2987251866d0Sdrh     i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
2988251866d0Sdrh     rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
29897c24610eSdan     if( rc==SQLITE_IOERR_SHORT_READ ){
29907c24610eSdan       rc = SQLITE_OK;
29917c24610eSdan     }
29927c24610eSdan   }
29937c24610eSdan 
2994251866d0Sdrh   if( pPg->pgno==1 ){
29957c24610eSdan     if( rc ){
29967c24610eSdan       /* If the read is unsuccessful, set the dbFileVers[] to something
29977c24610eSdan       ** that will never be a valid file version.  dbFileVers[] is a copy
29987c24610eSdan       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
2999b28e59bbSdrh       ** zero or the size of the database in page. Bytes 32..35 and 35..39
3000b28e59bbSdrh       ** should be page numbers which are never 0xffffffff.  So filling
3001b28e59bbSdrh       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
30027c24610eSdan       **
30037c24610eSdan       ** For an encrypted database, the situation is more complex:  bytes
30047c24610eSdan       ** 24..39 of the database are white noise.  But the probability of
3005113762a2Sdrh       ** white noise equaling 16 bytes of 0xff is vanishingly small so
30067c24610eSdan       ** we should still be ok.
30077c24610eSdan       */
30087c24610eSdan       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
30097c24610eSdan     }else{
30107c24610eSdan       u8 *dbFileVers = &((u8*)pPg->pData)[24];
30117c24610eSdan       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
30127c24610eSdan     }
30137c24610eSdan   }
30147c24610eSdan   PAGER_INCR(sqlite3_pager_readdb_count);
30157c24610eSdan   PAGER_INCR(pPager->nRead);
3016251866d0Sdrh   IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
30177c24610eSdan   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
3018251866d0Sdrh                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
30197c24610eSdan 
30207c24610eSdan   return rc;
30217c24610eSdan }
30227c24610eSdan 
30236d311fb0Sdan /*
30246d311fb0Sdan ** Update the value of the change-counter at offsets 24 and 92 in
30256d311fb0Sdan ** the header and the sqlite version number at offset 96.
30266d311fb0Sdan **
30276d311fb0Sdan ** This is an unconditional update.  See also the pager_incr_changecounter()
30286d311fb0Sdan ** routine which only updates the change-counter if the update is actually
30296d311fb0Sdan ** needed, as determined by the pPager->changeCountDone state variable.
30306d311fb0Sdan */
pager_write_changecounter(PgHdr * pPg)30316d311fb0Sdan static void pager_write_changecounter(PgHdr *pPg){
30326d311fb0Sdan   u32 change_counter;
3033aa6fe5bfSdrh   if( NEVER(pPg==0) ) return;
30346d311fb0Sdan 
30356d311fb0Sdan   /* Increment the value just read and write it back to byte 24. */
30366d311fb0Sdan   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
30376d311fb0Sdan   put32bits(((char*)pPg->pData)+24, change_counter);
30386d311fb0Sdan 
30396d311fb0Sdan   /* Also store the SQLite version number in bytes 96..99 and in
30406d311fb0Sdan   ** bytes 92..95 store the change counter for which the version number
30416d311fb0Sdan   ** is valid. */
30426d311fb0Sdan   put32bits(((char*)pPg->pData)+92, change_counter);
30436d311fb0Sdan   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
30446d311fb0Sdan }
30456d311fb0Sdan 
30465cf53537Sdan #ifndef SQLITE_OMIT_WAL
30473306c4a9Sdan /*
304874d6cd88Sdan ** This function is invoked once for each page that has already been
304974d6cd88Sdan ** written into the log file when a WAL transaction is rolled back.
305074d6cd88Sdan ** Parameter iPg is the page number of said page. The pCtx argument
305174d6cd88Sdan ** is actually a pointer to the Pager structure.
30523306c4a9Sdan **
305374d6cd88Sdan ** If page iPg is present in the cache, and has no outstanding references,
305474d6cd88Sdan ** it is discarded. Otherwise, if there are one or more outstanding
305574d6cd88Sdan ** references, the page content is reloaded from the database. If the
305674d6cd88Sdan ** attempt to reload content from the database is required and fails,
305774d6cd88Sdan ** return an SQLite error code. Otherwise, SQLITE_OK.
305874d6cd88Sdan */
pagerUndoCallback(void * pCtx,Pgno iPg)305974d6cd88Sdan static int pagerUndoCallback(void *pCtx, Pgno iPg){
306074d6cd88Sdan   int rc = SQLITE_OK;
306174d6cd88Sdan   Pager *pPager = (Pager *)pCtx;
306274d6cd88Sdan   PgHdr *pPg;
306374d6cd88Sdan 
3064092d993cSdrh   assert( pagerUseWal(pPager) );
306574d6cd88Sdan   pPg = sqlite3PagerLookup(pPager, iPg);
306674d6cd88Sdan   if( pPg ){
306774d6cd88Sdan     if( sqlite3PcachePageRefcount(pPg)==1 ){
306874d6cd88Sdan       sqlite3PcacheDrop(pPg);
306974d6cd88Sdan     }else{
307056520ab8Sdrh       rc = readDbPage(pPg);
307174d6cd88Sdan       if( rc==SQLITE_OK ){
307274d6cd88Sdan         pPager->xReiniter(pPg);
307374d6cd88Sdan       }
3074da8a330aSdrh       sqlite3PagerUnrefNotNull(pPg);
307574d6cd88Sdan     }
307674d6cd88Sdan   }
307774d6cd88Sdan 
30784c97b534Sdan   /* Normally, if a transaction is rolled back, any backup processes are
30794c97b534Sdan   ** updated as data is copied out of the rollback journal and into the
30804c97b534Sdan   ** database. This is not generally possible with a WAL database, as
30814c97b534Sdan   ** rollback involves simply truncating the log file. Therefore, if one
30824c97b534Sdan   ** or more frames have already been written to the log (and therefore
30834c97b534Sdan   ** also copied into the backup databases) as part of this transaction,
30844c97b534Sdan   ** the backups must be restarted.
30854c97b534Sdan   */
30864c97b534Sdan   sqlite3BackupRestart(pPager->pBackup);
30874c97b534Sdan 
308874d6cd88Sdan   return rc;
308974d6cd88Sdan }
309074d6cd88Sdan 
309174d6cd88Sdan /*
309274d6cd88Sdan ** This function is called to rollback a transaction on a WAL database.
30933306c4a9Sdan */
pagerRollbackWal(Pager * pPager)30947ed91f23Sdrh static int pagerRollbackWal(Pager *pPager){
309574d6cd88Sdan   int rc;                         /* Return Code */
309674d6cd88Sdan   PgHdr *pList;                   /* List of dirty pages to revert */
30973306c4a9Sdan 
309874d6cd88Sdan   /* For all pages in the cache that are currently dirty or have already
309974d6cd88Sdan   ** been written (but not committed) to the log file, do one of the
310074d6cd88Sdan   ** following:
310174d6cd88Sdan   **
310274d6cd88Sdan   **   + Discard the cached page (if refcount==0), or
310374d6cd88Sdan   **   + Reload page content from the database (if refcount>0).
310474d6cd88Sdan   */
31057c24610eSdan   pPager->dbSize = pPager->dbOrigSize;
31067ed91f23Sdrh   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
310774d6cd88Sdan   pList = sqlite3PcacheDirtyList(pPager->pPCache);
31087c24610eSdan   while( pList && rc==SQLITE_OK ){
31097c24610eSdan     PgHdr *pNext = pList->pDirty;
311074d6cd88Sdan     rc = pagerUndoCallback((void *)pPager, pList->pgno);
31117c24610eSdan     pList = pNext;
31127c24610eSdan   }
311374d6cd88Sdan 
31147c24610eSdan   return rc;
31157c24610eSdan }
31167c24610eSdan 
3117ed7c855cSdrh /*
31185cf53537Sdan ** This function is a wrapper around sqlite3WalFrames(). As well as logging
31195cf53537Sdan ** the contents of the list of pages headed by pList (connected by pDirty),
31205cf53537Sdan ** this function notifies any active backup processes that the pages have
31215cf53537Sdan ** changed.
3122104a7bbaSdrh **
3123104a7bbaSdrh ** The list of pages passed into this routine is always sorted by page number.
3124104a7bbaSdrh ** Hence, if page 1 appears anywhere on the list, it will be the first page.
31255cf53537Sdan */
pagerWalFrames(Pager * pPager,PgHdr * pList,Pgno nTruncate,int isCommit)31265cf53537Sdan static int pagerWalFrames(
31275cf53537Sdan   Pager *pPager,                  /* Pager object */
31285cf53537Sdan   PgHdr *pList,                   /* List of frames to log */
31295cf53537Sdan   Pgno nTruncate,                 /* Database size after this commit */
31304eb02a45Sdrh   int isCommit                    /* True if this is a commit */
31315cf53537Sdan ){
31325cf53537Sdan   int rc;                         /* Return code */
31339ad3ee40Sdrh   int nList;                      /* Number of pages in pList */
3134104a7bbaSdrh   PgHdr *p;                       /* For looping over pages */
31355cf53537Sdan 
31365cf53537Sdan   assert( pPager->pWal );
3137b07028f7Sdrh   assert( pList );
3138104a7bbaSdrh #ifdef SQLITE_DEBUG
3139104a7bbaSdrh   /* Verify that the page list is in accending order */
3140104a7bbaSdrh   for(p=pList; p && p->pDirty; p=p->pDirty){
3141104a7bbaSdrh     assert( p->pgno < p->pDirty->pgno );
3142104a7bbaSdrh   }
3143104a7bbaSdrh #endif
3144104a7bbaSdrh 
31459ad3ee40Sdrh   assert( pList->pDirty==0 || isCommit );
3146ce8e5ffeSdan   if( isCommit ){
3147ce8e5ffeSdan     /* If a WAL transaction is being committed, there is no point in writing
3148ce8e5ffeSdan     ** any pages with page numbers greater than nTruncate into the WAL file.
3149ce8e5ffeSdan     ** They will never be read by any client. So remove them from the pDirty
3150ce8e5ffeSdan     ** list here. */
3151ce8e5ffeSdan     PgHdr **ppNext = &pList;
31529ad3ee40Sdrh     nList = 0;
3153a4c5860eSdrh     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
31549ad3ee40Sdrh       if( p->pgno<=nTruncate ){
31559ad3ee40Sdrh         ppNext = &p->pDirty;
31569ad3ee40Sdrh         nList++;
31579ad3ee40Sdrh       }
3158ce8e5ffeSdan     }
3159ce8e5ffeSdan     assert( pList );
31609ad3ee40Sdrh   }else{
31619ad3ee40Sdrh     nList = 1;
3162ce8e5ffeSdan   }
31639ad3ee40Sdrh   pPager->aStat[PAGER_STAT_WRITE] += nList;
3164ce8e5ffeSdan 
316554a7347aSdrh   if( pList->pgno==1 ) pager_write_changecounter(pList);
31665cf53537Sdan   rc = sqlite3WalFrames(pPager->pWal,
31674eb02a45Sdrh       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
31685cf53537Sdan   );
31695cf53537Sdan   if( rc==SQLITE_OK && pPager->pBackup ){
31705cf53537Sdan     for(p=pList; p; p=p->pDirty){
31715cf53537Sdan       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
31725cf53537Sdan     }
31735cf53537Sdan   }
31745f848c3aSdan 
31755f848c3aSdan #ifdef SQLITE_CHECK_PAGES
3176ce8e5ffeSdan   pList = sqlite3PcacheDirtyList(pPager->pPCache);
3177104a7bbaSdrh   for(p=pList; p; p=p->pDirty){
3178104a7bbaSdrh     pager_set_pagehash(p);
31795f848c3aSdan   }
31805f848c3aSdan #endif
31815f848c3aSdan 
31825cf53537Sdan   return rc;
31835cf53537Sdan }
31845cf53537Sdan 
31855cf53537Sdan /*
318673b64e4dSdrh ** Begin a read transaction on the WAL.
318773b64e4dSdrh **
318873b64e4dSdrh ** This routine used to be called "pagerOpenSnapshot()" because it essentially
318973b64e4dSdrh ** makes a snapshot of the database at the current point in time and preserves
319073b64e4dSdrh ** that snapshot for use by the reader in spite of concurrently changes by
319173b64e4dSdrh ** other writers or checkpointers.
31925cf53537Sdan */
pagerBeginReadTransaction(Pager * pPager)319373b64e4dSdrh static int pagerBeginReadTransaction(Pager *pPager){
31945cf53537Sdan   int rc;                         /* Return code */
31955cf53537Sdan   int changed = 0;                /* True if cache must be reset */
31965cf53537Sdan 
31975cf53537Sdan   assert( pagerUseWal(pPager) );
3198de1ae34eSdan   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
31995cf53537Sdan 
320061e4acecSdrh   /* sqlite3WalEndReadTransaction() was not called for the previous
320161e4acecSdrh   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
320261e4acecSdrh   ** are in locking_mode=NORMAL and EndRead() was previously called,
320361e4acecSdrh   ** the duplicate call is harmless.
320461e4acecSdrh   */
320561e4acecSdrh   sqlite3WalEndReadTransaction(pPager->pWal);
320661e4acecSdrh 
320773b64e4dSdrh   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
320892683f54Sdrh   if( rc!=SQLITE_OK || changed ){
32095cf53537Sdan     pager_reset(pPager);
3210188d4884Sdrh     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
32115cf53537Sdan   }
32125cf53537Sdan 
32135cf53537Sdan   return rc;
32145cf53537Sdan }
32159091f775Sshaneh #endif
32165cf53537Sdan 
3217763afe62Sdan /*
321885d14ed2Sdan ** This function is called as part of the transition from PAGER_OPEN
321985d14ed2Sdan ** to PAGER_READER state to determine the size of the database file
322085d14ed2Sdan ** in pages (assuming the page size currently stored in Pager.pageSize).
322185d14ed2Sdan **
322285d14ed2Sdan ** If no error occurs, SQLITE_OK is returned and the size of the database
322385d14ed2Sdan ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
322485d14ed2Sdan ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
3225763afe62Sdan */
pagerPagecount(Pager * pPager,Pgno * pnPage)3226763afe62Sdan static int pagerPagecount(Pager *pPager, Pgno *pnPage){
3227763afe62Sdan   Pgno nPage;                     /* Value to return via *pnPage */
3228763afe62Sdan 
322985d14ed2Sdan   /* Query the WAL sub-system for the database size. The WalDbsize()
323085d14ed2Sdan   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
323185d14ed2Sdan   ** if the database size is not available. The database size is not
323285d14ed2Sdan   ** available from the WAL sub-system if the log file is empty or
323385d14ed2Sdan   ** contains no valid committed transactions.
323485d14ed2Sdan   */
3235de1ae34eSdan   assert( pPager->eState==PAGER_OPEN );
323633f111dcSdrh   assert( pPager->eLock>=SHARED_LOCK );
3237835f22deSdrh   assert( isOpen(pPager->fd) );
3238835f22deSdrh   assert( pPager->tempFile==0 );
3239763afe62Sdan   nPage = sqlite3WalDbsize(pPager->pWal);
324085d14ed2Sdan 
3241af80a1c8Sdrh   /* If the number of pages in the database is not available from the
32428abc54e2Sdrh   ** WAL sub-system, determine the page count based on the size of
3243af80a1c8Sdrh   ** the database file.  If the size of the database file is not an
3244af80a1c8Sdrh   ** integer multiple of the page-size, round up the result.
324585d14ed2Sdan   */
3246835f22deSdrh   if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
3247763afe62Sdan     i64 n = 0;                    /* Size of db file in bytes */
3248763afe62Sdan     int rc = sqlite3OsFileSize(pPager->fd, &n);
3249763afe62Sdan     if( rc!=SQLITE_OK ){
3250763afe62Sdan       return rc;
3251763afe62Sdan     }
3252935de7e8Sdrh     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
3253763afe62Sdan   }
3254937ac9daSdan 
3255937ac9daSdan   /* If the current number of pages in the file is greater than the
3256937ac9daSdan   ** configured maximum pager number, increase the allowed limit so
3257937ac9daSdan   ** that the file can be read.
3258937ac9daSdan   */
3259937ac9daSdan   if( nPage>pPager->mxPgno ){
3260937ac9daSdan     pPager->mxPgno = (Pgno)nPage;
3261937ac9daSdan   }
3262937ac9daSdan 
3263763afe62Sdan   *pnPage = nPage;
3264763afe62Sdan   return SQLITE_OK;
3265763afe62Sdan }
3266763afe62Sdan 
32679091f775Sshaneh #ifndef SQLITE_OMIT_WAL
32685cf53537Sdan /*
32695cf53537Sdan ** Check if the *-wal file that corresponds to the database opened by pPager
327032f29643Sdrh ** exists if the database is not empy, or verify that the *-wal file does
327132f29643Sdrh ** not exist (by deleting it) if the database file is empty.
327232f29643Sdrh **
327332f29643Sdrh ** If the database is not empty and the *-wal file exists, open the pager
327432f29643Sdrh ** in WAL mode.  If the database is empty or if no *-wal file exists and
327532f29643Sdrh ** if no error occurs, make sure Pager.journalMode is not set to
327632f29643Sdrh ** PAGER_JOURNALMODE_WAL.
327732f29643Sdrh **
327832f29643Sdrh ** Return SQLITE_OK or an error code.
32795cf53537Sdan **
32805cf53537Sdan ** The caller must hold a SHARED lock on the database file to call this
32815cf53537Sdan ** function. Because an EXCLUSIVE lock on the db file is required to delete
328232f29643Sdrh ** a WAL on a none-empty database, this ensures there is no race condition
328332f29643Sdrh ** between the xAccess() below and an xDelete() being executed by some
328432f29643Sdrh ** other connection.
32855cf53537Sdan */
pagerOpenWalIfPresent(Pager * pPager)32865cf53537Sdan static int pagerOpenWalIfPresent(Pager *pPager){
32875cf53537Sdan   int rc = SQLITE_OK;
328885d14ed2Sdan   assert( pPager->eState==PAGER_OPEN );
328933f111dcSdrh   assert( pPager->eLock>=SHARED_LOCK );
329085d14ed2Sdan 
32915cf53537Sdan   if( !pPager->tempFile ){
32925cf53537Sdan     int isWal;                    /* True if WAL file exists */
329377f6af2bSdrh     rc = sqlite3OsAccess(
329477f6af2bSdrh         pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
329577f6af2bSdrh     );
329677f6af2bSdrh     if( rc==SQLITE_OK ){
329777f6af2bSdrh       if( isWal ){
3298763afe62Sdan         Pgno nPage;                   /* Size of the database file */
3299d0864087Sdan 
3300763afe62Sdan         rc = pagerPagecount(pPager, &nPage);
330132f29643Sdrh         if( rc ) return rc;
330232f29643Sdrh         if( nPage==0 ){
3303db10f082Sdan           rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
330432f29643Sdrh         }else{
33054e004aa6Sdan           testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
33065cf53537Sdan           rc = sqlite3PagerOpenWal(pPager, 0);
330777f6af2bSdrh         }
33085cf53537Sdan       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
33095cf53537Sdan         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
33105cf53537Sdan       }
33115cf53537Sdan     }
33125cf53537Sdan   }
33135cf53537Sdan   return rc;
33145cf53537Sdan }
33155cf53537Sdan #endif
33165cf53537Sdan 
33175cf53537Sdan /*
3318d6e5e098Sdrh ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
3319067b92baSdrh ** the entire super-journal file. The case pSavepoint==NULL occurs when
3320bea2a948Sdanielk1977 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
3321bea2a948Sdanielk1977 ** savepoint.
3322d6e5e098Sdrh **
3323bea2a948Sdanielk1977 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
3324bea2a948Sdanielk1977 ** being rolled back), then the rollback consists of up to three stages,
3325bea2a948Sdanielk1977 ** performed in the order specified:
3326bea2a948Sdanielk1977 **
3327bea2a948Sdanielk1977 **   * Pages are played back from the main journal starting at byte
3328bea2a948Sdanielk1977 **     offset PagerSavepoint.iOffset and continuing to
3329bea2a948Sdanielk1977 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
3330bea2a948Sdanielk1977 **     file if PagerSavepoint.iHdrOffset is zero.
3331bea2a948Sdanielk1977 **
3332bea2a948Sdanielk1977 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
3333bea2a948Sdanielk1977 **     back starting from the journal header immediately following
3334bea2a948Sdanielk1977 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
3335bea2a948Sdanielk1977 **
3336bea2a948Sdanielk1977 **   * Pages are then played back from the sub-journal file, starting
3337bea2a948Sdanielk1977 **     with the PagerSavepoint.iSubRec and continuing to the end of
3338bea2a948Sdanielk1977 **     the journal file.
3339bea2a948Sdanielk1977 **
3340bea2a948Sdanielk1977 ** Throughout the rollback process, each time a page is rolled back, the
3341bea2a948Sdanielk1977 ** corresponding bit is set in a bitvec structure (variable pDone in the
3342bea2a948Sdanielk1977 ** implementation below). This is used to ensure that a page is only
3343bea2a948Sdanielk1977 ** rolled back the first time it is encountered in either journal.
3344bea2a948Sdanielk1977 **
3345bea2a948Sdanielk1977 ** If pSavepoint is NULL, then pages are only played back from the main
3346bea2a948Sdanielk1977 ** journal file. There is no need for a bitvec in this case.
3347bea2a948Sdanielk1977 **
3348bea2a948Sdanielk1977 ** In either case, before playback commences the Pager.dbSize variable
3349bea2a948Sdanielk1977 ** is reset to the value that it held at the start of the savepoint
3350bea2a948Sdanielk1977 ** (or transaction). No page with a page-number greater than this value
3351bea2a948Sdanielk1977 ** is played back. If one is encountered it is simply skipped.
3352fa86c412Sdrh */
pagerPlaybackSavepoint(Pager * pPager,PagerSavepoint * pSavepoint)3353fd7f0452Sdanielk1977 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
3354d6e5e098Sdrh   i64 szJ;                 /* Effective size of the main journal */
3355fd7f0452Sdanielk1977   i64 iHdrOff;             /* End of first segment of main-journal records */
3356f2c31ad8Sdanielk1977   int rc = SQLITE_OK;      /* Return code */
3357fd7f0452Sdanielk1977   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
3358fa86c412Sdrh 
3359a42c66bdSdan   assert( pPager->eState!=PAGER_ERROR );
3360de1ae34eSdan   assert( pPager->eState>=PAGER_WRITER_LOCKED );
3361bea2a948Sdanielk1977 
3362fd7f0452Sdanielk1977   /* Allocate a bitvec to use to store the set of pages rolled back */
3363fd7f0452Sdanielk1977   if( pSavepoint ){
3364fd7f0452Sdanielk1977     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
3365fd7f0452Sdanielk1977     if( !pDone ){
3366fad3039cSmistachkin       return SQLITE_NOMEM_BKPT;
3367fd7f0452Sdanielk1977     }
33687657240aSdanielk1977   }
33697657240aSdanielk1977 
3370bea2a948Sdanielk1977   /* Set the database size back to the value it was before the savepoint
3371bea2a948Sdanielk1977   ** being reverted was opened.
3372fa86c412Sdrh   */
3373f2c31ad8Sdanielk1977   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
3374ab7e8d85Sdan   pPager->changeCountDone = pPager->tempFile;
3375fa86c412Sdrh 
33767ed91f23Sdrh   if( !pSavepoint && pagerUseWal(pPager) ){
33777ed91f23Sdrh     return pagerRollbackWal(pPager);
33787c24610eSdan   }
33797c24610eSdan 
3380d6e5e098Sdrh   /* Use pPager->journalOff as the effective size of the main rollback
3381d6e5e098Sdrh   ** journal.  The actual file might be larger than this in
3382d6e5e098Sdrh   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
3383d6e5e098Sdrh   ** past pPager->journalOff is off-limits to us.
3384fa86c412Sdrh   */
3385fd7f0452Sdanielk1977   szJ = pPager->journalOff;
33867ed91f23Sdrh   assert( pagerUseWal(pPager)==0 || szJ==0 );
3387d6e5e098Sdrh 
3388d6e5e098Sdrh   /* Begin by rolling back records from the main journal starting at
3389d6e5e098Sdrh   ** PagerSavepoint.iOffset and continuing to the next journal header.
3390d6e5e098Sdrh   ** There might be records in the main journal that have a page number
3391d6e5e098Sdrh   ** greater than the current database size (pPager->dbSize) but those
3392d6e5e098Sdrh   ** will be skipped automatically.  Pages are added to pDone as they
3393d6e5e098Sdrh   ** are played back.
3394d6e5e098Sdrh   */
33957ed91f23Sdrh   if( pSavepoint && !pagerUseWal(pPager) ){
3396fd7f0452Sdanielk1977     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
3397fd7f0452Sdanielk1977     pPager->journalOff = pSavepoint->iOffset;
3398fd7f0452Sdanielk1977     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
339991781bd7Sdrh       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
340045d6882fSdanielk1977     }
3401bea2a948Sdanielk1977     assert( rc!=SQLITE_DONE );
3402fd7f0452Sdanielk1977   }else{
3403fd7f0452Sdanielk1977     pPager->journalOff = 0;
34047657240aSdanielk1977   }
3405d6e5e098Sdrh 
3406d6e5e098Sdrh   /* Continue rolling back records out of the main journal starting at
3407d6e5e098Sdrh   ** the first journal header seen and continuing until the effective end
3408d6e5e098Sdrh   ** of the main journal file.  Continue to skip out-of-range pages and
3409d6e5e098Sdrh   ** continue adding pages rolled back to pDone.
3410d6e5e098Sdrh   */
3411fd7f0452Sdanielk1977   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
3412bea2a948Sdanielk1977     u32 ii;            /* Loop counter */
3413c81806f3Sdanielk1977     u32 nJRec = 0;     /* Number of Journal Records */
34147657240aSdanielk1977     u32 dummy;
34156f4c73eeSdanielk1977     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
3416968af52aSdrh     assert( rc!=SQLITE_DONE );
3417d6e5e098Sdrh 
3418d6e5e098Sdrh     /*
3419d6e5e098Sdrh     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
3420d6e5e098Sdrh     ** test is related to ticket #2565.  See the discussion in the
3421d6e5e098Sdrh     ** pager_playback() function for additional information.
3422d6e5e098Sdrh     */
3423d6e5e098Sdrh     if( nJRec==0
3424d6e5e098Sdrh      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
3425d6e5e098Sdrh     ){
3426d87897dfSshane       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
342775edc16fSdanielk1977     }
342812dd5496Sdanielk1977     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
342991781bd7Sdrh       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
3430fd7f0452Sdanielk1977     }
3431bea2a948Sdanielk1977     assert( rc!=SQLITE_DONE );
343245d6882fSdanielk1977   }
343339cf5109Sdrh   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
3434fd7f0452Sdanielk1977 
3435d6e5e098Sdrh   /* Finally,  rollback pages from the sub-journal.  Page that were
3436d6e5e098Sdrh   ** previously rolled back out of the main journal (and are hence in pDone)
3437d6e5e098Sdrh   ** will be skipped.  Out-of-range pages are also skipped.
3438d6e5e098Sdrh   */
3439fd7f0452Sdanielk1977   if( pSavepoint ){
3440bea2a948Sdanielk1977     u32 ii;            /* Loop counter */
34417c3210e6Sdan     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
34424cd78b4dSdan 
34437ed91f23Sdrh     if( pagerUseWal(pPager) ){
344471d89919Sdan       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
34454cd78b4dSdan     }
3446bea2a948Sdanielk1977     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
34477c3210e6Sdan       assert( offset==(i64)ii*(4+pPager->pageSize) );
344891781bd7Sdrh       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
34497657240aSdanielk1977     }
3450bea2a948Sdanielk1977     assert( rc!=SQLITE_DONE );
345145d6882fSdanielk1977   }
34527657240aSdanielk1977 
3453fd7f0452Sdanielk1977   sqlite3BitvecDestroy(pDone);
34548a7aea3bSdanielk1977   if( rc==SQLITE_OK ){
345575edc16fSdanielk1977     pPager->journalOff = szJ;
3456fa86c412Sdrh   }
34574cd78b4dSdan 
3458fa86c412Sdrh   return rc;
3459fa86c412Sdrh }
3460fa86c412Sdrh 
3461fa86c412Sdrh /*
34629b0cf34fSdrh ** Change the maximum number of in-memory pages that are allowed
34639b0cf34fSdrh ** before attempting to recycle clean and unused pages.
3464f57b14a6Sdrh */
sqlite3PagerSetCachesize(Pager * pPager,int mxPage)34653b8a05f6Sdanielk1977 void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
34668c0a791aSdanielk1977   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
3467f57b14a6Sdrh }
3468f57b14a6Sdrh 
3469f57b14a6Sdrh /*
34709b0cf34fSdrh ** Change the maximum number of in-memory pages that are allowed
34719b0cf34fSdrh ** before attempting to spill pages to journal.
34729b0cf34fSdrh */
sqlite3PagerSetSpillsize(Pager * pPager,int mxPage)34739b0cf34fSdrh int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
34749b0cf34fSdrh   return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
34759b0cf34fSdrh }
34769b0cf34fSdrh 
34779b0cf34fSdrh /*
34789b4c59faSdrh ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
34795d8a1372Sdan */
pagerFixMaplimit(Pager * pPager)34805d8a1372Sdan static void pagerFixMaplimit(Pager *pPager){
34819b4c59faSdrh #if SQLITE_MAX_MMAP_SIZE>0
3482f23da966Sdan   sqlite3_file *fd = pPager->fd;
3483789efdb9Sdan   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
34849b4c59faSdrh     sqlite3_int64 sz;
34859b4c59faSdrh     sz = pPager->szMmap;
3486789efdb9Sdan     pPager->bUseFetch = (sz>0);
348712e6f682Sdrh     setGetterMethod(pPager);
34889b4c59faSdrh     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
3489f23da966Sdan   }
3490188d4884Sdrh #endif
34915d8a1372Sdan }
34925d8a1372Sdan 
34935d8a1372Sdan /*
34945d8a1372Sdan ** Change the maximum size of any memory mapping made of the database file.
34955d8a1372Sdan */
sqlite3PagerSetMmapLimit(Pager * pPager,sqlite3_int64 szMmap)34969b4c59faSdrh void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
34979b4c59faSdrh   pPager->szMmap = szMmap;
34985d8a1372Sdan   pagerFixMaplimit(pPager);
34995d8a1372Sdan }
35005d8a1372Sdan 
35015d8a1372Sdan /*
350209419b4bSdrh ** Free as much memory as possible from the pager.
350309419b4bSdrh */
sqlite3PagerShrink(Pager * pPager)350409419b4bSdrh void sqlite3PagerShrink(Pager *pPager){
350509419b4bSdrh   sqlite3PcacheShrink(pPager->pPCache);
350609419b4bSdrh }
350709419b4bSdrh 
350809419b4bSdrh /*
350940c3941cSdrh ** Adjust settings of the pager to those specified in the pgFlags parameter.
351040c3941cSdrh **
351140c3941cSdrh ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
351240c3941cSdrh ** of the database to damage due to OS crashes or power failures by
351340c3941cSdrh ** changing the number of syncs()s when writing the journals.
35140dba3304Sdrh ** There are four levels:
3515973b6e33Sdrh **
3516054889ecSdrh **    OFF       sqlite3OsSync() is never called.  This is the default
3517973b6e33Sdrh **              for temporary and transient files.
3518973b6e33Sdrh **
3519973b6e33Sdrh **    NORMAL    The journal is synced once before writes begin on the
3520973b6e33Sdrh **              database.  This is normally adequate protection, but
3521973b6e33Sdrh **              it is theoretically possible, though very unlikely,
3522973b6e33Sdrh **              that an inopertune power failure could leave the journal
3523973b6e33Sdrh **              in a state which would cause damage to the database
3524973b6e33Sdrh **              when it is rolled back.
3525973b6e33Sdrh **
3526973b6e33Sdrh **    FULL      The journal is synced twice before writes begin on the
352734e79ceeSdrh **              database (with some additional information - the nRec field
352834e79ceeSdrh **              of the journal header - being written in between the two
352934e79ceeSdrh **              syncs).  If we assume that writing a
3530973b6e33Sdrh **              single disk sector is atomic, then this mode provides
3531973b6e33Sdrh **              assurance that the journal will not be corrupted to the
3532973b6e33Sdrh **              point of causing damage to the database during rollback.
3533973b6e33Sdrh **
35340dba3304Sdrh **    EXTRA     This is like FULL except that is also syncs the directory
35350dba3304Sdrh **              that contains the rollback journal after the rollback
35360dba3304Sdrh **              journal is unlinked.
35370dba3304Sdrh **
3538c97d8463Sdrh ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
3539c97d8463Sdrh ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
3540c97d8463Sdrh ** prior to the start of checkpoint and that the database file is synced
3541c97d8463Sdrh ** at the conclusion of the checkpoint if the entire content of the WAL
3542c97d8463Sdrh ** was written back into the database.  But no sync operations occur for
3543c97d8463Sdrh ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
3544c97d8463Sdrh ** file is synced following each commit operation, in addition to the
35450dba3304Sdrh ** syncs associated with NORMAL.  There is no difference between FULL
35460dba3304Sdrh ** and EXTRA for WAL mode.
3547c97d8463Sdrh **
3548c97d8463Sdrh ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
3549c97d8463Sdrh ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
3550c97d8463Sdrh ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
3551c97d8463Sdrh ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
3552c97d8463Sdrh ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
3553c97d8463Sdrh ** synchronous=FULL versus synchronous=NORMAL setting determines when
3554c97d8463Sdrh ** the xSync primitive is called and is relevant to all platforms.
3555c97d8463Sdrh **
3556973b6e33Sdrh ** Numeric values associated with these states are OFF==1, NORMAL=2,
3557973b6e33Sdrh ** and FULL=3.
3558973b6e33Sdrh */
355993758c8dSdanielk1977 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
sqlite3PagerSetFlags(Pager * pPager,unsigned pgFlags)356040c3941cSdrh void sqlite3PagerSetFlags(
3561c97d8463Sdrh   Pager *pPager,        /* The pager to set safety level for */
356240c3941cSdrh   unsigned pgFlags      /* Various flags */
3563c97d8463Sdrh ){
356440c3941cSdrh   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
35656841b1cbSdrh   if( pPager->tempFile ){
35666841b1cbSdrh     pPager->noSync = 1;
35676841b1cbSdrh     pPager->fullSync = 0;
35686841b1cbSdrh     pPager->extraSync = 0;
35696841b1cbSdrh   }else{
35706841b1cbSdrh     pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
35716841b1cbSdrh     pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
35726841b1cbSdrh     pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
35736841b1cbSdrh   }
3574c97d8463Sdrh   if( pPager->noSync ){
3575c97d8463Sdrh     pPager->syncFlags = 0;
357640c3941cSdrh   }else if( pgFlags & PAGER_FULLFSYNC ){
3577c97d8463Sdrh     pPager->syncFlags = SQLITE_SYNC_FULL;
3578c97d8463Sdrh   }else{
3579c97d8463Sdrh     pPager->syncFlags = SQLITE_SYNC_NORMAL;
3580c97d8463Sdrh   }
3581daaae7b9Sdrh   pPager->walSyncFlags = (pPager->syncFlags<<2);
35824eb02a45Sdrh   if( pPager->fullSync ){
3583daaae7b9Sdrh     pPager->walSyncFlags |= pPager->syncFlags;
3584daaae7b9Sdrh   }
3585daaae7b9Sdrh   if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
3586daaae7b9Sdrh     pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
35874eb02a45Sdrh   }
358840c3941cSdrh   if( pgFlags & PAGER_CACHESPILL ){
358940c3941cSdrh     pPager->doNotSpill &= ~SPILLFLAG_OFF;
359040c3941cSdrh   }else{
359140c3941cSdrh     pPager->doNotSpill |= SPILLFLAG_OFF;
359240c3941cSdrh   }
3593973b6e33Sdrh }
359493758c8dSdanielk1977 #endif
3595973b6e33Sdrh 
3596973b6e33Sdrh /*
3597af6df11fSdrh ** The following global variable is incremented whenever the library
3598af6df11fSdrh ** attempts to open a temporary file.  This information is used for
3599af6df11fSdrh ** testing and analysis only.
3600af6df11fSdrh */
36010f7eb611Sdrh #ifdef SQLITE_TEST
3602af6df11fSdrh int sqlite3_opentemp_count = 0;
36030f7eb611Sdrh #endif
3604af6df11fSdrh 
3605af6df11fSdrh /*
36063f56e6ebSdrh ** Open a temporary file.
36073f56e6ebSdrh **
3608bea2a948Sdanielk1977 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
3609bea2a948Sdanielk1977 ** or some other error code if we fail. The OS will automatically
3610bea2a948Sdanielk1977 ** delete the temporary file when it is closed.
3611bea2a948Sdanielk1977 **
3612bea2a948Sdanielk1977 ** The flags passed to the VFS layer xOpen() call are those specified
3613bea2a948Sdanielk1977 ** by parameter vfsFlags ORed with the following:
3614bea2a948Sdanielk1977 **
3615bea2a948Sdanielk1977 **     SQLITE_OPEN_READWRITE
3616bea2a948Sdanielk1977 **     SQLITE_OPEN_CREATE
3617bea2a948Sdanielk1977 **     SQLITE_OPEN_EXCLUSIVE
3618bea2a948Sdanielk1977 **     SQLITE_OPEN_DELETEONCLOSE
3619fa86c412Sdrh */
pagerOpentemp(Pager * pPager,sqlite3_file * pFile,int vfsFlags)3620bea2a948Sdanielk1977 static int pagerOpentemp(
362117b90b53Sdanielk1977   Pager *pPager,        /* The pager object */
362233f4e02aSdrh   sqlite3_file *pFile,  /* Write the file descriptor here */
362333f4e02aSdrh   int vfsFlags          /* Flags passed through to the VFS */
3624b4b47411Sdanielk1977 ){
3625bea2a948Sdanielk1977   int rc;               /* Return code */
36263f56e6ebSdrh 
36270f7eb611Sdrh #ifdef SQLITE_TEST
3628af6df11fSdrh   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
36290f7eb611Sdrh #endif
3630b4b47411Sdanielk1977 
363133f4e02aSdrh   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
363233f4e02aSdrh             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
363317b90b53Sdanielk1977   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
3634bea2a948Sdanielk1977   assert( rc!=SQLITE_OK || isOpen(pFile) );
3635fa86c412Sdrh   return rc;
3636fa86c412Sdrh }
3637fa86c412Sdrh 
3638ed7c855cSdrh /*
363990f5ecb3Sdrh ** Set the busy handler function.
3640bea2a948Sdanielk1977 **
3641bea2a948Sdanielk1977 ** The pager invokes the busy-handler if sqlite3OsLock() returns
3642bea2a948Sdanielk1977 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
3643bea2a948Sdanielk1977 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
3644bea2a948Sdanielk1977 ** lock. It does *not* invoke the busy handler when upgrading from
3645bea2a948Sdanielk1977 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
3646bea2a948Sdanielk1977 ** (which occurs during hot-journal rollback). Summary:
3647bea2a948Sdanielk1977 **
3648bea2a948Sdanielk1977 **   Transition                        | Invokes xBusyHandler
3649bea2a948Sdanielk1977 **   --------------------------------------------------------
3650bea2a948Sdanielk1977 **   NO_LOCK       -> SHARED_LOCK      | Yes
3651bea2a948Sdanielk1977 **   SHARED_LOCK   -> RESERVED_LOCK    | No
3652bea2a948Sdanielk1977 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
3653bea2a948Sdanielk1977 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
3654bea2a948Sdanielk1977 **
3655bea2a948Sdanielk1977 ** If the busy-handler callback returns non-zero, the lock is
3656bea2a948Sdanielk1977 ** retried. If it returns zero, then the SQLITE_BUSY error is
3657bea2a948Sdanielk1977 ** returned to the caller of the pager API function.
365890f5ecb3Sdrh */
sqlite3PagerSetBusyHandler(Pager * pPager,int (* xBusyHandler)(void *),void * pBusyHandlerArg)365980262896Sdrh void sqlite3PagerSetBusyHandler(
3660bea2a948Sdanielk1977   Pager *pPager,                       /* Pager object */
3661bea2a948Sdanielk1977   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
3662bea2a948Sdanielk1977   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
36631ceedd37Sdanielk1977 ){
3664afb39a4cSdrh   void **ap;
36651ceedd37Sdanielk1977   pPager->xBusyHandler = xBusyHandler;
36661ceedd37Sdanielk1977   pPager->pBusyHandlerArg = pBusyHandlerArg;
3667afb39a4cSdrh   ap = (void **)&pPager->xBusyHandler;
366880bb6f82Sdan   assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
366980bb6f82Sdan   assert( ap[1]==pBusyHandlerArg );
367044c4fcb9Sdan   sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
367180bb6f82Sdan }
367290f5ecb3Sdrh 
367390f5ecb3Sdrh /*
3674bea2a948Sdanielk1977 ** Change the page size used by the Pager object. The new page size
3675bea2a948Sdanielk1977 ** is passed in *pPageSize.
3676bea2a948Sdanielk1977 **
3677bea2a948Sdanielk1977 ** If the pager is in the error state when this function is called, it
3678bea2a948Sdanielk1977 ** is a no-op. The value returned is the error state error code (i.e.
3679a81a2207Sdan ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
3680bea2a948Sdanielk1977 **
3681bea2a948Sdanielk1977 ** Otherwise, if all of the following are true:
3682bea2a948Sdanielk1977 **
3683bea2a948Sdanielk1977 **   * the new page size (value of *pPageSize) is valid (a power
3684bea2a948Sdanielk1977 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
3685bea2a948Sdanielk1977 **
3686bea2a948Sdanielk1977 **   * there are no outstanding page references, and
3687bea2a948Sdanielk1977 **
3688bea2a948Sdanielk1977 **   * the database is either not an in-memory database or it is
3689bea2a948Sdanielk1977 **     an in-memory database that currently consists of zero pages.
3690bea2a948Sdanielk1977 **
3691bea2a948Sdanielk1977 ** then the pager object page size is set to *pPageSize.
3692bea2a948Sdanielk1977 **
3693bea2a948Sdanielk1977 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
3694bea2a948Sdanielk1977 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
3695bea2a948Sdanielk1977 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
3696bea2a948Sdanielk1977 ** In all other cases, SQLITE_OK is returned.
3697bea2a948Sdanielk1977 **
3698bea2a948Sdanielk1977 ** If the page size is not changed, either because one of the enumerated
3699bea2a948Sdanielk1977 ** conditions above is not true, the pager was in error state when this
3700bea2a948Sdanielk1977 ** function was called, or because the memory allocation attempt failed,
3701bea2a948Sdanielk1977 ** then *pPageSize is set to the old, retained page size before returning.
370290f5ecb3Sdrh */
sqlite3PagerSetPagesize(Pager * pPager,u32 * pPageSize,int nReserve)3703b2eced5dSdrh int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
37041879b088Sdan   int rc = SQLITE_OK;
37051879b088Sdan 
3706a42c66bdSdan   /* It is not possible to do a full assert_pager_state() here, as this
3707a42c66bdSdan   ** function may be called from within PagerOpen(), before the state
3708a42c66bdSdan   ** of the Pager object is internally consistent.
370922b328b2Sdan   **
371022b328b2Sdan   ** At one point this function returned an error if the pager was in
371122b328b2Sdan   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
371222b328b2Sdan   ** there is at least one outstanding page reference, this function
371322b328b2Sdan   ** is a no-op for that case anyhow.
3714a42c66bdSdan   */
3715a42c66bdSdan 
3716b2eced5dSdrh   u32 pageSize = *pPageSize;
37179663b8f9Sdanielk1977   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
37188a938f98Sdrh   if( (pPager->memDb==0 || pPager->dbSize==0)
37197426f864Sdrh    && sqlite3PcacheRefCount(pPager->pPCache)==0
372043b18e1eSdrh    && pageSize && pageSize!=(u32)pPager->pageSize
3721a1644fd8Sdanielk1977   ){
37221df2db7fSshaneh     char *pNew = NULL;             /* New temp space */
3723763afe62Sdan     i64 nByte = 0;
37241879b088Sdan 
3725de1ae34eSdan     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
37261879b088Sdan       rc = sqlite3OsFileSize(pPager->fd, &nByte);
3727763afe62Sdan     }
37281879b088Sdan     if( rc==SQLITE_OK ){
37295cb1ffc1Sdrh       /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
37305cb1ffc1Sdrh       * cell header parser will never run off the end of the allocation */
37315cb1ffc1Sdrh       pNew = (char *)sqlite3PageMalloc(pageSize+8);
37325cb1ffc1Sdrh       if( !pNew ){
37335cb1ffc1Sdrh         rc = SQLITE_NOMEM_BKPT;
37345cb1ffc1Sdrh       }else{
37355cb1ffc1Sdrh         memset(pNew+pageSize, 0, 8);
37365cb1ffc1Sdrh       }
37371879b088Sdan     }
37381879b088Sdan 
37391879b088Sdan     if( rc==SQLITE_OK ){
3740c7c7e623Sdanielk1977       pager_reset(pPager);
3741c3031c61Sdrh       rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
37421c7880e5Sdrh     }
374360da7274Sdrh     if( rc==SQLITE_OK ){
37446a154403Sdrh       sqlite3PageFree(pPager->pTmpSpace);
37456a154403Sdrh       pPager->pTmpSpace = pNew;
374660da7274Sdrh       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
374760da7274Sdrh       pPager->pageSize = pageSize;
3748584bfcaeSdrh       pPager->lckPgno = (Pgno)(PENDING_BYTE/pageSize) + 1;
37496a154403Sdrh     }else{
37506a154403Sdrh       sqlite3PageFree(pNew);
375160da7274Sdrh     }
3752a1644fd8Sdanielk1977   }
375322b328b2Sdan 
3754b2eced5dSdrh   *pPageSize = pPager->pageSize;
37551879b088Sdan   if( rc==SQLITE_OK ){
3756fa9601a9Sdrh     if( nReserve<0 ) nReserve = pPager->nReserve;
3757fa9601a9Sdrh     assert( nReserve>=0 && nReserve<1000 );
3758fa9601a9Sdrh     pPager->nReserve = (i16)nReserve;
37595d8a1372Sdan     pagerFixMaplimit(pPager);
37601879b088Sdan   }
37611879b088Sdan   return rc;
376290f5ecb3Sdrh }
376390f5ecb3Sdrh 
376490f5ecb3Sdrh /*
376526b7994aSdrh ** Return a pointer to the "temporary page" buffer held internally
376626b7994aSdrh ** by the pager.  This is a buffer that is big enough to hold the
376726b7994aSdrh ** entire content of a database page.  This buffer is used internally
376826b7994aSdrh ** during rollback and will be overwritten whenever a rollback
376926b7994aSdrh ** occurs.  But other modules are free to use it too, as long as
377026b7994aSdrh ** no rollbacks are happening.
377126b7994aSdrh */
sqlite3PagerTempSpace(Pager * pPager)377226b7994aSdrh void *sqlite3PagerTempSpace(Pager *pPager){
377326b7994aSdrh   return pPager->pTmpSpace;
377426b7994aSdrh }
377526b7994aSdrh 
377626b7994aSdrh /*
3777f8e632b6Sdrh ** Attempt to set the maximum database page count if mxPage is positive.
3778f8e632b6Sdrh ** Make no changes if mxPage is zero or negative.  And never reduce the
3779f8e632b6Sdrh ** maximum page count below the current size of the database.
3780f8e632b6Sdrh **
3781f8e632b6Sdrh ** Regardless of mxPage, return the current maximum page count.
3782f8e632b6Sdrh */
sqlite3PagerMaxPageCount(Pager * pPager,Pgno mxPage)3783e9261dbdSdrh Pgno sqlite3PagerMaxPageCount(Pager *pPager, Pgno mxPage){
3784f8e632b6Sdrh   if( mxPage>0 ){
3785f8e632b6Sdrh     pPager->mxPgno = mxPage;
3786f8e632b6Sdrh   }
3787c84e033cSdrh   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
3788b8852ae0Sdan   /* assert( pPager->mxPgno>=pPager->dbSize ); */
3789b8852ae0Sdan   /* OP_MaxPgcnt ensures that the parameter passed to this function is not
3790b8852ae0Sdan   ** less than the total number of valid pages in the database. But this
3791b8852ae0Sdan   ** may be less than Pager.dbSize, and so the assert() above is not valid */
3792f8e632b6Sdrh   return pPager->mxPgno;
3793f8e632b6Sdrh }
3794f8e632b6Sdrh 
3795f8e632b6Sdrh /*
3796c9ac5caaSdrh ** The following set of routines are used to disable the simulated
3797c9ac5caaSdrh ** I/O error mechanism.  These routines are used to avoid simulated
3798c9ac5caaSdrh ** errors in places where we do not care about errors.
3799c9ac5caaSdrh **
3800c9ac5caaSdrh ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
3801c9ac5caaSdrh ** and generate no code.
3802c9ac5caaSdrh */
3803c9ac5caaSdrh #ifdef SQLITE_TEST
3804c9ac5caaSdrh extern int sqlite3_io_error_pending;
3805c9ac5caaSdrh extern int sqlite3_io_error_hit;
3806c9ac5caaSdrh static int saved_cnt;
disable_simulated_io_errors(void)3807c9ac5caaSdrh void disable_simulated_io_errors(void){
3808c9ac5caaSdrh   saved_cnt = sqlite3_io_error_pending;
3809c9ac5caaSdrh   sqlite3_io_error_pending = -1;
3810c9ac5caaSdrh }
enable_simulated_io_errors(void)3811c9ac5caaSdrh void enable_simulated_io_errors(void){
3812c9ac5caaSdrh   sqlite3_io_error_pending = saved_cnt;
3813c9ac5caaSdrh }
3814c9ac5caaSdrh #else
3815152410faSdrh # define disable_simulated_io_errors()
3816152410faSdrh # define enable_simulated_io_errors()
3817c9ac5caaSdrh #endif
3818c9ac5caaSdrh 
3819c9ac5caaSdrh /*
382090f5ecb3Sdrh ** Read the first N bytes from the beginning of the file into memory
3821aef0bf64Sdanielk1977 ** that pDest points to.
3822aef0bf64Sdanielk1977 **
3823bea2a948Sdanielk1977 ** If the pager was opened on a transient file (zFilename==""), or
3824bea2a948Sdanielk1977 ** opened on a file less than N bytes in size, the output buffer is
3825bea2a948Sdanielk1977 ** zeroed and SQLITE_OK returned. The rationale for this is that this
3826bea2a948Sdanielk1977 ** function is used to read database headers, and a new transient or
3827bea2a948Sdanielk1977 ** zero sized database has a header than consists entirely of zeroes.
3828bea2a948Sdanielk1977 **
3829bea2a948Sdanielk1977 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
3830bea2a948Sdanielk1977 ** the error code is returned to the caller and the contents of the
3831bea2a948Sdanielk1977 ** output buffer undefined.
383290f5ecb3Sdrh */
sqlite3PagerReadFileheader(Pager * pPager,int N,unsigned char * pDest)38333b8a05f6Sdanielk1977 int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
3834551b7736Sdrh   int rc = SQLITE_OK;
383590f5ecb3Sdrh   memset(pDest, 0, N);
3836bea2a948Sdanielk1977   assert( isOpen(pPager->fd) || pPager->tempFile );
3837b6e099a9Sdan 
383882043b30Sdrh   /* This routine is only called by btree immediately after creating
383982043b30Sdrh   ** the Pager object.  There has not been an opportunity to transition
384082043b30Sdrh   ** to WAL mode yet.
384182043b30Sdrh   */
384282043b30Sdrh   assert( !pagerUseWal(pPager) );
3843b6e099a9Sdan 
3844bea2a948Sdanielk1977   if( isOpen(pPager->fd) ){
3845b0603416Sdrh     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
384662079060Sdanielk1977     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
3847551b7736Sdrh     if( rc==SQLITE_IOERR_SHORT_READ ){
3848551b7736Sdrh       rc = SQLITE_OK;
384990f5ecb3Sdrh     }
385090f5ecb3Sdrh   }
3851551b7736Sdrh   return rc;
3852551b7736Sdrh }
385390f5ecb3Sdrh 
385490f5ecb3Sdrh /*
3855937ac9daSdan ** This function may only be called when a read-transaction is open on
3856937ac9daSdan ** the pager. It returns the total number of pages in the database.
3857937ac9daSdan **
3858bea2a948Sdanielk1977 ** However, if the file is between 1 and <page-size> bytes in size, then
3859bea2a948Sdanielk1977 ** this is considered a 1 page file.
3860ed7c855cSdrh */
sqlite3PagerPagecount(Pager * pPager,int * pnPage)38618fb8b537Sdrh void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
386254919f82Sdan   assert( pPager->eState>=PAGER_READER );
3863763afe62Sdan   assert( pPager->eState!=PAGER_WRITER_FINISHED );
3864937ac9daSdan   *pnPage = (int)pPager->dbSize;
3865ed7c855cSdrh }
3866ed7c855cSdrh 
3867ac69b05eSdrh 
3868ac69b05eSdrh /*
3869bea2a948Sdanielk1977 ** Try to obtain a lock of type locktype on the database file. If
3870bea2a948Sdanielk1977 ** a similar or greater lock is already held, this function is a no-op
3871bea2a948Sdanielk1977 ** (returning SQLITE_OK immediately).
3872bea2a948Sdanielk1977 **
3873bea2a948Sdanielk1977 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
3874bea2a948Sdanielk1977 ** the busy callback if the lock is currently not available. Repeat
3875bea2a948Sdanielk1977 ** until the busy callback returns false or until the attempt to
3876bea2a948Sdanielk1977 ** obtain the lock succeeds.
387717221813Sdanielk1977 **
387817221813Sdanielk1977 ** Return SQLITE_OK on success and an error code if we cannot obtain
3879bea2a948Sdanielk1977 ** the lock. If the lock is obtained successfully, set the Pager.state
3880bea2a948Sdanielk1977 ** variable to locktype before returning.
388117221813Sdanielk1977 */
pager_wait_on_lock(Pager * pPager,int locktype)388217221813Sdanielk1977 static int pager_wait_on_lock(Pager *pPager, int locktype){
3883bea2a948Sdanielk1977   int rc;                              /* Return code */
38841aa2d8b5Sdrh 
3885bea2a948Sdanielk1977   /* Check that this is either a no-op (because the requested lock is
388660ec914cSpeter.d.reid   ** already held), or one of the transitions that the busy-handler
3887bea2a948Sdanielk1977   ** may be invoked during, according to the comment above
3888bea2a948Sdanielk1977   ** sqlite3PagerSetBusyhandler().
3889bea2a948Sdanielk1977   */
3890d0864087Sdan   assert( (pPager->eLock>=locktype)
3891d0864087Sdan        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
3892d0864087Sdan        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
3893bea2a948Sdanielk1977   );
3894bea2a948Sdanielk1977 
389517221813Sdanielk1977   do {
38964e004aa6Sdan     rc = pagerLockDb(pPager, locktype);
38971ceedd37Sdanielk1977   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
389817221813Sdanielk1977   return rc;
389917221813Sdanielk1977 }
390017221813Sdanielk1977 
39013460d19cSdanielk1977 /*
39029f0b6be8Sdanielk1977 ** Function assertTruncateConstraint(pPager) checks that one of the
39039f0b6be8Sdanielk1977 ** following is true for all dirty pages currently in the page-cache:
39049f0b6be8Sdanielk1977 **
39059f0b6be8Sdanielk1977 **   a) The page number is less than or equal to the size of the
39069f0b6be8Sdanielk1977 **      current database image, in pages, OR
39079f0b6be8Sdanielk1977 **
39089f0b6be8Sdanielk1977 **   b) if the page content were written at this time, it would not
39094ce289d0Sdan **      be necessary to write the current content out to the sub-journal.
39109f0b6be8Sdanielk1977 **
39119f0b6be8Sdanielk1977 ** If the condition asserted by this function were not true, and the
39129f0b6be8Sdanielk1977 ** dirty page were to be discarded from the cache via the pagerStress()
39139f0b6be8Sdanielk1977 ** routine, pagerStress() would not write the current page content to
39149f0b6be8Sdanielk1977 ** the database file. If a savepoint transaction were rolled back after
391548864df9Smistachkin ** this happened, the correct behavior would be to restore the current
39169f0b6be8Sdanielk1977 ** content of the page. However, since this content is not present in either
39179f0b6be8Sdanielk1977 ** the database file or the portion of the rollback journal and
39189f0b6be8Sdanielk1977 ** sub-journal rolled back the content could not be restored and the
39199f0b6be8Sdanielk1977 ** database image would become corrupt. It is therefore fortunate that
39209f0b6be8Sdanielk1977 ** this circumstance cannot arise.
39219f0b6be8Sdanielk1977 */
39229f0b6be8Sdanielk1977 #if defined(SQLITE_DEBUG)
assertTruncateConstraintCb(PgHdr * pPg)39239f0b6be8Sdanielk1977 static void assertTruncateConstraintCb(PgHdr *pPg){
39244ce289d0Sdan   Pager *pPager = pPg->pPager;
39259f0b6be8Sdanielk1977   assert( pPg->flags&PGHDR_DIRTY );
39264ce289d0Sdan   if( pPg->pgno>pPager->dbSize ){      /* if (a) is false */
39274ce289d0Sdan     Pgno pgno = pPg->pgno;
39284ce289d0Sdan     int i;
39294ce289d0Sdan     for(i=0; i<pPg->pPager->nSavepoint; i++){
39304ce289d0Sdan       PagerSavepoint *p = &pPager->aSavepoint[i];
39314ce289d0Sdan       assert( p->nOrig<pgno || sqlite3BitvecTestNotNull(p->pInSavepoint,pgno) );
39324ce289d0Sdan     }
39334ce289d0Sdan   }
39349f0b6be8Sdanielk1977 }
assertTruncateConstraint(Pager * pPager)39359f0b6be8Sdanielk1977 static void assertTruncateConstraint(Pager *pPager){
39369f0b6be8Sdanielk1977   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
39379f0b6be8Sdanielk1977 }
39389f0b6be8Sdanielk1977 #else
39399f0b6be8Sdanielk1977 # define assertTruncateConstraint(pPager)
39409f0b6be8Sdanielk1977 #endif
39419f0b6be8Sdanielk1977 
39429f0b6be8Sdanielk1977 /*
3943f90b7260Sdanielk1977 ** Truncate the in-memory database file image to nPage pages. This
3944f90b7260Sdanielk1977 ** function does not actually modify the database file on disk. It
3945f90b7260Sdanielk1977 ** just sets the internal state of the pager object so that the
3946f90b7260Sdanielk1977 ** truncation will be done when the current transaction is committed.
3947e0ac363cSdan **
3948e0ac363cSdan ** This function is only called right before committing a transaction.
3949e0ac363cSdan ** Once this function has been called, the transaction must either be
3950e0ac363cSdan ** rolled back or committed. It is not safe to call this function and
3951e0ac363cSdan ** then continue writing to the database.
39523460d19cSdanielk1977 */
sqlite3PagerTruncateImage(Pager * pPager,Pgno nPage)39533460d19cSdanielk1977 void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
39544ba1c5ccSdrh   assert( pPager->dbSize>=nPage || CORRUPT_DB );
3955d0864087Sdan   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
39563460d19cSdanielk1977   pPager->dbSize = nPage;
3957e0ac363cSdan 
3958e0ac363cSdan   /* At one point the code here called assertTruncateConstraint() to
3959e0ac363cSdan   ** ensure that all pages being truncated away by this operation are,
3960e0ac363cSdan   ** if one or more savepoints are open, present in the savepoint
3961e0ac363cSdan   ** journal so that they can be restored if the savepoint is rolled
3962e0ac363cSdan   ** back. This is no longer necessary as this function is now only
3963e0ac363cSdan   ** called right before committing a transaction. So although the
3964e0ac363cSdan   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
3965e0ac363cSdan   ** they cannot be rolled back. So the assertTruncateConstraint() call
3966e0ac363cSdan   ** is no longer correct. */
39673460d19cSdanielk1977 }
39683460d19cSdanielk1977 
39697c24610eSdan 
3970f7c57531Sdrh /*
3971eada58aaSdan ** This function is called before attempting a hot-journal rollback. It
3972eada58aaSdan ** syncs the journal file to disk, then sets pPager->journalHdr to the
3973eada58aaSdan ** size of the journal file so that the pager_playback() routine knows
3974eada58aaSdan ** that the entire journal file has been synced.
3975eada58aaSdan **
3976eada58aaSdan ** Syncing a hot-journal to disk before attempting to roll it back ensures
3977eada58aaSdan ** that if a power-failure occurs during the rollback, the process that
3978eada58aaSdan ** attempts rollback following system recovery sees the same journal
3979eada58aaSdan ** content as this process.
3980eada58aaSdan **
3981eada58aaSdan ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
3982eada58aaSdan ** an SQLite error code.
3983eada58aaSdan */
pagerSyncHotJournal(Pager * pPager)3984eada58aaSdan static int pagerSyncHotJournal(Pager *pPager){
3985eada58aaSdan   int rc = SQLITE_OK;
3986eada58aaSdan   if( !pPager->noSync ){
3987eada58aaSdan     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
3988eada58aaSdan   }
3989eada58aaSdan   if( rc==SQLITE_OK ){
3990eada58aaSdan     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
3991eada58aaSdan   }
3992eada58aaSdan   return rc;
3993eada58aaSdan }
3994eada58aaSdan 
39959c4dc229Sdrh #if SQLITE_MAX_MMAP_SIZE>0
3996b2d3de3bSdan /*
39975d8a1372Sdan ** Obtain a reference to a memory mapped page object for page number pgno.
3998f23da966Sdan ** The new object will use the pointer pData, obtained from xFetch().
3999f23da966Sdan ** If successful, set *ppPage to point to the new page reference
40005d8a1372Sdan ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
40015d8a1372Sdan ** *ppPage to zero.
40025d8a1372Sdan **
40035d8a1372Sdan ** Page references obtained by calling this function should be released
40045d8a1372Sdan ** by calling pagerReleaseMapPage().
40055d8a1372Sdan */
pagerAcquireMapPage(Pager * pPager,Pgno pgno,void * pData,PgHdr ** ppPage)4006f23da966Sdan static int pagerAcquireMapPage(
4007f23da966Sdan   Pager *pPager,                  /* Pager object */
4008f23da966Sdan   Pgno pgno,                      /* Page number */
4009f23da966Sdan   void *pData,                    /* xFetch()'d data for this page */
4010f23da966Sdan   PgHdr **ppPage                  /* OUT: Acquired page object */
4011f23da966Sdan ){
40125d8a1372Sdan   PgHdr *p;                       /* Memory mapped page to return */
4013b2d3de3bSdan 
4014c86e5135Sdrh   if( pPager->pMmapFreelist ){
4015c86e5135Sdrh     *ppPage = p = pPager->pMmapFreelist;
4016c86e5135Sdrh     pPager->pMmapFreelist = p->pDirty;
4017b2d3de3bSdan     p->pDirty = 0;
4018a2ee589cSdrh     assert( pPager->nExtra>=8 );
4019a2ee589cSdrh     memset(p->pExtra, 0, 8);
4020b2d3de3bSdan   }else{
40215d8a1372Sdan     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
40225d8a1372Sdan     if( p==0 ){
4023df737fe6Sdan       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
4024fad3039cSmistachkin       return SQLITE_NOMEM_BKPT;
40255d8a1372Sdan     }
4026b2d3de3bSdan     p->pExtra = (void *)&p[1];
4027b2d3de3bSdan     p->flags = PGHDR_MMAP;
4028b2d3de3bSdan     p->nRef = 1;
4029b2d3de3bSdan     p->pPager = pPager;
4030b2d3de3bSdan   }
4031b2d3de3bSdan 
4032b2d3de3bSdan   assert( p->pExtra==(void *)&p[1] );
4033b2d3de3bSdan   assert( p->pPage==0 );
4034b2d3de3bSdan   assert( p->flags==PGHDR_MMAP );
4035b2d3de3bSdan   assert( p->pPager==pPager );
4036b2d3de3bSdan   assert( p->nRef==1 );
4037b2d3de3bSdan 
4038b2d3de3bSdan   p->pgno = pgno;
4039f23da966Sdan   p->pData = pData;
4040b2d3de3bSdan   pPager->nMmapOut++;
4041b2d3de3bSdan 
4042b2d3de3bSdan   return SQLITE_OK;
4043b2d3de3bSdan }
40449c4dc229Sdrh #endif
4045b2d3de3bSdan 
40465d8a1372Sdan /*
40475d8a1372Sdan ** Release a reference to page pPg. pPg must have been returned by an
40485d8a1372Sdan ** earlier call to pagerAcquireMapPage().
40495d8a1372Sdan */
pagerReleaseMapPage(PgHdr * pPg)4050b2d3de3bSdan static void pagerReleaseMapPage(PgHdr *pPg){
4051b2d3de3bSdan   Pager *pPager = pPg->pPager;
4052b2d3de3bSdan   pPager->nMmapOut--;
4053c86e5135Sdrh   pPg->pDirty = pPager->pMmapFreelist;
4054c86e5135Sdrh   pPager->pMmapFreelist = pPg;
4055f23da966Sdan 
4056f23da966Sdan   assert( pPager->fd->pMethods->iVersion>=3 );
4057df737fe6Sdan   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
4058b2d3de3bSdan }
4059b2d3de3bSdan 
40605d8a1372Sdan /*
4061c86e5135Sdrh ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
40625d8a1372Sdan */
pagerFreeMapHdrs(Pager * pPager)4063b2d3de3bSdan static void pagerFreeMapHdrs(Pager *pPager){
4064b2d3de3bSdan   PgHdr *p;
4065b2d3de3bSdan   PgHdr *pNext;
4066c86e5135Sdrh   for(p=pPager->pMmapFreelist; p; p=pNext){
4067b2d3de3bSdan     pNext = p->pDirty;
4068b2d3de3bSdan     sqlite3_free(p);
4069b2d3de3bSdan   }
4070b2d3de3bSdan }
4071b2d3de3bSdan 
4072fa68815fSdan /* Verify that the database file has not be deleted or renamed out from
4073b189e410Smistachkin ** under the pager.  Return SQLITE_OK if the database is still where it ought
4074fa68815fSdan ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
4075fa68815fSdan ** code from sqlite3OsAccess()) if the database has gone missing.
4076fa68815fSdan */
databaseIsUnmoved(Pager * pPager)4077fa68815fSdan static int databaseIsUnmoved(Pager *pPager){
4078fa68815fSdan   int bHasMoved = 0;
4079fa68815fSdan   int rc;
4080fa68815fSdan 
4081fa68815fSdan   if( pPager->tempFile ) return SQLITE_OK;
4082fa68815fSdan   if( pPager->dbSize==0 ) return SQLITE_OK;
4083fa68815fSdan   assert( pPager->zFilename && pPager->zFilename[0] );
4084fa68815fSdan   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
4085fa68815fSdan   if( rc==SQLITE_NOTFOUND ){
4086fa68815fSdan     /* If the HAS_MOVED file-control is unimplemented, assume that the file
4087fa68815fSdan     ** has not been moved.  That is the historical behavior of SQLite: prior to
4088fa68815fSdan     ** version 3.8.3, it never checked */
4089fa68815fSdan     rc = SQLITE_OK;
4090fa68815fSdan   }else if( rc==SQLITE_OK && bHasMoved ){
4091fa68815fSdan     rc = SQLITE_READONLY_DBMOVED;
4092fa68815fSdan   }
4093fa68815fSdan   return rc;
4094fa68815fSdan }
4095fa68815fSdan 
4096b2d3de3bSdan 
4097eada58aaSdan /*
4098ed7c855cSdrh ** Shutdown the page cache.  Free all memory and close all files.
4099ed7c855cSdrh **
4100ed7c855cSdrh ** If a transaction was in progress when this routine is called, that
4101ed7c855cSdrh ** transaction is rolled back.  All outstanding pages are invalidated
4102ed7c855cSdrh ** and their memory is freed.  Any attempt to use a page associated
4103ed7c855cSdrh ** with this page cache after this function returns will likely
4104ed7c855cSdrh ** result in a coredump.
4105aef0bf64Sdanielk1977 **
4106aef0bf64Sdanielk1977 ** This function always succeeds. If a transaction is active an attempt
4107aef0bf64Sdanielk1977 ** is made to roll it back. If an error occurs during the rollback
4108aef0bf64Sdanielk1977 ** a hot journal may be left in the filesystem but no error is returned
4109aef0bf64Sdanielk1977 ** to the caller.
4110ed7c855cSdrh */
sqlite3PagerClose(Pager * pPager,sqlite3 * db)41117fb89906Sdan int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
41127c24610eSdan   u8 *pTmp = (u8*)pPager->pTmpSpace;
41137fb89906Sdan   assert( db || pagerUseWal(pPager)==0 );
41142a5d9908Sdrh   assert( assert_pager_state(pPager) );
4115c9ac5caaSdrh   disable_simulated_io_errors();
41162d1d86fbSdanielk1977   sqlite3BeginBenignMalloc();
4117b2d3de3bSdan   pagerFreeMapHdrs(pPager);
4118a42c66bdSdan   /* pPager->errCode = 0; */
411941483468Sdanielk1977   pPager->exclusiveMode = 0;
41205cf53537Sdan #ifndef SQLITE_OMIT_WAL
4121fa68815fSdan   {
4122fa68815fSdan     u8 *a = 0;
41234a5bad57Sdan     assert( db || pPager->pWal==0 );
4124fa68815fSdan     if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
4125fa68815fSdan      && SQLITE_OK==databaseIsUnmoved(pPager)
4126fa68815fSdan     ){
4127fa68815fSdan       a = pTmp;
4128fa68815fSdan     }
4129fa68815fSdan     sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
41307ed91f23Sdrh     pPager->pWal = 0;
4131fa68815fSdan   }
41325cf53537Sdan #endif
4133bafda096Sdrh   pager_reset(pPager);
4134bea2a948Sdanielk1977   if( MEMDB ){
4135bea2a948Sdanielk1977     pager_unlock(pPager);
4136bea2a948Sdanielk1977   }else{
4137a42c66bdSdan     /* If it is open, sync the journal file before calling UnlockAndRollback.
4138a42c66bdSdan     ** If this is not done, then an unsynced portion of the open journal
4139a42c66bdSdan     ** file may be played back into the database. If a power failure occurs
4140a42c66bdSdan     ** while this is happening, the database could become corrupt.
4141a42c66bdSdan     **
4142a42c66bdSdan     ** If an error occurs while trying to sync the journal, shift the pager
4143a42c66bdSdan     ** into the ERROR state. This causes UnlockAndRollback to unlock the
4144a42c66bdSdan     ** database and close the journal file without attempting to roll it
4145a42c66bdSdan     ** back or finalize it. The next database user will have to do hot-journal
4146a42c66bdSdan     ** rollback before accessing the database file.
4147f2c31ad8Sdanielk1977     */
4148eada58aaSdan     if( isOpen(pPager->jfd) ){
4149a42c66bdSdan       pager_error(pPager, pagerSyncHotJournal(pPager));
4150eada58aaSdan     }
4151e277be05Sdanielk1977     pagerUnlockAndRollback(pPager);
4152b3175389Sdanielk1977   }
415345d6882fSdanielk1977   sqlite3EndBenignMalloc();
4154bea2a948Sdanielk1977   enable_simulated_io_errors();
415530d53701Sdrh   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
4156b0603416Sdrh   IOTRACE(("CLOSE %p\n", pPager))
4157e08341c6Sdan   sqlite3OsClose(pPager->jfd);
4158b4b47411Sdanielk1977   sqlite3OsClose(pPager->fd);
41597c24610eSdan   sqlite3PageFree(pTmp);
41608c0a791aSdanielk1977   sqlite3PcacheClose(pPager->pPCache);
4161bea2a948Sdanielk1977   assert( !pPager->aSavepoint && !pPager->pInJournal );
4162bea2a948Sdanielk1977   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
4163bea2a948Sdanielk1977 
416417435752Sdrh   sqlite3_free(pPager);
4165ed7c855cSdrh   return SQLITE_OK;
4166ed7c855cSdrh }
4167ed7c855cSdrh 
416887cc3b31Sdrh #if !defined(NDEBUG) || defined(SQLITE_TEST)
4169ed7c855cSdrh /*
4170bea2a948Sdanielk1977 ** Return the page number for page pPg.
4171ed7c855cSdrh */
sqlite3PagerPagenumber(DbPage * pPg)4172bea2a948Sdanielk1977 Pgno sqlite3PagerPagenumber(DbPage *pPg){
4173bea2a948Sdanielk1977   return pPg->pgno;
4174ed7c855cSdrh }
417587cc3b31Sdrh #endif
4176ed7c855cSdrh 
4177ed7c855cSdrh /*
4178bea2a948Sdanielk1977 ** Increment the reference count for page pPg.
4179df0b3b09Sdrh */
sqlite3PagerRef(DbPage * pPg)4180bea2a948Sdanielk1977 void sqlite3PagerRef(DbPage *pPg){
41818c0a791aSdanielk1977   sqlite3PcacheRef(pPg);
41827e3b0a07Sdrh }
41837e3b0a07Sdrh 
41847e3b0a07Sdrh /*
418534e79ceeSdrh ** Sync the journal. In other words, make sure all the pages that have
418634e79ceeSdrh ** been written to the journal have actually reached the surface of the
4187bea2a948Sdanielk1977 ** disk and can be restored in the event of a hot-journal rollback.
4188b19a2bc6Sdrh **
418951133eaeSdan ** If the Pager.noSync flag is set, then this function is a no-op.
419051133eaeSdan ** Otherwise, the actions required depend on the journal-mode and the
4191d5578433Smistachkin ** device characteristics of the file-system, as follows:
4192fa86c412Sdrh **
4193bea2a948Sdanielk1977 **   * If the journal file is an in-memory journal file, no action need
4194bea2a948Sdanielk1977 **     be taken.
41954cd2cd5cSdanielk1977 **
4196bea2a948Sdanielk1977 **   * Otherwise, if the device does not support the SAFE_APPEND property,
4197bea2a948Sdanielk1977 **     then the nRec field of the most recently written journal header
4198bea2a948Sdanielk1977 **     is updated to contain the number of journal records that have
4199bea2a948Sdanielk1977 **     been written following it. If the pager is operating in full-sync
4200bea2a948Sdanielk1977 **     mode, then the journal file is synced before this field is updated.
420134e79ceeSdrh **
4202bea2a948Sdanielk1977 **   * If the device does not support the SEQUENTIAL property, then
4203bea2a948Sdanielk1977 **     journal file is synced.
4204bea2a948Sdanielk1977 **
4205bea2a948Sdanielk1977 ** Or, in pseudo-code:
4206bea2a948Sdanielk1977 **
4207bea2a948Sdanielk1977 **   if( NOT <in-memory journal> ){
4208bea2a948Sdanielk1977 **     if( NOT SAFE_APPEND ){
4209bea2a948Sdanielk1977 **       if( <full-sync mode> ) xSync(<journal file>);
4210bea2a948Sdanielk1977 **       <update nRec field>
4211bea2a948Sdanielk1977 **     }
4212bea2a948Sdanielk1977 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
4213bea2a948Sdanielk1977 **   }
4214bea2a948Sdanielk1977 **
4215bea2a948Sdanielk1977 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
4216bea2a948Sdanielk1977 ** page currently held in memory before returning SQLITE_OK. If an IO
4217bea2a948Sdanielk1977 ** error is encountered, then the IO error code is returned to the caller.
421850e5dadfSdrh */
syncJournal(Pager * pPager,int newHdr)4219937ac9daSdan static int syncJournal(Pager *pPager, int newHdr){
4220d0864087Sdan   int rc;                         /* Return code */
4221d0864087Sdan 
4222d0864087Sdan   assert( pPager->eState==PAGER_WRITER_CACHEMOD
4223d0864087Sdan        || pPager->eState==PAGER_WRITER_DBMOD
4224d0864087Sdan   );
4225d0864087Sdan   assert( assert_pager_state(pPager) );
4226937ac9daSdan   assert( !pagerUseWal(pPager) );
4227d0864087Sdan 
4228d0864087Sdan   rc = sqlite3PagerExclusiveLock(pPager);
4229d0864087Sdan   if( rc!=SQLITE_OK ) return rc;
4230d0864087Sdan 
423151133eaeSdan   if( !pPager->noSync ){
4232b3175389Sdanielk1977     assert( !pPager->tempFile );
4233d0864087Sdan     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
4234bea2a948Sdanielk1977       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
4235bea2a948Sdanielk1977       assert( isOpen(pPager->jfd) );
42364cd2cd5cSdanielk1977 
42374cd2cd5cSdanielk1977       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
4238112f752bSdanielk1977         /* This block deals with an obscure problem. If the last connection
4239112f752bSdanielk1977         ** that wrote to this database was operating in persistent-journal
4240112f752bSdanielk1977         ** mode, then the journal file may at this point actually be larger
4241112f752bSdanielk1977         ** than Pager.journalOff bytes. If the next thing in the journal
4242112f752bSdanielk1977         ** file happens to be a journal-header (written as part of the
424391781bd7Sdrh         ** previous connection's transaction), and a crash or power-failure
4244112f752bSdanielk1977         ** occurs after nRec is updated but before this connection writes
4245112f752bSdanielk1977         ** anything else to the journal file (or commits/rolls back its
4246112f752bSdanielk1977         ** transaction), then SQLite may become confused when doing the
4247112f752bSdanielk1977         ** hot-journal rollback following recovery. It may roll back all
4248112f752bSdanielk1977         ** of this connections data, then proceed to rolling back the old,
4249112f752bSdanielk1977         ** out-of-date data that follows it. Database corruption.
4250112f752bSdanielk1977         **
4251112f752bSdanielk1977         ** To work around this, if the journal file does appear to contain
4252112f752bSdanielk1977         ** a valid header following Pager.journalOff, then write a 0x00
4253112f752bSdanielk1977         ** byte to the start of it to prevent it from being recognized.
4254bea2a948Sdanielk1977         **
4255bea2a948Sdanielk1977         ** Variable iNextHdrOffset is set to the offset at which this
4256bea2a948Sdanielk1977         ** problematic header will occur, if it exists. aMagic is used
4257bea2a948Sdanielk1977         ** as a temporary buffer to inspect the first couple of bytes of
4258bea2a948Sdanielk1977         ** the potential journal header.
4259112f752bSdanielk1977         */
42607b746030Sdrh         i64 iNextHdrOffset;
4261bea2a948Sdanielk1977         u8 aMagic[8];
42627b746030Sdrh         u8 zHeader[sizeof(aJournalMagic)+4];
42637b746030Sdrh 
42647b746030Sdrh         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42657b746030Sdrh         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
42667b746030Sdrh 
42677b746030Sdrh         iNextHdrOffset = journalHdrOffset(pPager);
4268bea2a948Sdanielk1977         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
4269bea2a948Sdanielk1977         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
4270112f752bSdanielk1977           static const u8 zerobyte = 0;
4271bea2a948Sdanielk1977           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
4272112f752bSdanielk1977         }
4273112f752bSdanielk1977         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
4274112f752bSdanielk1977           return rc;
4275112f752bSdanielk1977         }
4276112f752bSdanielk1977 
42777657240aSdanielk1977         /* Write the nRec value into the journal file header. If in
42787657240aSdanielk1977         ** full-synchronous mode, sync the journal first. This ensures that
42797657240aSdanielk1977         ** all data has really hit the disk before nRec is updated to mark
42807657240aSdanielk1977         ** it as a candidate for rollback.
42814cd2cd5cSdanielk1977         **
42824cd2cd5cSdanielk1977         ** This is not required if the persistent media supports the
42834cd2cd5cSdanielk1977         ** SAFE_APPEND property. Because in this case it is not possible
42844cd2cd5cSdanielk1977         ** for garbage data to be appended to the file, the nRec field
42854cd2cd5cSdanielk1977         ** is populated with 0xFFFFFFFF when the journal header is written
42864cd2cd5cSdanielk1977         ** and never needs to be updated.
42877657240aSdanielk1977         */
42884cd2cd5cSdanielk1977         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
428930d53701Sdrh           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
4290b0603416Sdrh           IOTRACE(("JSYNC %p\n", pPager))
4291c97d8463Sdrh           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
4292bea2a948Sdanielk1977           if( rc!=SQLITE_OK ) return rc;
4293968af52aSdrh         }
42947b746030Sdrh         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
42956f4c73eeSdanielk1977         rc = sqlite3OsWrite(
42966f4c73eeSdanielk1977             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
42976f4c73eeSdanielk1977         );
4298bea2a948Sdanielk1977         if( rc!=SQLITE_OK ) return rc;
4299d8d66e8cSdrh       }
43004cd2cd5cSdanielk1977       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
430130d53701Sdrh         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
4302126afe6bSdrh         IOTRACE(("JSYNC %p\n", pPager))
4303c97d8463Sdrh         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
4304c97d8463Sdrh           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
4305f036aef0Sdanielk1977         );
4306bea2a948Sdanielk1977         if( rc!=SQLITE_OK ) return rc;
43074cd2cd5cSdanielk1977       }
430845d6882fSdanielk1977 
430991781bd7Sdrh       pPager->journalHdr = pPager->journalOff;
4310937ac9daSdan       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
4311937ac9daSdan         pPager->nRec = 0;
4312937ac9daSdan         rc = writeJournalHdr(pPager);
43135761dbe4Sdan         if( rc!=SQLITE_OK ) return rc;
4314937ac9daSdan       }
4315937ac9daSdan     }else{
4316937ac9daSdan       pPager->journalHdr = pPager->journalOff;
4317937ac9daSdan     }
4318341eae8dSdrh   }
4319341eae8dSdrh 
4320d0864087Sdan   /* Unless the pager is in noSync mode, the journal file was just
4321d0864087Sdan   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
4322d0864087Sdan   ** all pages.
4323d0864087Sdan   */
4324d0864087Sdan   sqlite3PcacheClearSyncFlags(pPager->pPCache);
4325d0864087Sdan   pPager->eState = PAGER_WRITER_DBMOD;
4326d0864087Sdan   assert( assert_pager_state(pPager) );
4327bea2a948Sdanielk1977   return SQLITE_OK;
432850e5dadfSdrh }
432950e5dadfSdrh 
433050e5dadfSdrh /*
4331bea2a948Sdanielk1977 ** The argument is the first in a linked list of dirty pages connected
4332bea2a948Sdanielk1977 ** by the PgHdr.pDirty pointer. This function writes each one of the
4333bea2a948Sdanielk1977 ** in-memory pages in the list to the database file. The argument may
4334bea2a948Sdanielk1977 ** be NULL, representing an empty list. In this case this function is
4335bea2a948Sdanielk1977 ** a no-op.
4336bea2a948Sdanielk1977 **
4337bea2a948Sdanielk1977 ** The pager must hold at least a RESERVED lock when this function
4338bea2a948Sdanielk1977 ** is called. Before writing anything to the database file, this lock
4339bea2a948Sdanielk1977 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
4340bea2a948Sdanielk1977 ** SQLITE_BUSY is returned and no data is written to the database file.
4341bea2a948Sdanielk1977 **
4342bea2a948Sdanielk1977 ** If the pager is a temp-file pager and the actual file-system file
4343bea2a948Sdanielk1977 ** is not yet open, it is created and opened before any data is
4344bea2a948Sdanielk1977 ** written out.
4345bea2a948Sdanielk1977 **
4346bea2a948Sdanielk1977 ** Once the lock has been upgraded and, if necessary, the file opened,
4347bea2a948Sdanielk1977 ** the pages are written out to the database file in list order. Writing
4348bea2a948Sdanielk1977 ** a page is skipped if it meets either of the following criteria:
4349bea2a948Sdanielk1977 **
4350bea2a948Sdanielk1977 **   * The page number is greater than Pager.dbSize, or
4351bea2a948Sdanielk1977 **   * The PGHDR_DONT_WRITE flag is set on the page.
4352bea2a948Sdanielk1977 **
4353bea2a948Sdanielk1977 ** If writing out a page causes the database file to grow, Pager.dbFileSize
4354bea2a948Sdanielk1977 ** is updated accordingly. If page 1 is written out, then the value cached
4355bea2a948Sdanielk1977 ** in Pager.dbFileVers[] is updated to match the new value stored in
4356bea2a948Sdanielk1977 ** the database file.
4357bea2a948Sdanielk1977 **
4358bea2a948Sdanielk1977 ** If everything is successful, SQLITE_OK is returned. If an IO error
4359bea2a948Sdanielk1977 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
4360bea2a948Sdanielk1977 ** be obtained, SQLITE_BUSY is returned.
43612554f8b0Sdrh */
pager_write_pagelist(Pager * pPager,PgHdr * pList)4362146151cdSdrh static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
4363c864912aSdan   int rc = SQLITE_OK;                  /* Return code */
43642554f8b0Sdrh 
4365c864912aSdan   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
4366146151cdSdrh   assert( !pagerUseWal(pPager) );
436741113b64Sdan   assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
4368c864912aSdan   assert( pPager->eLock==EXCLUSIVE_LOCK );
4369199f56b9Sdan   assert( isOpen(pPager->fd) || pList->pDirty==0 );
4370bea2a948Sdanielk1977 
4371bea2a948Sdanielk1977   /* If the file is a temp-file has not yet been opened, open it now. It
4372bea2a948Sdanielk1977   ** is not possible for rc to be other than SQLITE_OK if this branch
4373bea2a948Sdanielk1977   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
4374bea2a948Sdanielk1977   */
4375bea2a948Sdanielk1977   if( !isOpen(pPager->fd) ){
4376bea2a948Sdanielk1977     assert( pPager->tempFile && rc==SQLITE_OK );
4377bea2a948Sdanielk1977     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
43789eed5057Sdanielk1977   }
43799eed5057Sdanielk1977 
43809ff27ecdSdrh   /* Before the first write, give the VFS a hint of what the final
43819ff27ecdSdrh   ** file size will be.
43829ff27ecdSdrh   */
43837fb574ecSdan   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
4384eb97b293Sdan   if( rc==SQLITE_OK
43853719f5f6Sdan    && pPager->dbHintSize<pPager->dbSize
43863719f5f6Sdan    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
4387eb97b293Sdan   ){
43889ff27ecdSdrh     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
4389c02372ceSdrh     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
4390c864912aSdan     pPager->dbHintSize = pPager->dbSize;
43919ff27ecdSdrh   }
43929ff27ecdSdrh 
4393bea2a948Sdanielk1977   while( rc==SQLITE_OK && pList ){
4394bea2a948Sdanielk1977     Pgno pgno = pList->pgno;
43957a2b1eebSdanielk1977 
4396687566d7Sdanielk1977     /* If there are dirty pages in the page cache with page numbers greater
4397f90b7260Sdanielk1977     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
4398687566d7Sdanielk1977     ** make the file smaller (presumably by auto-vacuum code). Do not write
4399687566d7Sdanielk1977     ** any such pages to the file.
4400bea2a948Sdanielk1977     **
4401bea2a948Sdanielk1977     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
44025b47efa6Sdrh     ** set (set by sqlite3PagerDontWrite()).
4403687566d7Sdanielk1977     */
4404bea2a948Sdanielk1977     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
4405bea2a948Sdanielk1977       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
440685d2bd22Sdrh       char *pData;                                   /* Data to write */
440785d2bd22Sdrh 
440851133eaeSdan       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
4409d40d7ec7Sdrh       if( pList->pgno==1 ) pager_write_changecounter(pList);
441051133eaeSdan 
4411b48c0d59Sdrh       pData = pList->pData;
4412443c0597Sdanielk1977 
4413bea2a948Sdanielk1977       /* Write out the page data. */
4414f23da966Sdan       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
4415bea2a948Sdanielk1977 
4416bea2a948Sdanielk1977       /* If page 1 was just written, update Pager.dbFileVers to match
4417bea2a948Sdanielk1977       ** the value now stored in the database file. If writing this
4418bea2a948Sdanielk1977       ** page caused the database file to grow, update dbFileSize.
4419bea2a948Sdanielk1977       */
4420bea2a948Sdanielk1977       if( pgno==1 ){
442145d6882fSdanielk1977         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
4422687566d7Sdanielk1977       }
4423bea2a948Sdanielk1977       if( pgno>pPager->dbFileSize ){
4424bea2a948Sdanielk1977         pPager->dbFileSize = pgno;
442545d6882fSdanielk1977       }
44269ad3ee40Sdrh       pPager->aStat[PAGER_STAT_WRITE]++;
4427bea2a948Sdanielk1977 
44280410302eSdanielk1977       /* Update any backup objects copying the contents of this pager. */
44290719ee29Sdrh       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
44300410302eSdanielk1977 
4431bea2a948Sdanielk1977       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
4432bea2a948Sdanielk1977                    PAGERID(pPager), pgno, pager_pagehash(pList)));
4433bea2a948Sdanielk1977       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
4434bea2a948Sdanielk1977       PAGER_INCR(sqlite3_pager_writedb_count);
4435bea2a948Sdanielk1977     }else{
4436bea2a948Sdanielk1977       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
443745d6882fSdanielk1977     }
44385f848c3aSdan     pager_set_pagehash(pList);
44392554f8b0Sdrh     pList = pList->pDirty;
44402554f8b0Sdrh   }
44418c0a791aSdanielk1977 
4442bea2a948Sdanielk1977   return rc;
44432554f8b0Sdrh }
44442554f8b0Sdrh 
44452554f8b0Sdrh /*
4446459564f4Sdan ** Ensure that the sub-journal file is open. If it is already open, this
4447459564f4Sdan ** function is a no-op.
4448459564f4Sdan **
4449459564f4Sdan ** SQLITE_OK is returned if everything goes according to plan. An
4450459564f4Sdan ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
4451459564f4Sdan ** fails.
4452459564f4Sdan */
openSubJournal(Pager * pPager)4453459564f4Sdan static int openSubJournal(Pager *pPager){
4454459564f4Sdan   int rc = SQLITE_OK;
4455459564f4Sdan   if( !isOpen(pPager->sjfd) ){
44566e76326dSdan     const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
44576e76326dSdan       | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
44586e76326dSdan       | SQLITE_OPEN_DELETEONCLOSE;
44598c71a98cSdrh     int nStmtSpill = sqlite3Config.nStmtSpill;
4460459564f4Sdan     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
44618c71a98cSdrh       nStmtSpill = -1;
4462459564f4Sdan     }
44638c71a98cSdrh     rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
4464459564f4Sdan   }
4465459564f4Sdan   return rc;
4466459564f4Sdan }
4467459564f4Sdan 
4468459564f4Sdan /*
4469bea2a948Sdanielk1977 ** Append a record of the current state of page pPg to the sub-journal.
4470bea2a948Sdanielk1977 **
4471bea2a948Sdanielk1977 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
4472bea2a948Sdanielk1977 ** for all open savepoints before returning.
4473bea2a948Sdanielk1977 **
4474bea2a948Sdanielk1977 ** This function returns SQLITE_OK if everything is successful, an IO
4475bea2a948Sdanielk1977 ** error code if the attempt to write to the sub-journal fails, or
4476bea2a948Sdanielk1977 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
4477bea2a948Sdanielk1977 ** bitvec.
4478f2c31ad8Sdanielk1977 */
subjournalPage(PgHdr * pPg)4479f2c31ad8Sdanielk1977 static int subjournalPage(PgHdr *pPg){
4480651a52faSdanielk1977   int rc = SQLITE_OK;
4481f2c31ad8Sdanielk1977   Pager *pPager = pPg->pPager;
4482459564f4Sdan   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
4483459564f4Sdan 
4484459564f4Sdan     /* Open the sub-journal, if it has not already been opened */
4485459564f4Sdan     assert( pPager->useJournal );
4486459564f4Sdan     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
4487459564f4Sdan     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
4488459564f4Sdan     assert( pagerUseWal(pPager)
44895dee6afcSdrh          || pageInJournal(pPager, pPg)
4490459564f4Sdan          || pPg->pgno>pPager->dbOrigSize
4491459564f4Sdan     );
4492459564f4Sdan     rc = openSubJournal(pPager);
4493459564f4Sdan 
4494459564f4Sdan     /* If the sub-journal was opened successfully (or was already open),
4495459564f4Sdan     ** write the journal record into the file.  */
4496459564f4Sdan     if( rc==SQLITE_OK ){
4497651a52faSdanielk1977       void *pData = pPg->pData;
44987c3210e6Sdan       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
449985d2bd22Sdrh       char *pData2;
4500614c6a09Sdrh       pData2 = pData;
450130d53701Sdrh       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
4502f2c31ad8Sdanielk1977       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
4503f2c31ad8Sdanielk1977       if( rc==SQLITE_OK ){
4504f2c31ad8Sdanielk1977         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
4505f2c31ad8Sdanielk1977       }
4506651a52faSdanielk1977     }
4507459564f4Sdan   }
4508f2c31ad8Sdanielk1977   if( rc==SQLITE_OK ){
4509bea2a948Sdanielk1977     pPager->nSubRec++;
4510f2c31ad8Sdanielk1977     assert( pPager->nSavepoint>0 );
4511f2c31ad8Sdanielk1977     rc = addToSavepointBitvecs(pPager, pPg->pgno);
4512f2c31ad8Sdanielk1977   }
4513f2c31ad8Sdanielk1977   return rc;
4514f2c31ad8Sdanielk1977 }
subjournalPageIfRequired(PgHdr * pPg)451560e32edbSdrh static int subjournalPageIfRequired(PgHdr *pPg){
451660e32edbSdrh   if( subjRequiresPage(pPg) ){
451760e32edbSdrh     return subjournalPage(pPg);
451860e32edbSdrh   }else{
451960e32edbSdrh     return SQLITE_OK;
452060e32edbSdrh   }
452160e32edbSdrh }
4522f2c31ad8Sdanielk1977 
45233306c4a9Sdan /*
45248c0a791aSdanielk1977 ** This function is called by the pcache layer when it has reached some
4525bea2a948Sdanielk1977 ** soft memory limit. The first argument is a pointer to a Pager object
4526bea2a948Sdanielk1977 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
4527bea2a948Sdanielk1977 ** database). The second argument is a reference to a page that is
4528bea2a948Sdanielk1977 ** currently dirty but has no outstanding references. The page
4529bea2a948Sdanielk1977 ** is always associated with the Pager object passed as the first
4530bea2a948Sdanielk1977 ** argument.
4531bea2a948Sdanielk1977 **
4532bea2a948Sdanielk1977 ** The job of this function is to make pPg clean by writing its contents
4533bea2a948Sdanielk1977 ** out to the database file, if possible. This may involve syncing the
4534bea2a948Sdanielk1977 ** journal file.
4535bea2a948Sdanielk1977 **
4536bea2a948Sdanielk1977 ** If successful, sqlite3PcacheMakeClean() is called on the page and
4537bea2a948Sdanielk1977 ** SQLITE_OK returned. If an IO error occurs while trying to make the
4538bea2a948Sdanielk1977 ** page clean, the IO error code is returned. If the page cannot be
4539bea2a948Sdanielk1977 ** made clean for some other reason, but no error occurs, then SQLITE_OK
4540bea2a948Sdanielk1977 ** is returned by sqlite3PcacheMakeClean() is not called.
45412554f8b0Sdrh */
pagerStress(void * p,PgHdr * pPg)4542a858aa2eSdanielk1977 static int pagerStress(void *p, PgHdr *pPg){
45438c0a791aSdanielk1977   Pager *pPager = (Pager *)p;
45448c0a791aSdanielk1977   int rc = SQLITE_OK;
45458f2e9a1aSdrh 
4546bea2a948Sdanielk1977   assert( pPg->pPager==pPager );
4547bea2a948Sdanielk1977   assert( pPg->flags&PGHDR_DIRTY );
4548bea2a948Sdanielk1977 
454940c3941cSdrh   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
4550314f30dbSdrh   ** journal (and adding a new header) is not allowed.  This occurs
4551314f30dbSdrh   ** during calls to sqlite3PagerWrite() while trying to journal multiple
4552314f30dbSdrh   ** pages belonging to the same sector.
45537cf4c7adSdrh   **
455440c3941cSdrh   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
455540c3941cSdrh   ** regardless of whether or not a sync is required.  This is set during
455640c3941cSdrh   ** a rollback or by user request, respectively.
4557314f30dbSdrh   **
45580028486bSdrh   ** Spilling is also prohibited when in an error state since that could
455960ec914cSpeter.d.reid   ** lead to database corruption.   In the current implementation it
4560c3031c61Sdrh   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
45610028486bSdrh   ** while in the error state, hence it is impossible for this routine to
45620028486bSdrh   ** be called in the error state.  Nevertheless, we include a NEVER()
45630028486bSdrh   ** test for the error state as a safeguard against future changes.
45647cf4c7adSdrh   */
45650028486bSdrh   if( NEVER(pPager->errCode) ) return SQLITE_OK;
456640c3941cSdrh   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
456740c3941cSdrh   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
456840c3941cSdrh   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
456940c3941cSdrh   if( pPager->doNotSpill
457040c3941cSdrh    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
457140c3941cSdrh       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
457240c3941cSdrh   ){
45737cf4c7adSdrh     return SQLITE_OK;
45747cf4c7adSdrh   }
45757cf4c7adSdrh 
4576ffc78a41Sdrh   pPager->aStat[PAGER_STAT_SPILL]++;
45774a4b01dcSdan   pPg->pDirty = 0;
45787ed91f23Sdrh   if( pagerUseWal(pPager) ){
45794cc6fb61Sdan     /* Write a single frame for this page to the log. */
458060e32edbSdrh     rc = subjournalPageIfRequired(pPg);
45814cd78b4dSdan     if( rc==SQLITE_OK ){
45824eb02a45Sdrh       rc = pagerWalFrames(pPager, pPg, 0, 0);
45834cd78b4dSdan     }
45844cc6fb61Sdan   }else{
45858c20014aSdanielk1977 
4586d67a9770Sdan #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
4587efe16971Sdan     if( pPager->tempFile==0 ){
4588efe16971Sdan       rc = sqlite3JournalCreate(pPager->jfd);
4589efe16971Sdan       if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
4590efe16971Sdan     }
4591efe16971Sdan #endif
4592efe16971Sdan 
4593bea2a948Sdanielk1977     /* Sync the journal file if required. */
4594c864912aSdan     if( pPg->flags&PGHDR_NEED_SYNC
4595c864912aSdan      || pPager->eState==PAGER_WRITER_CACHEMOD
4596c864912aSdan     ){
4597937ac9daSdan       rc = syncJournal(pPager, 1);
45988c0a791aSdanielk1977     }
4599bea2a948Sdanielk1977 
4600bea2a948Sdanielk1977     /* Write the contents of the page out to the database file. */
460145d6882fSdanielk1977     if( rc==SQLITE_OK ){
460251133eaeSdan       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
4603146151cdSdrh       rc = pager_write_pagelist(pPager, pPg);
46048c0a791aSdanielk1977     }
46054cc6fb61Sdan   }
4606a858aa2eSdanielk1977 
4607bea2a948Sdanielk1977   /* Mark the page as clean. */
4608a858aa2eSdanielk1977   if( rc==SQLITE_OK ){
460930d53701Sdrh     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
4610a858aa2eSdanielk1977     sqlite3PcacheMakeClean(pPg);
46118c0a791aSdanielk1977   }
4612bea2a948Sdanielk1977 
4613bea2a948Sdanielk1977   return pager_error(pPager, rc);
46148c0a791aSdanielk1977 }
46158c0a791aSdanielk1977 
46166fa255fdSdan /*
46176fa255fdSdan ** Flush all unreferenced dirty pages to disk.
46186fa255fdSdan */
sqlite3PagerFlush(Pager * pPager)46196fa255fdSdan int sqlite3PagerFlush(Pager *pPager){
4620dbf6773eSdan   int rc = pPager->errCode;
46219fb13abcSdan   if( !MEMDB ){
46226fa255fdSdan     PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
4623dbf6773eSdan     assert( assert_pager_state(pPager) );
46246fa255fdSdan     while( rc==SQLITE_OK && pList ){
46256fa255fdSdan       PgHdr *pNext = pList->pDirty;
46266fa255fdSdan       if( pList->nRef==0 ){
46276fa255fdSdan         rc = pagerStress((void*)pPager, pList);
46286fa255fdSdan       }
46296fa255fdSdan       pList = pNext;
46306fa255fdSdan     }
46319fb13abcSdan   }
46326fa255fdSdan 
46336fa255fdSdan   return rc;
46346fa255fdSdan }
46352554f8b0Sdrh 
46362554f8b0Sdrh /*
4637bea2a948Sdanielk1977 ** Allocate and initialize a new Pager object and put a pointer to it
4638bea2a948Sdanielk1977 ** in *ppPager. The pager should eventually be freed by passing it
4639bea2a948Sdanielk1977 ** to sqlite3PagerClose().
4640bea2a948Sdanielk1977 **
4641bea2a948Sdanielk1977 ** The zFilename argument is the path to the database file to open.
4642bea2a948Sdanielk1977 ** If zFilename is NULL then a randomly-named temporary file is created
4643bea2a948Sdanielk1977 ** and used as the file to be cached. Temporary files are be deleted
4644bea2a948Sdanielk1977 ** automatically when they are closed. If zFilename is ":memory:" then
4645bea2a948Sdanielk1977 ** all information is held in cache. It is never written to disk.
4646bea2a948Sdanielk1977 ** This can be used to implement an in-memory database.
4647bea2a948Sdanielk1977 **
4648bea2a948Sdanielk1977 ** The nExtra parameter specifies the number of bytes of space allocated
4649bea2a948Sdanielk1977 ** along with each page reference. This space is available to the user
4650a2ee589cSdrh ** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
4651a2ee589cSdrh ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
4652a2ee589cSdrh ** (The extra space is used by btree as the MemPage object.)
4653bea2a948Sdanielk1977 **
4654bea2a948Sdanielk1977 ** The flags argument is used to specify properties that affect the
4655bea2a948Sdanielk1977 ** operation of the pager. It should be passed some bitwise combination
465633f111dcSdrh ** of the PAGER_* flags.
4657bea2a948Sdanielk1977 **
4658bea2a948Sdanielk1977 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
4659bea2a948Sdanielk1977 ** of the xOpen() method of the supplied VFS when opening files.
4660bea2a948Sdanielk1977 **
4661bea2a948Sdanielk1977 ** If the pager object is allocated and the specified file opened
4662bea2a948Sdanielk1977 ** successfully, SQLITE_OK is returned and *ppPager set to point to
4663bea2a948Sdanielk1977 ** the new pager object. If an error occurs, *ppPager is set to NULL
4664bea2a948Sdanielk1977 ** and error code returned. This function may return SQLITE_NOMEM
4665bea2a948Sdanielk1977 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
4666bea2a948Sdanielk1977 ** various SQLITE_IO_XXX errors.
4667bea2a948Sdanielk1977 */
sqlite3PagerOpen(sqlite3_vfs * pVfs,Pager ** ppPager,const char * zFilename,int nExtra,int flags,int vfsFlags,void (* xReinit)(DbPage *))4668bea2a948Sdanielk1977 int sqlite3PagerOpen(
4669bea2a948Sdanielk1977   sqlite3_vfs *pVfs,       /* The virtual file system to use */
4670bea2a948Sdanielk1977   Pager **ppPager,         /* OUT: Return the Pager structure here */
4671bea2a948Sdanielk1977   const char *zFilename,   /* Name of the database file to open */
4672bea2a948Sdanielk1977   int nExtra,              /* Extra bytes append to each in-memory page */
4673bea2a948Sdanielk1977   int flags,               /* flags controlling this file */
46744775ecd0Sdrh   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
46754775ecd0Sdrh   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
4676bea2a948Sdanielk1977 ){
4677bea2a948Sdanielk1977   u8 *pPtr;
4678bea2a948Sdanielk1977   Pager *pPager = 0;       /* Pager object to allocate and return */
4679bea2a948Sdanielk1977   int rc = SQLITE_OK;      /* Return code */
4680bea2a948Sdanielk1977   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
4681bea2a948Sdanielk1977   int memDb = 0;           /* True if this is an in-memory file */
46828d889afcSdrh #ifndef SQLITE_OMIT_DESERIALIZE
4683ac442f41Sdrh   int memJM = 0;           /* Memory journal mode */
46849c6396ecSdrh #else
46859c6396ecSdrh # define memJM 0
46869c6396ecSdrh #endif
4687bea2a948Sdanielk1977   int readOnly = 0;        /* True if this is a read-only file */
4688bea2a948Sdanielk1977   int journalFileSize;     /* Bytes to allocate for each journal fd */
4689bea2a948Sdanielk1977   char *zPathname = 0;     /* Full path to database file */
4690bea2a948Sdanielk1977   int nPathname = 0;       /* Number of bytes in zPathname */
4691bea2a948Sdanielk1977   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
4692bea2a948Sdanielk1977   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
4693b2eced5dSdrh   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
4694cd74b611Sdan   const char *zUri = 0;    /* URI args to copy */
4695746461f1Sdrh   int nUriByte = 1;        /* Number of bytes of URI args at *zUri */
4696746461f1Sdrh   int nUri = 0;            /* Number of URI parameters */
4697bea2a948Sdanielk1977 
4698bea2a948Sdanielk1977   /* Figure out how much space is required for each journal file-handle
46992491de28Sdan   ** (there are two of them, the main journal and the sub-journal).  */
4700ea598cbdSdrh   journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
4701bea2a948Sdanielk1977 
4702bea2a948Sdanielk1977   /* Set the output variable to NULL in case an error occurs. */
4703bea2a948Sdanielk1977   *ppPager = 0;
4704bea2a948Sdanielk1977 
470575c014c3Sdrh #ifndef SQLITE_OMIT_MEMORYDB
470675c014c3Sdrh   if( flags & PAGER_MEMORY ){
470775c014c3Sdrh     memDb = 1;
4708d4e0bb0eSdrh     if( zFilename && zFilename[0] ){
4709afc8b7f0Sdrh       zPathname = sqlite3DbStrDup(0, zFilename);
4710fad3039cSmistachkin       if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
4711afc8b7f0Sdrh       nPathname = sqlite3Strlen30(zPathname);
471275c014c3Sdrh       zFilename = 0;
471375c014c3Sdrh     }
47144ab9d254Sdrh   }
471575c014c3Sdrh #endif
471675c014c3Sdrh 
4717bea2a948Sdanielk1977   /* Compute and store the full pathname in an allocated buffer pointed
4718bea2a948Sdanielk1977   ** to by zPathname, length nPathname. Or, if this is a temporary file,
4719bea2a948Sdanielk1977   ** leave both nPathname and zPathname set to 0.
4720bea2a948Sdanielk1977   */
4721bea2a948Sdanielk1977   if( zFilename && zFilename[0] ){
4722cd74b611Sdan     const char *z;
4723bea2a948Sdanielk1977     nPathname = pVfs->mxPathname+1;
4724a879342bSdan     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
4725bea2a948Sdanielk1977     if( zPathname==0 ){
4726fad3039cSmistachkin       return SQLITE_NOMEM_BKPT;
4727bea2a948Sdanielk1977     }
4728e8df800dSdrh     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
4729bea2a948Sdanielk1977     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
4730c398c65bSdrh     if( rc!=SQLITE_OK ){
4731c398c65bSdrh       if( rc==SQLITE_OK_SYMLINK ){
4732c398c65bSdrh         if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){
4733c398c65bSdrh           rc = SQLITE_CANTOPEN_SYMLINK;
4734c398c65bSdrh         }else{
4735c398c65bSdrh           rc = SQLITE_OK;
4736c398c65bSdrh         }
4737c398c65bSdrh       }
4738c398c65bSdrh     }
4739bea2a948Sdanielk1977     nPathname = sqlite3Strlen30(zPathname);
4740cd74b611Sdan     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
4741cd74b611Sdan     while( *z ){
4742746461f1Sdrh       z += strlen(z)+1;
4743746461f1Sdrh       z += strlen(z)+1;
4744746461f1Sdrh       nUri++;
4745cd74b611Sdan     }
4746879f1a1eSdan     nUriByte = (int)(&z[1] - zUri);
4747746461f1Sdrh     assert( nUriByte>=1 );
4748bea2a948Sdanielk1977     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
4749bea2a948Sdanielk1977       /* This branch is taken when the journal path required by
4750bea2a948Sdanielk1977       ** the database being opened will be more than pVfs->mxPathname
4751bea2a948Sdanielk1977       ** bytes in length. This means the database cannot be opened,
4752bea2a948Sdanielk1977       ** as it will not be possible to open the journal file or even
4753bea2a948Sdanielk1977       ** check for a hot-journal before reading.
4754bea2a948Sdanielk1977       */
47559978c97eSdrh       rc = SQLITE_CANTOPEN_BKPT;
4756bea2a948Sdanielk1977     }
4757bea2a948Sdanielk1977     if( rc!=SQLITE_OK ){
4758a879342bSdan       sqlite3DbFree(0, zPathname);
4759bea2a948Sdanielk1977       return rc;
4760bea2a948Sdanielk1977     }
4761bea2a948Sdanielk1977   }
4762bea2a948Sdanielk1977 
4763bea2a948Sdanielk1977   /* Allocate memory for the Pager structure, PCache object, the
4764bea2a948Sdanielk1977   ** three file descriptors, the database file name and the journal
4765bea2a948Sdanielk1977   ** file name. The layout in memory is as follows:
4766bea2a948Sdanielk1977   **
4767bea2a948Sdanielk1977   **     Pager object                    (sizeof(Pager) bytes)
4768bea2a948Sdanielk1977   **     PCache object                   (sqlite3PcacheSize() bytes)
4769bea2a948Sdanielk1977   **     Database file handle            (pVfs->szOsFile bytes)
4770bea2a948Sdanielk1977   **     Sub-journal file handle         (journalFileSize bytes)
4771bea2a948Sdanielk1977   **     Main journal file handle        (journalFileSize bytes)
4772480620c7Sdrh   **     Ptr back to the Pager           (sizeof(Pager*) bytes)
4773532b0d23Sdrh   **     \0\0\0\0 database prefix        (4 bytes)
4774bea2a948Sdanielk1977   **     Database file name              (nPathname+1 bytes)
47758875b9e7Sdrh   **     URI query parameters            (nUriByte bytes)
4776532b0d23Sdrh   **     Journal filename                (nPathname+8+1 bytes)
4777532b0d23Sdrh   **     WAL filename                    (nPathname+4+1 bytes)
4778532b0d23Sdrh   **     \0\0\0 terminator               (3 bytes)
4779532b0d23Sdrh   **
4780532b0d23Sdrh   ** Some 3rd-party software, over which we have no control, depends on
4781532b0d23Sdrh   ** the specific order of the filenames and the \0 separators between them
4782532b0d23Sdrh   ** so that it can (for example) find the database filename given the WAL
4783532b0d23Sdrh   ** filename without using the sqlite3_filename_database() API.  This is a
4784532b0d23Sdrh   ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
4785532b0d23Sdrh   ** software is in widespread use, so we try to avoid changing the filename
4786532b0d23Sdrh   ** order and formatting if possible.  In particular, the details of the
4787532b0d23Sdrh   ** filename format expected by 3rd-party software should be as follows:
4788532b0d23Sdrh   **
4789532b0d23Sdrh   **   - Main Database Path
4790532b0d23Sdrh   **   - \0
4791532b0d23Sdrh   **   - Multiple URI components consisting of:
4792532b0d23Sdrh   **     - Key
4793532b0d23Sdrh   **     - \0
4794532b0d23Sdrh   **     - Value
4795532b0d23Sdrh   **     - \0
4796532b0d23Sdrh   **   - \0
4797532b0d23Sdrh   **   - Journal Path
4798532b0d23Sdrh   **   - \0
4799532b0d23Sdrh   **   - WAL Path (zWALName)
4800532b0d23Sdrh   **   - \0
48014defdddcSdrh   **
48024defdddcSdrh   ** The sqlite3_create_filename() interface and the databaseFilename() utility
48034defdddcSdrh   ** that is used by sqlite3_filename_database() and kin also depend on the
48044defdddcSdrh   ** specific formatting and order of the various filenames, so if the format
48054defdddcSdrh   ** changes here, be sure to change it there as well.
4806bea2a948Sdanielk1977   */
4807bea2a948Sdanielk1977   pPtr = (u8 *)sqlite3MallocZero(
4808ea598cbdSdrh     ROUND8(sizeof(*pPager)) +            /* Pager structure */
4809ea598cbdSdrh     ROUND8(pcacheSize) +                 /* PCache object */
4810ea598cbdSdrh     ROUND8(pVfs->szOsFile) +             /* The main db file */
4811bea2a948Sdanielk1977     journalFileSize * 2 +                /* The two journal files */
4812480620c7Sdrh     sizeof(pPager) +                     /* Space to hold a pointer */
4813532b0d23Sdrh     4 +                                  /* Database prefix */
48148080403eSdrh     nPathname + 1 +                      /* database filename */
48158080403eSdrh     nUriByte +                           /* query parameters */
4816532b0d23Sdrh     nPathname + 8 + 1 +                  /* Journal filename */
4817532b0d23Sdrh #ifndef SQLITE_OMIT_WAL
4818532b0d23Sdrh     nPathname + 4 + 1 +                  /* WAL filename */
4819532b0d23Sdrh #endif
4820532b0d23Sdrh     3                                    /* Terminator */
4821bea2a948Sdanielk1977   );
482260a4b538Sshane   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
4823bea2a948Sdanielk1977   if( !pPtr ){
4824a879342bSdan     sqlite3DbFree(0, zPathname);
4825fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
4826bea2a948Sdanielk1977   }
48278875b9e7Sdrh   pPager = (Pager*)pPtr;                  pPtr += ROUND8(sizeof(*pPager));
48288875b9e7Sdrh   pPager->pPCache = (PCache*)pPtr;        pPtr += ROUND8(pcacheSize);
48298875b9e7Sdrh   pPager->fd = (sqlite3_file*)pPtr;       pPtr += ROUND8(pVfs->szOsFile);
48308875b9e7Sdrh   pPager->sjfd = (sqlite3_file*)pPtr;     pPtr += journalFileSize;
48318875b9e7Sdrh   pPager->jfd =  (sqlite3_file*)pPtr;     pPtr += journalFileSize;
4832ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
4833480620c7Sdrh   memcpy(pPtr, &pPager, sizeof(pPager));  pPtr += sizeof(pPager);
4834bea2a948Sdanielk1977 
4835532b0d23Sdrh   /* Fill in the Pager.zFilename and pPager.zQueryParam fields */
4836532b0d23Sdrh                                           pPtr += 4;  /* Skip zero prefix */
4837532b0d23Sdrh   pPager->zFilename = (char*)pPtr;
4838532b0d23Sdrh   if( nPathname>0 ){
4839532b0d23Sdrh     memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname + 1;
4840532b0d23Sdrh     if( zUri ){
4841532b0d23Sdrh       memcpy(pPtr, zUri, nUriByte);       pPtr += nUriByte;
4842532b0d23Sdrh     }else{
4843532b0d23Sdrh                                           pPtr++;
4844532b0d23Sdrh     }
4845532b0d23Sdrh   }
4846532b0d23Sdrh 
48478080403eSdrh 
48488080403eSdrh   /* Fill in Pager.zJournal */
48498080403eSdrh   if( nPathname>0 ){
48508080403eSdrh     pPager->zJournal = (char*)pPtr;
48518080403eSdrh     memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;
48528080403eSdrh     memcpy(pPtr, "-journal",8);           pPtr += 8 + 1;
48538080403eSdrh #ifdef SQLITE_ENABLE_8_3_NAMES
48548080403eSdrh     sqlite3FileSuffix3(zFilename,pPager->zJournal);
48558080403eSdrh     pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
48568080403eSdrh #endif
48578080403eSdrh   }else{
48588080403eSdrh     pPager->zJournal = 0;
48598080403eSdrh   }
48608875b9e7Sdrh 
48613e875ef3Sdan #ifndef SQLITE_OMIT_WAL
48628875b9e7Sdrh   /* Fill in Pager.zWal */
48638080403eSdrh   if( nPathname>0 ){
48648875b9e7Sdrh     pPager->zWal = (char*)pPtr;
48658080403eSdrh     memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;
48668080403eSdrh     memcpy(pPtr, "-wal", 4);              pPtr += 4 + 1;
48678080403eSdrh #ifdef SQLITE_ENABLE_8_3_NAMES
48688080403eSdrh     sqlite3FileSuffix3(zFilename, pPager->zWal);
48698080403eSdrh     pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
48708080403eSdrh #endif
48718080403eSdrh   }else{
48728080403eSdrh     pPager->zWal = 0;
48738080403eSdrh   }
48743e875ef3Sdan #endif
4875e85e1da0Sdrh   (void)pPtr;  /* Suppress warning about unused pPtr value */
48768875b9e7Sdrh 
48778875b9e7Sdrh   if( nPathname ) sqlite3DbFree(0, zPathname);
4878bea2a948Sdanielk1977   pPager->pVfs = pVfs;
4879bea2a948Sdanielk1977   pPager->vfsFlags = vfsFlags;
4880bea2a948Sdanielk1977 
4881bea2a948Sdanielk1977   /* Open the pager file.
4882bea2a948Sdanielk1977   */
48838c96a6eaSdrh   if( zFilename && zFilename[0] ){
4884bea2a948Sdanielk1977     int fout = 0;                    /* VFS flags returned by xOpen() */
4885bea2a948Sdanielk1977     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
48868c96a6eaSdrh     assert( !memDb );
48878d889afcSdrh #ifndef SQLITE_OMIT_DESERIALIZE
4888021e228eSdrh     pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
48899c6396ecSdrh #endif
4890ac442f41Sdrh     readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
4891bea2a948Sdanielk1977 
4892bea2a948Sdanielk1977     /* If the file was successfully opened for read/write access,
4893bea2a948Sdanielk1977     ** choose a default page size in case we have to create the
4894bea2a948Sdanielk1977     ** database file. The default page size is the maximum of:
4895bea2a948Sdanielk1977     **
4896bea2a948Sdanielk1977     **    + SQLITE_DEFAULT_PAGE_SIZE,
4897bea2a948Sdanielk1977     **    + The value returned by sqlite3OsSectorSize()
4898bea2a948Sdanielk1977     **    + The largest page size that can be written atomically.
4899bea2a948Sdanielk1977     */
4900d1ae96d3Sdrh     if( rc==SQLITE_OK ){
4901d1ae96d3Sdrh       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
49026451c2b0Sdrh       if( !readOnly ){
4903bea2a948Sdanielk1977         setSectorSize(pPager);
4904d87897dfSshane         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
4905bea2a948Sdanielk1977         if( szPageDflt<pPager->sectorSize ){
4906d87897dfSshane           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
4907d87897dfSshane             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
4908d87897dfSshane           }else{
4909b2eced5dSdrh             szPageDflt = (u32)pPager->sectorSize;
4910d87897dfSshane           }
4911bea2a948Sdanielk1977         }
4912bea2a948Sdanielk1977 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
4913bea2a948Sdanielk1977         {
4914bea2a948Sdanielk1977           int ii;
4915bea2a948Sdanielk1977           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
4916bea2a948Sdanielk1977           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
4917bea2a948Sdanielk1977           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
4918bea2a948Sdanielk1977           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
4919bea2a948Sdanielk1977             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
4920bea2a948Sdanielk1977               szPageDflt = ii;
4921bea2a948Sdanielk1977             }
4922bea2a948Sdanielk1977           }
4923bea2a948Sdanielk1977         }
4924bea2a948Sdanielk1977 #endif
49256451c2b0Sdrh       }
49268875b9e7Sdrh       pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
4927d1ae96d3Sdrh       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
49288875b9e7Sdrh        || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
4929d1ae96d3Sdrh           vfsFlags |= SQLITE_OPEN_READONLY;
4930d1ae96d3Sdrh           goto act_like_temp_file;
4931d1ae96d3Sdrh       }
4932d1ae96d3Sdrh     }
4933bea2a948Sdanielk1977   }else{
4934bea2a948Sdanielk1977     /* If a temporary file is requested, it is not opened immediately.
4935bea2a948Sdanielk1977     ** In this case we accept the default page size and delay actually
4936bea2a948Sdanielk1977     ** opening the file until the first call to OsWrite().
4937bea2a948Sdanielk1977     **
4938bea2a948Sdanielk1977     ** This branch is also run for an in-memory database. An in-memory
4939bea2a948Sdanielk1977     ** database is the same as a temp-file that is never written out to
4940bea2a948Sdanielk1977     ** disk and uses an in-memory rollback journal.
494157fe136bSdrh     **
494257fe136bSdrh     ** This branch also runs for files marked as immutable.
4943bea2a948Sdanielk1977     */
4944d1ae96d3Sdrh act_like_temp_file:
4945bea2a948Sdanielk1977     tempFile = 1;
494657fe136bSdrh     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
4947e399ac2eSdrh     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
494857fe136bSdrh     pPager->noLock = 1;                /* Do no locking */
4949aed24608Sdrh     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
4950bea2a948Sdanielk1977   }
4951bea2a948Sdanielk1977 
4952bea2a948Sdanielk1977   /* The following call to PagerSetPagesize() serves to set the value of
4953bea2a948Sdanielk1977   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
4954bea2a948Sdanielk1977   */
4955bea2a948Sdanielk1977   if( rc==SQLITE_OK ){
4956bea2a948Sdanielk1977     assert( pPager->memDb==0 );
4957fa9601a9Sdrh     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
4958bea2a948Sdanielk1977     testcase( rc!=SQLITE_OK );
4959bea2a948Sdanielk1977   }
4960bea2a948Sdanielk1977 
4961c3031c61Sdrh   /* Initialize the PCache object. */
4962c3031c61Sdrh   if( rc==SQLITE_OK ){
4963c3031c61Sdrh     nExtra = ROUND8(nExtra);
4964a2ee589cSdrh     assert( nExtra>=8 && nExtra<1000 );
4965c3031c61Sdrh     rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
4966c3031c61Sdrh                        !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
4967c3031c61Sdrh   }
4968c3031c61Sdrh 
4969c3031c61Sdrh   /* If an error occurred above, free the  Pager structure and close the file.
4970bea2a948Sdanielk1977   */
4971bea2a948Sdanielk1977   if( rc!=SQLITE_OK ){
4972bea2a948Sdanielk1977     sqlite3OsClose(pPager->fd);
4973c3031c61Sdrh     sqlite3PageFree(pPager->pTmpSpace);
4974bea2a948Sdanielk1977     sqlite3_free(pPager);
4975bea2a948Sdanielk1977     return rc;
4976bea2a948Sdanielk1977   }
4977bea2a948Sdanielk1977 
4978bea2a948Sdanielk1977   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
4979bea2a948Sdanielk1977   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
4980bea2a948Sdanielk1977 
4981bea2a948Sdanielk1977   pPager->useJournal = (u8)useJournal;
4982bea2a948Sdanielk1977   /* pPager->stmtOpen = 0; */
4983bea2a948Sdanielk1977   /* pPager->stmtInUse = 0; */
4984bea2a948Sdanielk1977   /* pPager->nRef = 0; */
4985bea2a948Sdanielk1977   /* pPager->stmtSize = 0; */
4986bea2a948Sdanielk1977   /* pPager->stmtJSize = 0; */
4987bea2a948Sdanielk1977   /* pPager->nPage = 0; */
4988bea2a948Sdanielk1977   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
4989bea2a948Sdanielk1977   /* pPager->state = PAGER_UNLOCK; */
4990bea2a948Sdanielk1977   /* pPager->errMask = 0; */
4991bea2a948Sdanielk1977   pPager->tempFile = (u8)tempFile;
4992bea2a948Sdanielk1977   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
4993bea2a948Sdanielk1977           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
4994bea2a948Sdanielk1977   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
4995bea2a948Sdanielk1977   pPager->exclusiveMode = (u8)tempFile;
4996bea2a948Sdanielk1977   pPager->changeCountDone = pPager->tempFile;
4997bea2a948Sdanielk1977   pPager->memDb = (u8)memDb;
4998bea2a948Sdanielk1977   pPager->readOnly = (u8)readOnly;
49994775ecd0Sdrh   assert( useJournal || pPager->tempFile );
50004775ecd0Sdrh   pPager->noSync = pPager->tempFile;
50014eb02a45Sdrh   if( pPager->noSync ){
50024eb02a45Sdrh     assert( pPager->fullSync==0 );
50036841b1cbSdrh     assert( pPager->extraSync==0 );
50044eb02a45Sdrh     assert( pPager->syncFlags==0 );
50054eb02a45Sdrh     assert( pPager->walSyncFlags==0 );
50064eb02a45Sdrh   }else{
50074eb02a45Sdrh     pPager->fullSync = 1;
50086841b1cbSdrh     pPager->extraSync = 0;
50094eb02a45Sdrh     pPager->syncFlags = SQLITE_SYNC_NORMAL;
5010daaae7b9Sdrh     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
50114eb02a45Sdrh   }
5012bea2a948Sdanielk1977   /* pPager->pFirst = 0; */
5013bea2a948Sdanielk1977   /* pPager->pFirstSynced = 0; */
5014bea2a948Sdanielk1977   /* pPager->pLast = 0; */
5015fa9601a9Sdrh   pPager->nExtra = (u16)nExtra;
5016bea2a948Sdanielk1977   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
5017bea2a948Sdanielk1977   assert( isOpen(pPager->fd) || tempFile );
5018bea2a948Sdanielk1977   setSectorSize(pPager);
50194775ecd0Sdrh   if( !useJournal ){
50204775ecd0Sdrh     pPager->journalMode = PAGER_JOURNALMODE_OFF;
5021ac442f41Sdrh   }else if( memDb || memJM ){
5022bea2a948Sdanielk1977     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
5023bea2a948Sdanielk1977   }
5024bea2a948Sdanielk1977   /* pPager->xBusyHandler = 0; */
5025bea2a948Sdanielk1977   /* pPager->pBusyHandlerArg = 0; */
50264775ecd0Sdrh   pPager->xReiniter = xReinit;
502712e6f682Sdrh   setGetterMethod(pPager);
5028bea2a948Sdanielk1977   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
50299b4c59faSdrh   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
503029391c5bSdrh 
5031bea2a948Sdanielk1977   *ppPager = pPager;
5032bea2a948Sdanielk1977   return SQLITE_OK;
5033bea2a948Sdanielk1977 }
5034bea2a948Sdanielk1977 
5035480620c7Sdrh /*
5036480620c7Sdrh ** Return the sqlite3_file for the main database given the name
5037480620c7Sdrh ** of the corresonding WAL or Journal name as passed into
5038480620c7Sdrh ** xOpen.
5039480620c7Sdrh */
sqlite3_database_file_object(const char * zName)5040480620c7Sdrh sqlite3_file *sqlite3_database_file_object(const char *zName){
5041480620c7Sdrh   Pager *pPager;
5042480620c7Sdrh   while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
5043480620c7Sdrh     zName--;
5044480620c7Sdrh   }
5045480620c7Sdrh   pPager = *(Pager**)(zName - 4 - sizeof(Pager*));
5046480620c7Sdrh   return pPager->fd;
5047480620c7Sdrh }
5048bea2a948Sdanielk1977 
5049bea2a948Sdanielk1977 
5050bea2a948Sdanielk1977 /*
5051bea2a948Sdanielk1977 ** This function is called after transitioning from PAGER_UNLOCK to
5052bea2a948Sdanielk1977 ** PAGER_SHARED state. It tests if there is a hot journal present in
5053bea2a948Sdanielk1977 ** the file-system for the given pager. A hot journal is one that
5054bea2a948Sdanielk1977 ** needs to be played back. According to this function, a hot-journal
5055ee8b799dSdanielk1977 ** file exists if the following criteria are met:
5056bea2a948Sdanielk1977 **
5057bea2a948Sdanielk1977 **   * The journal file exists in the file system, and
5058bea2a948Sdanielk1977 **   * No process holds a RESERVED or greater lock on the database file, and
5059ee8b799dSdanielk1977 **   * The database file itself is greater than 0 bytes in size, and
5060ee8b799dSdanielk1977 **   * The first byte of the journal file exists and is not 0x00.
5061165ffe97Sdrh **
5062165ffe97Sdrh ** If the current size of the database file is 0 but a journal file
5063165ffe97Sdrh ** exists, that is probably an old journal left over from a prior
5064bea2a948Sdanielk1977 ** database with the same name. In this case the journal file is
5065bea2a948Sdanielk1977 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
5066bea2a948Sdanielk1977 ** is returned.
506782ed1e5bSdrh **
5068067b92baSdrh ** This routine does not check if there is a super-journal filename
5069067b92baSdrh ** at the end of the file. If there is, and that super-journal file
5070ee8b799dSdanielk1977 ** does not exist, then the journal file is not really hot. In this
5071ee8b799dSdanielk1977 ** case this routine will return a false-positive. The pager_playback()
5072ee8b799dSdanielk1977 ** routine will discover that the journal file is not really hot and
5073ee8b799dSdanielk1977 ** will not roll it back.
5074bea2a948Sdanielk1977 **
5075bea2a948Sdanielk1977 ** If a hot-journal file is found to exist, *pExists is set to 1 and
5076bea2a948Sdanielk1977 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
5077bea2a948Sdanielk1977 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
5078bea2a948Sdanielk1977 ** to determine whether or not a hot-journal file exists, the IO error
5079bea2a948Sdanielk1977 ** code is returned and the value of *pExists is undefined.
5080165ffe97Sdrh */
hasHotJournal(Pager * pPager,int * pExists)5081d300b8a3Sdanielk1977 static int hasHotJournal(Pager *pPager, int *pExists){
5082bea2a948Sdanielk1977   sqlite3_vfs * const pVfs = pPager->pVfs;
50832a321c75Sdan   int rc = SQLITE_OK;           /* Return code */
50842a321c75Sdan   int exists = 1;               /* True if a journal file is present */
50852a321c75Sdan   int jrnlOpen = !!isOpen(pPager->jfd);
5086bea2a948Sdanielk1977 
5087d05c223cSdrh   assert( pPager->useJournal );
5088bea2a948Sdanielk1977   assert( isOpen(pPager->fd) );
5089de1ae34eSdan   assert( pPager->eState==PAGER_OPEN );
5090d0864087Sdan 
50918ce49d6aSdan   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
50928ce49d6aSdan     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
50938ce49d6aSdan   ));
5094bea2a948Sdanielk1977 
50950a846f96Sdrh   *pExists = 0;
50962a321c75Sdan   if( !jrnlOpen ){
5097861f7456Sdanielk1977     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
50982a321c75Sdan   }
5099861f7456Sdanielk1977   if( rc==SQLITE_OK && exists ){
5100431b0b42Sdan     int locked = 0;             /* True if some process holds a RESERVED lock */
5101f0039ad8Sdrh 
5102f0039ad8Sdrh     /* Race condition here:  Another process might have been holding the
5103f0039ad8Sdrh     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
5104f0039ad8Sdrh     ** call above, but then delete the journal and drop the lock before
5105f0039ad8Sdrh     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
5106f0039ad8Sdrh     ** is the case, this routine might think there is a hot journal when
5107f0039ad8Sdrh     ** in fact there is none.  This results in a false-positive which will
51089fe769f1Sdrh     ** be dealt with by the playback routine.  Ticket #3883.
5109f0039ad8Sdrh     */
5110861f7456Sdanielk1977     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
5111bea2a948Sdanielk1977     if( rc==SQLITE_OK && !locked ){
5112763afe62Sdan       Pgno nPage;                 /* Number of pages in database file */
5113ee8b799dSdanielk1977 
5114835f22deSdrh       assert( pPager->tempFile==0 );
5115763afe62Sdan       rc = pagerPagecount(pPager, &nPage);
5116d300b8a3Sdanielk1977       if( rc==SQLITE_OK ){
5117f3ccc38aSdrh         /* If the database is zero pages in size, that means that either (1) the
5118f3ccc38aSdrh         ** journal is a remnant from a prior database with the same name where
5119f3ccc38aSdrh         ** the database file but not the journal was deleted, or (2) the initial
5120f3ccc38aSdrh         ** transaction that populates a new database is being rolled back.
5121f3ccc38aSdrh         ** In either case, the journal file can be deleted.  However, take care
5122f3ccc38aSdrh         ** not to delete the journal file if it is already open due to
5123f3ccc38aSdrh         ** journal_mode=PERSIST.
5124f3ccc38aSdrh         */
5125eb443925Smistachkin         if( nPage==0 && !jrnlOpen ){
5126cc0acb26Sdrh           sqlite3BeginBenignMalloc();
51274e004aa6Sdan           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
5128f0039ad8Sdrh             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
512976de8a75Sdan             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
5130f0039ad8Sdrh           }
5131cc0acb26Sdrh           sqlite3EndBenignMalloc();
5132d300b8a3Sdanielk1977         }else{
5133ee8b799dSdanielk1977           /* The journal file exists and no other connection has a reserved
5134ee8b799dSdanielk1977           ** or greater lock on the database file. Now check that there is
5135ee8b799dSdanielk1977           ** at least one non-zero bytes at the start of the journal file.
5136ee8b799dSdanielk1977           ** If there is, then we consider this journal to be hot. If not,
5137ee8b799dSdanielk1977           ** it can be ignored.
5138ee8b799dSdanielk1977           */
51392a321c75Sdan           if( !jrnlOpen ){
5140ee8b799dSdanielk1977             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
5141ee8b799dSdanielk1977             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51422a321c75Sdan           }
5143ee8b799dSdanielk1977           if( rc==SQLITE_OK ){
5144ee8b799dSdanielk1977             u8 first = 0;
5145ee8b799dSdanielk1977             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
5146ee8b799dSdanielk1977             if( rc==SQLITE_IOERR_SHORT_READ ){
5147ee8b799dSdanielk1977               rc = SQLITE_OK;
5148ee8b799dSdanielk1977             }
51492a321c75Sdan             if( !jrnlOpen ){
5150ee8b799dSdanielk1977               sqlite3OsClose(pPager->jfd);
51512a321c75Sdan             }
5152ee8b799dSdanielk1977             *pExists = (first!=0);
5153cc0acb26Sdrh           }else if( rc==SQLITE_CANTOPEN ){
5154f0039ad8Sdrh             /* If we cannot open the rollback journal file in order to see if
515560ec914cSpeter.d.reid             ** it has a zero header, that might be due to an I/O error, or
5156f0039ad8Sdrh             ** it might be due to the race condition described above and in
5157f0039ad8Sdrh             ** ticket #3883.  Either way, assume that the journal is hot.
5158f0039ad8Sdrh             ** This might be a false positive.  But if it is, then the
5159f0039ad8Sdrh             ** automatic journal playback and recovery mechanism will deal
5160f0039ad8Sdrh             ** with it under an EXCLUSIVE lock where we do not need to
5161f0039ad8Sdrh             ** worry so much with race conditions.
5162f0039ad8Sdrh             */
5163f0039ad8Sdrh             *pExists = 1;
5164f0039ad8Sdrh             rc = SQLITE_OK;
5165d300b8a3Sdanielk1977           }
5166d300b8a3Sdanielk1977         }
5167165ffe97Sdrh       }
5168bea2a948Sdanielk1977     }
5169ee8b799dSdanielk1977   }
5170ee8b799dSdanielk1977 
5171d300b8a3Sdanielk1977   return rc;
5172861f7456Sdanielk1977 }
5173861f7456Sdanielk1977 
5174a470aeb4Sdan /*
517589bc4bc6Sdanielk1977 ** This function is called to obtain a shared lock on the database file.
51769584f58cSdrh ** It is illegal to call sqlite3PagerGet() until after this function
517789bc4bc6Sdanielk1977 ** has been successfully called. If a shared-lock is already held when
517889bc4bc6Sdanielk1977 ** this function is called, it is a no-op.
517989bc4bc6Sdanielk1977 **
518089bc4bc6Sdanielk1977 ** The following operations are also performed by this function.
5181393f0689Sdanielk1977 **
5182a81a2207Sdan **   1) If the pager is currently in PAGER_OPEN state (no lock held
5183bea2a948Sdanielk1977 **      on the database file), then an attempt is made to obtain a
5184bea2a948Sdanielk1977 **      SHARED lock on the database file. Immediately after obtaining
5185bea2a948Sdanielk1977 **      the SHARED lock, the file-system is checked for a hot-journal,
5186bea2a948Sdanielk1977 **      which is played back if present. Following any hot-journal
5187bea2a948Sdanielk1977 **      rollback, the contents of the cache are validated by checking
5188bea2a948Sdanielk1977 **      the 'change-counter' field of the database file header and
5189bea2a948Sdanielk1977 **      discarded if they are found to be invalid.
5190bea2a948Sdanielk1977 **
5191bea2a948Sdanielk1977 **   2) If the pager is running in exclusive-mode, and there are currently
5192bea2a948Sdanielk1977 **      no outstanding references to any pages, and is in the error state,
5193bea2a948Sdanielk1977 **      then an attempt is made to clear the error state by discarding
5194bea2a948Sdanielk1977 **      the contents of the page cache and rolling back any open journal
5195bea2a948Sdanielk1977 **      file.
5196bea2a948Sdanielk1977 **
5197a81a2207Sdan ** If everything is successful, SQLITE_OK is returned. If an IO error
5198a81a2207Sdan ** occurs while locking the database, checking for a hot-journal file or
5199a81a2207Sdan ** rolling back a journal file, the IO error code is returned.
5200ed7c855cSdrh */
sqlite3PagerSharedLock(Pager * pPager)520189bc4bc6Sdanielk1977 int sqlite3PagerSharedLock(Pager *pPager){
5202bea2a948Sdanielk1977   int rc = SQLITE_OK;                /* Return code */
5203ed7c855cSdrh 
52048a938f98Sdrh   /* This routine is only called from b-tree and only when there are no
5205763afe62Sdan   ** outstanding pages. This implies that the pager state should either
5206de1ae34eSdan   ** be OPEN or READER. READER is only possible if the pager is or was in
52076572c16aSdan   ** exclusive access mode.  */
52088a938f98Sdrh   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
5209763afe62Sdan   assert( assert_pager_state(pPager) );
5210de1ae34eSdan   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
52116572c16aSdan   assert( pPager->errCode==SQLITE_OK );
52128a938f98Sdrh 
5213de1ae34eSdan   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
5214431b0b42Sdan     int bHotJournal = 1;          /* True if there exists a hot journal-file */
5215d0864087Sdan 
52164e004aa6Sdan     assert( !MEMDB );
52176572c16aSdan     assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
5218d0864087Sdan 
52199281bf2aSdan     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
52209281bf2aSdan     if( rc!=SQLITE_OK ){
522154919f82Sdan       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
5222b22aa4a6Sdan       goto failed;
52239281bf2aSdan     }
52247c24610eSdan 
522513adf8a0Sdanielk1977     /* If a journal file exists, and there is no RESERVED lock on the
522613adf8a0Sdanielk1977     ** database file, then it either needs to be played back or deleted.
5227ed7c855cSdrh     */
5228431b0b42Sdan     if( pPager->eLock<=SHARED_LOCK ){
5229431b0b42Sdan       rc = hasHotJournal(pPager, &bHotJournal);
5230431b0b42Sdan     }
5231d300b8a3Sdanielk1977     if( rc!=SQLITE_OK ){
523252b472aeSdanielk1977       goto failed;
523319db9352Sdrh     }
5234431b0b42Sdan     if( bHotJournal ){
5235e3664fb0Sdan       if( pPager->readOnly ){
5236e3664fb0Sdan         rc = SQLITE_READONLY_ROLLBACK;
5237e3664fb0Sdan         goto failed;
5238e3664fb0Sdan       }
5239e3664fb0Sdan 
524090ba3bd0Sdanielk1977       /* Get an EXCLUSIVE lock on the database file. At this point it is
524190ba3bd0Sdanielk1977       ** important that a RESERVED lock is not obtained on the way to the
524290ba3bd0Sdanielk1977       ** EXCLUSIVE lock. If it were, another process might open the
524390ba3bd0Sdanielk1977       ** database file, detect the RESERVED lock, and conclude that the
5244bea2a948Sdanielk1977       ** database is safe to read while this process is still rolling the
5245bea2a948Sdanielk1977       ** hot-journal back.
524690ba3bd0Sdanielk1977       **
5247bea2a948Sdanielk1977       ** Because the intermediate RESERVED lock is not requested, any
5248bea2a948Sdanielk1977       ** other process attempting to access the database file will get to
5249bea2a948Sdanielk1977       ** this point in the code and fail to obtain its own EXCLUSIVE lock
5250bea2a948Sdanielk1977       ** on the database file.
5251d0864087Sdan       **
5252d0864087Sdan       ** Unless the pager is in locking_mode=exclusive mode, the lock is
5253d0864087Sdan       ** downgraded to SHARED_LOCK before this function returns.
525490ba3bd0Sdanielk1977       */
52554e004aa6Sdan       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
5256a7fcb059Sdrh       if( rc!=SQLITE_OK ){
525752b472aeSdanielk1977         goto failed;
5258a7fcb059Sdrh       }
5259a7fcb059Sdrh 
5260d0864087Sdan       /* If it is not already open and the file exists on disk, open the
5261d0864087Sdan       ** journal for read/write access. Write access is required because
5262d0864087Sdan       ** in exclusive-access mode the file descriptor will be kept open
5263d0864087Sdan       ** and possibly used for a transaction later on. Also, write-access
5264d0864087Sdan       ** is usually required to finalize the journal in journal_mode=persist
5265d0864087Sdan       ** mode (and also for journal_mode=truncate on some systems).
5266d0864087Sdan       **
5267d0864087Sdan       ** If the journal does not exist, it usually means that some
5268d0864087Sdan       ** other connection managed to get in and roll it back before
5269d0864087Sdan       ** this connection obtained the exclusive lock above. Or, it
5270d0864087Sdan       ** may mean that the pager was in the error-state when this
5271d0864087Sdan       ** function was called and the journal file does not exist.
5272ed7c855cSdrh       */
5273bda4d200Sdrh       if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
5274431b0b42Sdan         sqlite3_vfs * const pVfs = pPager->pVfs;
5275431b0b42Sdan         int bExists;              /* True if journal file exists */
5276431b0b42Sdan         rc = sqlite3OsAccess(
5277431b0b42Sdan             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
5278431b0b42Sdan         if( rc==SQLITE_OK && bExists ){
5279b4b47411Sdanielk1977           int fout = 0;
5280ae72d982Sdanielk1977           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
52817152de8dSdanielk1977           assert( !pPager->tempFile );
5282ae72d982Sdanielk1977           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
5283bea2a948Sdanielk1977           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
5284281d8bd3Sdanielk1977           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
52859978c97eSdrh             rc = SQLITE_CANTOPEN_BKPT;
5286b4b47411Sdanielk1977             sqlite3OsClose(pPager->jfd);
5287979f38e5Sdanielk1977           }
5288861f7456Sdanielk1977         }
5289979f38e5Sdanielk1977       }
529091781bd7Sdrh 
5291ed7c855cSdrh       /* Playback and delete the journal.  Drop the database write
5292112f752bSdanielk1977       ** lock and reacquire the read lock. Purge the cache before
5293112f752bSdanielk1977       ** playing back the hot-journal so that we don't end up with
529491781bd7Sdrh       ** an inconsistent cache.  Sync the hot journal before playing
529591781bd7Sdrh       ** it back since the process that crashed and left the hot journal
529691781bd7Sdrh       ** probably did not sync it and we are required to always sync
529791781bd7Sdrh       ** the journal before playing it back.
5298ed7c855cSdrh       */
5299641a0bd2Sdanielk1977       if( isOpen(pPager->jfd) ){
53004e004aa6Sdan         assert( rc==SQLITE_OK );
5301eada58aaSdan         rc = pagerSyncHotJournal(pPager);
530291781bd7Sdrh         if( rc==SQLITE_OK ){
53036572c16aSdan           rc = pager_playback(pPager, !pPager->tempFile);
5304de1ae34eSdan           pPager->eState = PAGER_OPEN;
530591781bd7Sdrh         }
53064e004aa6Sdan       }else if( !pPager->exclusiveMode ){
53074e004aa6Sdan         pagerUnlockDb(pPager, SHARED_LOCK);
5308ed7c855cSdrh       }
53094e004aa6Sdan 
53104e004aa6Sdan       if( rc!=SQLITE_OK ){
5311de1ae34eSdan         /* This branch is taken if an error occurs while trying to open
5312de1ae34eSdan         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
5313de1ae34eSdan         ** pager_unlock() routine will be called before returning to unlock
5314de1ae34eSdan         ** the file. If the unlock attempt fails, then Pager.eLock must be
5315de1ae34eSdan         ** set to UNKNOWN_LOCK (see the comment above the #define for
5316de1ae34eSdan         ** UNKNOWN_LOCK above for an explanation).
5317de1ae34eSdan         **
5318de1ae34eSdan         ** In order to get pager_unlock() to do this, set Pager.eState to
5319de1ae34eSdan         ** PAGER_ERROR now. This is not actually counted as a transition
5320de1ae34eSdan         ** to ERROR state in the state diagram at the top of this file,
5321de1ae34eSdan         ** since we know that the same call to pager_unlock() will very
5322de1ae34eSdan         ** shortly transition the pager object to the OPEN state. Calling
5323de1ae34eSdan         ** assert_pager_state() would fail now, as it should not be possible
5324de1ae34eSdan         ** to be in ERROR state when there are zero outstanding page
5325de1ae34eSdan         ** references.
5326de1ae34eSdan         */
53274e004aa6Sdan         pager_error(pPager, rc);
53284e004aa6Sdan         goto failed;
5329641a0bd2Sdanielk1977       }
5330d0864087Sdan 
5331de1ae34eSdan       assert( pPager->eState==PAGER_OPEN );
5332d0864087Sdan       assert( (pPager->eLock==SHARED_LOCK)
5333d0864087Sdan            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
5334c5859718Sdanielk1977       );
5335ed7c855cSdrh     }
5336e277be05Sdanielk1977 
5337c98a4cc8Sdrh     if( !pPager->tempFile && pPager->hasHeldSharedLock ){
5338542d5586Sdrh       /* The shared-lock has just been acquired then check to
5339542d5586Sdrh       ** see if the database has been modified.  If the database has changed,
5340c98a4cc8Sdrh       ** flush the cache.  The hasHeldSharedLock flag prevents this from
5341542d5586Sdrh       ** occurring on the very first access to a file, in order to save a
5342542d5586Sdrh       ** single unnecessary sqlite3OsRead() call at the start-up.
534386a88114Sdrh       **
5344b84c14d0Sdrh       ** Database changes are detected by looking at 15 bytes beginning
534586a88114Sdrh       ** at offset 24 into the file.  The first 4 of these 16 bytes are
534686a88114Sdrh       ** a 32-bit counter that is incremented with each change.  The
534786a88114Sdrh       ** other bytes change randomly with each file change when
534886a88114Sdrh       ** a codec is in use.
534986a88114Sdrh       **
535086a88114Sdrh       ** There is a vanishingly small chance that a change will not be
53516fa51035Sdrh       ** detected.  The chance of an undetected change is so small that
535286a88114Sdrh       ** it can be neglected.
535324168728Sdanielk1977       */
535486a88114Sdrh       char dbFileVers[sizeof(pPager->dbFileVers)];
535524168728Sdanielk1977 
5356ae5e445bSdrh       IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
535762079060Sdanielk1977       rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
53585f5a2d1cSdrh       if( rc!=SQLITE_OK ){
53595f5a2d1cSdrh         if( rc!=SQLITE_IOERR_SHORT_READ ){
536052b472aeSdanielk1977           goto failed;
5361e180dd93Sdanielk1977         }
536286a88114Sdrh         memset(dbFileVers, 0, sizeof(dbFileVers));
5363e180dd93Sdanielk1977       }
5364e180dd93Sdanielk1977 
536586a88114Sdrh       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
5366e277be05Sdanielk1977         pager_reset(pPager);
536711dcd119Sdan 
536811dcd119Sdan         /* Unmap the database file. It is possible that external processes
536911dcd119Sdan         ** may have truncated the database file and then extended it back
537011dcd119Sdan         ** to its original size while this process was not holding a lock.
537111dcd119Sdan         ** In this case there may exist a Pager.pMap mapping that appears
537211dcd119Sdan         ** to be the right size but is not actually valid. Avoid this
537311dcd119Sdan         ** possibility by unmapping the db here. */
5374188d4884Sdrh         if( USEFETCH(pPager) ){
5375df737fe6Sdan           sqlite3OsUnfetch(pPager->fd, 0, 0);
5376f23da966Sdan         }
5377e277be05Sdanielk1977       }
5378e277be05Sdanielk1977     }
5379e04dc88bSdan 
53805cf53537Sdan     /* If there is a WAL file in the file-system, open this database in WAL
53815cf53537Sdan     ** mode. Otherwise, the following function call is a no-op.
53825cf53537Sdan     */
53835cf53537Sdan     rc = pagerOpenWalIfPresent(pPager);
53849091f775Sshaneh #ifndef SQLITE_OMIT_WAL
538522b328b2Sdan     assert( pPager->pWal==0 || rc==SQLITE_OK );
53869091f775Sshaneh #endif
5387c5859718Sdanielk1977   }
5388e277be05Sdanielk1977 
538922b328b2Sdan   if( pagerUseWal(pPager) ){
539022b328b2Sdan     assert( rc==SQLITE_OK );
5391763afe62Sdan     rc = pagerBeginReadTransaction(pPager);
5392763afe62Sdan   }
5393763afe62Sdan 
53946572c16aSdan   if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
5395763afe62Sdan     rc = pagerPagecount(pPager, &pPager->dbSize);
5396763afe62Sdan   }
5397763afe62Sdan 
539852b472aeSdanielk1977  failed:
539952b472aeSdanielk1977   if( rc!=SQLITE_OK ){
540022b328b2Sdan     assert( !MEMDB );
540152b472aeSdanielk1977     pager_unlock(pPager);
5402de1ae34eSdan     assert( pPager->eState==PAGER_OPEN );
5403763afe62Sdan   }else{
5404763afe62Sdan     pPager->eState = PAGER_READER;
5405c98a4cc8Sdrh     pPager->hasHeldSharedLock = 1;
540652b472aeSdanielk1977   }
5407e277be05Sdanielk1977   return rc;
5408d9b0257aSdrh }
5409e277be05Sdanielk1977 
5410e277be05Sdanielk1977 /*
5411bea2a948Sdanielk1977 ** If the reference count has reached zero, rollback any active
5412bea2a948Sdanielk1977 ** transaction and unlock the pager.
541359813953Sdrh **
541459813953Sdrh ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
541559813953Sdrh ** the rollback journal, the unlock is not performed and there is
541659813953Sdrh ** nothing to rollback, so this routine is a no-op.
54178c0a791aSdanielk1977 */
pagerUnlockIfUnused(Pager * pPager)54188c0a791aSdanielk1977 static void pagerUnlockIfUnused(Pager *pPager){
54193908fe90Sdrh   if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
54203908fe90Sdrh     assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
54218c0a791aSdanielk1977     pagerUnlockAndRollback(pPager);
54228c0a791aSdanielk1977   }
54238c0a791aSdanielk1977 }
54248c0a791aSdanielk1977 
54258c0a791aSdanielk1977 /*
5426d5df3ff2Sdrh ** The page getter methods each try to acquire a reference to a
5427d5df3ff2Sdrh ** page with page number pgno. If the requested reference is
5428bea2a948Sdanielk1977 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
5429e277be05Sdanielk1977 **
5430d5df3ff2Sdrh ** There are different implementations of the getter method depending
5431d5df3ff2Sdrh ** on the current state of the pager.
5432d5df3ff2Sdrh **
5433d5df3ff2Sdrh **     getPageNormal()         --  The normal getter
5434d5df3ff2Sdrh **     getPageError()          --  Used if the pager is in an error state
5435d5df3ff2Sdrh **     getPageMmap()           --  Used if memory-mapped I/O is enabled
5436d5df3ff2Sdrh **
5437bea2a948Sdanielk1977 ** If the requested page is already in the cache, it is returned.
5438bea2a948Sdanielk1977 ** Otherwise, a new page object is allocated and populated with data
5439bea2a948Sdanielk1977 ** read from the database file. In some cases, the pcache module may
5440bea2a948Sdanielk1977 ** choose not to allocate a new page object and may reuse an existing
5441bea2a948Sdanielk1977 ** object with no outstanding references.
5442bea2a948Sdanielk1977 **
5443bea2a948Sdanielk1977 ** The extra data appended to a page is always initialized to zeros the
5444bea2a948Sdanielk1977 ** first time a page is loaded into memory. If the page requested is
5445bea2a948Sdanielk1977 ** already in the cache when this function is called, then the extra
5446bea2a948Sdanielk1977 ** data is left as it was when the page object was last used.
5447bea2a948Sdanielk1977 **
5448d5df3ff2Sdrh ** If the database image is smaller than the requested page or if
5449d5df3ff2Sdrh ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
5450bea2a948Sdanielk1977 ** requested page is not already stored in the cache, then no
5451bea2a948Sdanielk1977 ** actual disk read occurs. In this case the memory image of the
5452bea2a948Sdanielk1977 ** page is initialized to all zeros.
5453bea2a948Sdanielk1977 **
5454d5df3ff2Sdrh ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
5455d5df3ff2Sdrh ** the contents of the page. This occurs in two scenarios:
5456bea2a948Sdanielk1977 **
5457bea2a948Sdanielk1977 **   a) When reading a free-list leaf page from the database, and
5458bea2a948Sdanielk1977 **
5459bea2a948Sdanielk1977 **   b) When a savepoint is being rolled back and we need to load
546091781bd7Sdrh **      a new page into the cache to be filled with the data read
5461bea2a948Sdanielk1977 **      from the savepoint journal.
5462bea2a948Sdanielk1977 **
5463d5df3ff2Sdrh ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
5464d5df3ff2Sdrh ** of being read from the database. Additionally, the bits corresponding
5465bea2a948Sdanielk1977 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
5466bea2a948Sdanielk1977 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
5467bea2a948Sdanielk1977 ** savepoints are set. This means if the page is made writable at any
5468bea2a948Sdanielk1977 ** point in the future, using a call to sqlite3PagerWrite(), its contents
5469bea2a948Sdanielk1977 ** will not be journaled. This saves IO.
5470e277be05Sdanielk1977 **
5471e277be05Sdanielk1977 ** The acquisition might fail for several reasons.  In all cases,
5472e277be05Sdanielk1977 ** an appropriate error code is returned and *ppPage is set to NULL.
5473e277be05Sdanielk1977 **
5474d33d5a89Sdrh ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
5475e277be05Sdanielk1977 ** to find a page in the in-memory cache first.  If the page is not already
5476d33d5a89Sdrh ** in memory, this routine goes to disk to read it in whereas Lookup()
5477e277be05Sdanielk1977 ** just returns 0.  This routine acquires a read-lock the first time it
5478e277be05Sdanielk1977 ** has to go to disk, and could also playback an old journal if necessary.
5479d33d5a89Sdrh ** Since Lookup() never goes to disk, it never has to deal with locks
5480e277be05Sdanielk1977 ** or journal files.
5481e277be05Sdanielk1977 */
getPageNormal(Pager * pPager,Pgno pgno,DbPage ** ppPage,int flags)548212e6f682Sdrh static int getPageNormal(
5483538f570cSdrh   Pager *pPager,      /* The pager open on the database file */
5484538f570cSdrh   Pgno pgno,          /* Page number to fetch */
5485538f570cSdrh   DbPage **ppPage,    /* Write a pointer to the page here */
5486b00fc3b1Sdrh   int flags           /* PAGER_GET_XXX flags */
5487538f570cSdrh ){
548811dcd119Sdan   int rc = SQLITE_OK;
5489d5df3ff2Sdrh   PgHdr *pPg;
5490d5df3ff2Sdrh   u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
549112e6f682Sdrh   sqlite3_pcache_page *pBase;
549211dcd119Sdan 
549312e6f682Sdrh   assert( pPager->errCode==SQLITE_OK );
5494d0864087Sdan   assert( pPager->eState>=PAGER_READER );
5495bea2a948Sdanielk1977   assert( assert_pager_state(pPager) );
5496c98a4cc8Sdrh   assert( pPager->hasHeldSharedLock==1 );
5497e277be05Sdanielk1977 
5498b2d71371Sdrh   if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
5499bc59ac0eSdrh   pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
5500bc59ac0eSdrh   if( pBase==0 ){
5501d5df3ff2Sdrh     pPg = 0;
5502bc59ac0eSdrh     rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
5503bc59ac0eSdrh     if( rc!=SQLITE_OK ) goto pager_acquire_err;
5504d8c0ba3bSdrh     if( pBase==0 ){
5505fad3039cSmistachkin       rc = SQLITE_NOMEM_BKPT;
5506d8c0ba3bSdrh       goto pager_acquire_err;
5507d8c0ba3bSdrh     }
5508bc59ac0eSdrh   }
5509bc59ac0eSdrh   pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
5510b84c14d0Sdrh   assert( pPg==(*ppPage) );
5511b84c14d0Sdrh   assert( pPg->pgno==pgno );
5512b84c14d0Sdrh   assert( pPg->pPager==pPager || pPg->pPager==0 );
551389bc4bc6Sdanielk1977 
55148a123d60Sdrh   noContent = (flags & PAGER_GET_NOCONTENT)!=0;
55158a123d60Sdrh   if( pPg->pPager && !noContent ){
551689bc4bc6Sdanielk1977     /* In this case the pcache already contains an initialized copy of
551789bc4bc6Sdanielk1977     ** the page. Return without further ado.  */
5518584bfcaeSdrh     assert( pgno!=PAGER_SJ_PGNO(pPager) );
55199ad3ee40Sdrh     pPager->aStat[PAGER_STAT_HIT]++;
552089bc4bc6Sdanielk1977     return SQLITE_OK;
552189bc4bc6Sdanielk1977 
552289bc4bc6Sdanielk1977   }else{
55238c0a791aSdanielk1977     /* The pager cache has created a new page. Its content needs to
5524cbed604fSdrh     ** be initialized. But first some error checks:
5525cbed604fSdrh     **
5526e3994f29Sdrh     ** (*) obsolete.  Was: maximum page number is 2^31
5527e3994f29Sdrh     ** (2) Never try to fetch the locking page
5528cbed604fSdrh     */
5529b2d71371Sdrh     if( pgno==PAGER_SJ_PGNO(pPager) ){
553089bc4bc6Sdanielk1977       rc = SQLITE_CORRUPT_BKPT;
553189bc4bc6Sdanielk1977       goto pager_acquire_err;
553289bc4bc6Sdanielk1977     }
553389bc4bc6Sdanielk1977 
5534cbed604fSdrh     pPg->pPager = pPager;
5535cbed604fSdrh 
5536835f22deSdrh     assert( !isOpen(pPager->fd) || !MEMDB );
5537835f22deSdrh     if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
5538f8e632b6Sdrh       if( pgno>pPager->mxPgno ){
553989bc4bc6Sdanielk1977         rc = SQLITE_FULL;
554089bc4bc6Sdanielk1977         goto pager_acquire_err;
5541f8e632b6Sdrh       }
5542a1fa00d9Sdanielk1977       if( noContent ){
5543bea2a948Sdanielk1977         /* Failure to set the bits in the InJournal bit-vectors is benign.
5544bea2a948Sdanielk1977         ** It merely means that we might do some extra work to journal a
5545bea2a948Sdanielk1977         ** page that does not need to be journaled.  Nevertheless, be sure
5546bea2a948Sdanielk1977         ** to test the case where a malloc error occurs while trying to set
5547bea2a948Sdanielk1977         ** a bit in a bit vector.
5548bea2a948Sdanielk1977         */
5549bea2a948Sdanielk1977         sqlite3BeginBenignMalloc();
55508a938f98Sdrh         if( pgno<=pPager->dbOrigSize ){
5551bea2a948Sdanielk1977           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
5552bea2a948Sdanielk1977           testcase( rc==SQLITE_NOMEM );
5553bea2a948Sdanielk1977         }
5554bea2a948Sdanielk1977         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
5555bea2a948Sdanielk1977         testcase( rc==SQLITE_NOMEM );
5556bea2a948Sdanielk1977         sqlite3EndBenignMalloc();
55578c0a791aSdanielk1977       }
555839187959Sdrh       memset(pPg->pData, 0, pPager->pageSize);
5559538f570cSdrh       IOTRACE(("ZERO %p %d\n", pPager, pgno));
5560306dc213Sdrh     }else{
5561bea2a948Sdanielk1977       assert( pPg->pPager==pPager );
55629ad3ee40Sdrh       pPager->aStat[PAGER_STAT_MISS]++;
556356520ab8Sdrh       rc = readDbPage(pPg);
5564546820e3Sdanielk1977       if( rc!=SQLITE_OK ){
556589bc4bc6Sdanielk1977         goto pager_acquire_err;
556681a20f21Sdrh       }
5567306dc213Sdrh     }
55685f848c3aSdan     pager_set_pagehash(pPg);
5569ed7c855cSdrh   }
5570ed7c855cSdrh   return SQLITE_OK;
557189bc4bc6Sdanielk1977 
557289bc4bc6Sdanielk1977 pager_acquire_err:
557389bc4bc6Sdanielk1977   assert( rc!=SQLITE_OK );
5574e878a2f4Sdanielk1977   if( pPg ){
5575e878a2f4Sdanielk1977     sqlite3PcacheDrop(pPg);
5576e878a2f4Sdanielk1977   }
557789bc4bc6Sdanielk1977   pagerUnlockIfUnused(pPager);
557889bc4bc6Sdanielk1977   *ppPage = 0;
557989bc4bc6Sdanielk1977   return rc;
5580ed7c855cSdrh }
55818c0a791aSdanielk1977 
5582d5df3ff2Sdrh #if SQLITE_MAX_MMAP_SIZE>0
558312e6f682Sdrh /* The page getter for when memory-mapped I/O is enabled */
getPageMMap(Pager * pPager,Pgno pgno,DbPage ** ppPage,int flags)558412e6f682Sdrh static int getPageMMap(
558512e6f682Sdrh   Pager *pPager,      /* The pager open on the database file */
558612e6f682Sdrh   Pgno pgno,          /* Page number to fetch */
558712e6f682Sdrh   DbPage **ppPage,    /* Write a pointer to the page here */
558812e6f682Sdrh   int flags           /* PAGER_GET_XXX flags */
558912e6f682Sdrh ){
559012e6f682Sdrh   int rc = SQLITE_OK;
559112e6f682Sdrh   PgHdr *pPg = 0;
559212e6f682Sdrh   u32 iFrame = 0;                 /* Frame to read from WAL file */
559312e6f682Sdrh 
559412e6f682Sdrh   /* It is acceptable to use a read-only (mmap) page for any page except
559512e6f682Sdrh   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
559612e6f682Sdrh   ** flag was specified by the caller. And so long as the db is not a
559712e6f682Sdrh   ** temporary or in-memory database.  */
559812e6f682Sdrh   const int bMmapOk = (pgno>1
559912e6f682Sdrh    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
560012e6f682Sdrh   );
560112e6f682Sdrh 
5602380c08eaSdrh   assert( USEFETCH(pPager) );
5603380c08eaSdrh 
560412e6f682Sdrh   /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
560512e6f682Sdrh   ** allows the compiler optimizer to reuse the results of the "pgno>1"
560612e6f682Sdrh   ** test in the previous statement, and avoid testing pgno==0 in the
560712e6f682Sdrh   ** common case where pgno is large. */
560812e6f682Sdrh   if( pgno<=1 && pgno==0 ){
560912e6f682Sdrh     return SQLITE_CORRUPT_BKPT;
561012e6f682Sdrh   }
561112e6f682Sdrh   assert( pPager->eState>=PAGER_READER );
561212e6f682Sdrh   assert( assert_pager_state(pPager) );
561312e6f682Sdrh   assert( pPager->hasHeldSharedLock==1 );
561412e6f682Sdrh   assert( pPager->errCode==SQLITE_OK );
561512e6f682Sdrh 
561612e6f682Sdrh   if( bMmapOk && pagerUseWal(pPager) ){
561712e6f682Sdrh     rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
561812e6f682Sdrh     if( rc!=SQLITE_OK ){
561912e6f682Sdrh       *ppPage = 0;
562012e6f682Sdrh       return rc;
562112e6f682Sdrh     }
562212e6f682Sdrh   }
562312e6f682Sdrh   if( bMmapOk && iFrame==0 ){
562412e6f682Sdrh     void *pData = 0;
562512e6f682Sdrh     rc = sqlite3OsFetch(pPager->fd,
562612e6f682Sdrh         (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
562712e6f682Sdrh     );
562812e6f682Sdrh     if( rc==SQLITE_OK && pData ){
562912e6f682Sdrh       if( pPager->eState>PAGER_READER || pPager->tempFile ){
563012e6f682Sdrh         pPg = sqlite3PagerLookup(pPager, pgno);
563112e6f682Sdrh       }
563212e6f682Sdrh       if( pPg==0 ){
563312e6f682Sdrh         rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
563412e6f682Sdrh       }else{
563512e6f682Sdrh         sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
563612e6f682Sdrh       }
563712e6f682Sdrh       if( pPg ){
563812e6f682Sdrh         assert( rc==SQLITE_OK );
563912e6f682Sdrh         *ppPage = pPg;
564012e6f682Sdrh         return SQLITE_OK;
564112e6f682Sdrh       }
564212e6f682Sdrh     }
564312e6f682Sdrh     if( rc!=SQLITE_OK ){
564412e6f682Sdrh       *ppPage = 0;
564512e6f682Sdrh       return rc;
564612e6f682Sdrh     }
564712e6f682Sdrh   }
564812e6f682Sdrh   return getPageNormal(pPager, pgno, ppPage, flags);
564912e6f682Sdrh }
5650d5df3ff2Sdrh #endif /* SQLITE_MAX_MMAP_SIZE>0 */
565112e6f682Sdrh 
565212e6f682Sdrh /* The page getter method for when the pager is an error state */
getPageError(Pager * pPager,Pgno pgno,DbPage ** ppPage,int flags)565312e6f682Sdrh static int getPageError(
565412e6f682Sdrh   Pager *pPager,      /* The pager open on the database file */
565512e6f682Sdrh   Pgno pgno,          /* Page number to fetch */
565612e6f682Sdrh   DbPage **ppPage,    /* Write a pointer to the page here */
565712e6f682Sdrh   int flags           /* PAGER_GET_XXX flags */
565812e6f682Sdrh ){
5659380c08eaSdrh   UNUSED_PARAMETER(pgno);
5660380c08eaSdrh   UNUSED_PARAMETER(flags);
566112e6f682Sdrh   assert( pPager->errCode!=SQLITE_OK );
566212e6f682Sdrh   *ppPage = 0;
566312e6f682Sdrh   return pPager->errCode;
566412e6f682Sdrh }
566512e6f682Sdrh 
566612e6f682Sdrh 
566712e6f682Sdrh /* Dispatch all page fetch requests to the appropriate getter method.
566812e6f682Sdrh */
sqlite3PagerGet(Pager * pPager,Pgno pgno,DbPage ** ppPage,int flags)566912e6f682Sdrh int sqlite3PagerGet(
567012e6f682Sdrh   Pager *pPager,      /* The pager open on the database file */
567112e6f682Sdrh   Pgno pgno,          /* Page number to fetch */
567212e6f682Sdrh   DbPage **ppPage,    /* Write a pointer to the page here */
567312e6f682Sdrh   int flags           /* PAGER_GET_XXX flags */
567412e6f682Sdrh ){
56755622c7f9Sdrh   /* printf("PAGE %u\n", pgno); fflush(stdout); */
567612e6f682Sdrh   return pPager->xGet(pPager, pgno, ppPage, flags);
567712e6f682Sdrh }
567812e6f682Sdrh 
5679ed7c855cSdrh /*
56807e3b0a07Sdrh ** Acquire a page if it is already in the in-memory cache.  Do
56817e3b0a07Sdrh ** not read the page from disk.  Return a pointer to the page,
5682a81a2207Sdan ** or 0 if the page is not in cache.
56837e3b0a07Sdrh **
56843b8a05f6Sdanielk1977 ** See also sqlite3PagerGet().  The difference between this routine
56853b8a05f6Sdanielk1977 ** and sqlite3PagerGet() is that _get() will go to the disk and read
56867e3b0a07Sdrh ** in the page if the page is not already in cache.  This routine
56875e00f6c7Sdrh ** returns NULL if the page is not in cache or if a disk I/O error
56885e00f6c7Sdrh ** has ever happened.
56897e3b0a07Sdrh */
sqlite3PagerLookup(Pager * pPager,Pgno pgno)56903b8a05f6Sdanielk1977 DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
5691bc59ac0eSdrh   sqlite3_pcache_page *pPage;
5692836faa48Sdrh   assert( pPager!=0 );
5693836faa48Sdrh   assert( pgno!=0 );
5694ad7516c4Sdrh   assert( pPager->pPCache!=0 );
5695bc59ac0eSdrh   pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
5696c98a4cc8Sdrh   assert( pPage==0 || pPager->hasHeldSharedLock );
5697d8c0ba3bSdrh   if( pPage==0 ) return 0;
5698bc59ac0eSdrh   return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
56997e3b0a07Sdrh }
57007e3b0a07Sdrh 
57017e3b0a07Sdrh /*
5702bea2a948Sdanielk1977 ** Release a page reference.
5703ed7c855cSdrh **
57043908fe90Sdrh ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
57053908fe90Sdrh ** used if we know that the page being released is not the last page.
57063908fe90Sdrh ** The btree layer always holds page1 open until the end, so these first
57073908fe90Sdrh ** to routines can be used to release any page other than BtShared.pPage1.
57083908fe90Sdrh **
57093908fe90Sdrh ** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
57103908fe90Sdrh ** checks the total number of outstanding pages and if the number of
57113908fe90Sdrh ** pages reaches zero it drops the database lock.
5712ed7c855cSdrh */
sqlite3PagerUnrefNotNull(DbPage * pPg)5713da8a330aSdrh void sqlite3PagerUnrefNotNull(DbPage *pPg){
57143908fe90Sdrh   TESTONLY( Pager *pPager = pPg->pPager; )
5715da8a330aSdrh   assert( pPg!=0 );
5716b2d3de3bSdan   if( pPg->flags & PGHDR_MMAP ){
57173908fe90Sdrh     assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
5718b2d3de3bSdan     pagerReleaseMapPage(pPg);
5719b2d3de3bSdan   }else{
57208c0a791aSdanielk1977     sqlite3PcacheRelease(pPg);
5721b2d3de3bSdan   }
57223908fe90Sdrh   /* Do not use this routine to release the last reference to page1 */
57233908fe90Sdrh   assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
57248c0a791aSdanielk1977 }
sqlite3PagerUnref(DbPage * pPg)5725da8a330aSdrh void sqlite3PagerUnref(DbPage *pPg){
5726da8a330aSdrh   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
5727d9b0257aSdrh }
sqlite3PagerUnrefPageOne(DbPage * pPg)57283908fe90Sdrh void sqlite3PagerUnrefPageOne(DbPage *pPg){
57293908fe90Sdrh   Pager *pPager;
57303908fe90Sdrh   assert( pPg!=0 );
57313908fe90Sdrh   assert( pPg->pgno==1 );
57323908fe90Sdrh   assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
57333908fe90Sdrh   pPager = pPg->pPager;
57343908fe90Sdrh   sqlite3PcacheRelease(pPg);
57353908fe90Sdrh   pagerUnlockIfUnused(pPager);
57363908fe90Sdrh }
5737ed7c855cSdrh 
57389153d850Sdanielk1977 /*
5739bea2a948Sdanielk1977 ** This function is called at the start of every write transaction.
5740bea2a948Sdanielk1977 ** There must already be a RESERVED or EXCLUSIVE lock on the database
5741bea2a948Sdanielk1977 ** file when this routine is called.
5742da47d774Sdrh **
5743bea2a948Sdanielk1977 ** Open the journal file for pager pPager and write a journal header
5744bea2a948Sdanielk1977 ** to the start of it. If there are active savepoints, open the sub-journal
5745bea2a948Sdanielk1977 ** as well. This function is only used when the journal file is being
5746bea2a948Sdanielk1977 ** opened to write a rollback log for a transaction. It is not used
5747bea2a948Sdanielk1977 ** when opening a hot journal file to roll it back.
5748bea2a948Sdanielk1977 **
5749bea2a948Sdanielk1977 ** If the journal file is already open (as it may be in exclusive mode),
5750bea2a948Sdanielk1977 ** then this function just writes a journal header to the start of the
5751bea2a948Sdanielk1977 ** already open file.
5752bea2a948Sdanielk1977 **
5753bea2a948Sdanielk1977 ** Whether or not the journal file is opened by this function, the
5754bea2a948Sdanielk1977 ** Pager.pInJournal bitvec structure is allocated.
5755bea2a948Sdanielk1977 **
5756bea2a948Sdanielk1977 ** Return SQLITE_OK if everything is successful. Otherwise, return
5757bea2a948Sdanielk1977 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
5758bea2a948Sdanielk1977 ** an IO error code if opening or writing the journal file fails.
5759da47d774Sdrh */
pager_open_journal(Pager * pPager)5760da47d774Sdrh static int pager_open_journal(Pager *pPager){
5761bea2a948Sdanielk1977   int rc = SQLITE_OK;                        /* Return code */
5762bea2a948Sdanielk1977   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
5763b4b47411Sdanielk1977 
5764de1ae34eSdan   assert( pPager->eState==PAGER_WRITER_LOCKED );
5765d0864087Sdan   assert( assert_pager_state(pPager) );
5766f5e7bb51Sdrh   assert( pPager->pInJournal==0 );
5767bea2a948Sdanielk1977 
5768ad7516c4Sdrh   /* If already in the error state, this function is a no-op.  But on
5769ad7516c4Sdrh   ** the other hand, this routine is never called if we are already in
5770ad7516c4Sdrh   ** an error state. */
5771ad7516c4Sdrh   if( NEVER(pPager->errCode) ) return pPager->errCode;
5772b4b47411Sdanielk1977 
5773d0864087Sdan   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
5774937ac9daSdan     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
5775bea2a948Sdanielk1977     if( pPager->pInJournal==0 ){
5776fad3039cSmistachkin       return SQLITE_NOMEM_BKPT;
5777b4b47411Sdanielk1977     }
5778bea2a948Sdanielk1977 
5779bea2a948Sdanielk1977     /* Open the journal file if it is not already open. */
5780bea2a948Sdanielk1977     if( !isOpen(pPager->jfd) ){
5781b3175389Sdanielk1977       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
5782b3175389Sdanielk1977         sqlite3MemJournalOpen(pPager->jfd);
5783b3175389Sdanielk1977       }else{
57849131ab93Sdan         int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
57859131ab93Sdan         int nSpill;
57869131ab93Sdan 
57879131ab93Sdan         if( pPager->tempFile ){
57889131ab93Sdan           flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
57892756f806Sdan           flags |= SQLITE_OPEN_EXCLUSIVE;
57909131ab93Sdan           nSpill = sqlite3Config.nStmtSpill;
57919131ab93Sdan         }else{
57929131ab93Sdan           flags |= SQLITE_OPEN_MAIN_JOURNAL;
57939131ab93Sdan           nSpill = jrnlBufferSize(pPager);
57949131ab93Sdan         }
57953fee8a63Sdrh 
57963fee8a63Sdrh         /* Verify that the database still has the same name as it did when
57973fee8a63Sdrh         ** it was originally opened. */
57983fee8a63Sdrh         rc = databaseIsUnmoved(pPager);
57993fee8a63Sdrh         if( rc==SQLITE_OK ){
5800c7b6017cSdanielk1977           rc = sqlite3JournalOpen (
58019131ab93Sdan               pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
5802c7b6017cSdanielk1977           );
5803b3175389Sdanielk1977         }
58043fee8a63Sdrh       }
5805bea2a948Sdanielk1977       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
5806600e46a0Sdrh     }
5807bea2a948Sdanielk1977 
5808bea2a948Sdanielk1977 
5809bea2a948Sdanielk1977     /* Write the first journal header to the journal file and open
5810bea2a948Sdanielk1977     ** the sub-journal if necessary.
5811bea2a948Sdanielk1977     */
5812bea2a948Sdanielk1977     if( rc==SQLITE_OK ){
5813bea2a948Sdanielk1977       /* TODO: Check if all of these are really required. */
5814968af52aSdrh       pPager->nRec = 0;
5815bea2a948Sdanielk1977       pPager->journalOff = 0;
5816067b92baSdrh       pPager->setSuper = 0;
5817bea2a948Sdanielk1977       pPager->journalHdr = 0;
58187657240aSdanielk1977       rc = writeJournalHdr(pPager);
5819bea2a948Sdanielk1977     }
5820d0864087Sdan   }
58219c105bb9Sdrh 
5822bea2a948Sdanielk1977   if( rc!=SQLITE_OK ){
5823f5e7bb51Sdrh     sqlite3BitvecDestroy(pPager->pInJournal);
5824f5e7bb51Sdrh     pPager->pInJournal = 0;
5825*ad617b4dSdan     pPager->journalOff = 0;
5826d0864087Sdan   }else{
5827de1ae34eSdan     assert( pPager->eState==PAGER_WRITER_LOCKED );
5828d0864087Sdan     pPager->eState = PAGER_WRITER_CACHEMOD;
5829bea2a948Sdanielk1977   }
5830d0864087Sdan 
58319c105bb9Sdrh   return rc;
5832da47d774Sdrh }
5833da47d774Sdrh 
5834da47d774Sdrh /*
5835bea2a948Sdanielk1977 ** Begin a write-transaction on the specified pager object. If a
5836bea2a948Sdanielk1977 ** write-transaction has already been opened, this function is a no-op.
58374b845d7eSdrh **
5838bea2a948Sdanielk1977 ** If the exFlag argument is false, then acquire at least a RESERVED
5839bea2a948Sdanielk1977 ** lock on the database file. If exFlag is true, then acquire at least
5840bea2a948Sdanielk1977 ** an EXCLUSIVE lock. If such a lock is already held, no locking
5841bea2a948Sdanielk1977 ** functions need be called.
58424b845d7eSdrh **
5843d829335eSdanielk1977 ** If the subjInMemory argument is non-zero, then any sub-journal opened
5844d829335eSdanielk1977 ** within this transaction will be opened as an in-memory file. This
5845d829335eSdanielk1977 ** has no effect if the sub-journal is already opened (as it may be when
5846d829335eSdanielk1977 ** running in exclusive mode) or if the transaction does not require a
5847d829335eSdanielk1977 ** sub-journal. If the subjInMemory argument is zero, then any required
5848d829335eSdanielk1977 ** sub-journal is implemented in-memory if pPager is an in-memory database,
5849d829335eSdanielk1977 ** or using a temporary file otherwise.
58504b845d7eSdrh */
sqlite3PagerBegin(Pager * pPager,int exFlag,int subjInMemory)5851d829335eSdanielk1977 int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
58524b845d7eSdrh   int rc = SQLITE_OK;
5853719e3a7aSdrh 
585489bd82aeSdrh   if( pPager->errCode ) return pPager->errCode;
5855719e3a7aSdrh   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
585660a4b538Sshane   pPager->subjInMemory = (u8)subjInMemory;
58575543759bSdan 
585855938b5fSdrh   if( pPager->eState==PAGER_READER ){
5859f5e7bb51Sdrh     assert( pPager->pInJournal==0 );
5860bea2a948Sdanielk1977 
58617ed91f23Sdrh     if( pagerUseWal(pPager) ){
58625543759bSdan       /* If the pager is configured to use locking_mode=exclusive, and an
58635543759bSdan       ** exclusive lock on the database is not already held, obtain it now.
58645543759bSdan       */
586561e4acecSdrh       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
58664e004aa6Sdan         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
58675543759bSdan         if( rc!=SQLITE_OK ){
58685543759bSdan           return rc;
58695543759bSdan         }
5870b4acd6a8Sdrh         (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
58715543759bSdan       }
58725543759bSdan 
587364d039e5Sdan       /* Grab the write lock on the log file. If successful, upgrade to
58745543759bSdan       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
587564d039e5Sdan       ** The busy-handler is not invoked if another connection already
587664d039e5Sdan       ** holds the write-lock. If possible, the upper layer will call it.
587764d039e5Sdan       */
587873b64e4dSdrh       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
587964d039e5Sdan     }else{
5880bea2a948Sdanielk1977       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
5881bea2a948Sdanielk1977       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
5882bea2a948Sdanielk1977       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
5883bea2a948Sdanielk1977       ** lock, but not when obtaining the RESERVED lock.
5884bea2a948Sdanielk1977       */
58854e004aa6Sdan       rc = pagerLockDb(pPager, RESERVED_LOCK);
5886d0864087Sdan       if( rc==SQLITE_OK && exFlag ){
5887684917c2Sdrh         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
5888684917c2Sdrh       }
5889684917c2Sdrh     }
58907c24610eSdan 
5891d0864087Sdan     if( rc==SQLITE_OK ){
5892de1ae34eSdan       /* Change to WRITER_LOCKED state.
5893d0864087Sdan       **
5894de1ae34eSdan       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
5895d0864087Sdan       ** when it has an open transaction, but never to DBMOD or FINISHED.
5896d0864087Sdan       ** This is because in those states the code to roll back savepoint
5897d0864087Sdan       ** transactions may copy data from the sub-journal into the database
5898d0864087Sdan       ** file as well as into the page cache. Which would be incorrect in
5899d0864087Sdan       ** WAL mode.
5900bea2a948Sdanielk1977       */
5901de1ae34eSdan       pPager->eState = PAGER_WRITER_LOCKED;
5902c864912aSdan       pPager->dbHintSize = pPager->dbSize;
5903c864912aSdan       pPager->dbFileSize = pPager->dbSize;
5904c864912aSdan       pPager->dbOrigSize = pPager->dbSize;
5905d0864087Sdan       pPager->journalOff = 0;
590675a40127Sdanielk1977     }
5907d0864087Sdan 
5908d0864087Sdan     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
5909de1ae34eSdan     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
5910d0864087Sdan     assert( assert_pager_state(pPager) );
59113ad5fd25Sdan   }
59123ad5fd25Sdan 
59133ad5fd25Sdan   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
59144b845d7eSdrh   return rc;
59154b845d7eSdrh }
59164b845d7eSdrh 
59174b845d7eSdrh /*
591882ef8775Sdrh ** Write page pPg onto the end of the rollback journal.
5919ed7c855cSdrh */
pagerAddPageToRollbackJournal(PgHdr * pPg)592082ef8775Sdrh static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
592169688d5fSdrh   Pager *pPager = pPg->pPager;
592282ef8775Sdrh   int rc;
5923bf4bca54Sdrh   u32 cksum;
5924bf4bca54Sdrh   char *pData2;
592573d66fdbSdan   i64 iOff = pPager->journalOff;
5926dd97a49cSdanielk1977 
5927267cb326Sdrh   /* We should never write to the journal file the page that
5928267cb326Sdrh   ** contains the database locks.  The following assert verifies
5929267cb326Sdrh   ** that we do not. */
5930584bfcaeSdrh   assert( pPg->pgno!=PAGER_SJ_PGNO(pPager) );
593191781bd7Sdrh 
593291781bd7Sdrh   assert( pPager->journalHdr<=pPager->journalOff );
5933b48c0d59Sdrh   pData2 = pPg->pData;
59343752785fSdrh   cksum = pager_cksum(pPager, (u8*)pData2);
593507cb560bSdanielk1977 
593673d66fdbSdan   /* Even if an IO or diskfull error occurs while journalling the
5937f3107512Sdanielk1977   ** page in the block above, set the need-sync flag for the page.
5938f3107512Sdanielk1977   ** Otherwise, when the transaction is rolled back, the logic in
5939f3107512Sdanielk1977   ** playback_one_page() will think that the page needs to be restored
5940f3107512Sdanielk1977   ** in the database file. And if an IO error occurs while doing so,
5941f3107512Sdanielk1977   ** then corruption may follow.
5942f3107512Sdanielk1977   */
5943f3107512Sdanielk1977   pPg->flags |= PGHDR_NEED_SYNC;
5944f3107512Sdanielk1977 
594573d66fdbSdan   rc = write32bits(pPager->jfd, iOff, pPg->pgno);
594673d66fdbSdan   if( rc!=SQLITE_OK ) return rc;
594773d66fdbSdan   rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
594873d66fdbSdan   if( rc!=SQLITE_OK ) return rc;
594973d66fdbSdan   rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
595073d66fdbSdan   if( rc!=SQLITE_OK ) return rc;
595107cb560bSdanielk1977 
595273d66fdbSdan   IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
595373d66fdbSdan            pPager->journalOff, pPager->pageSize));
595473d66fdbSdan   PAGER_INCR(sqlite3_pager_writej_count);
595573d66fdbSdan   PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
595673d66fdbSdan        PAGERID(pPager), pPg->pgno,
595773d66fdbSdan        ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
595873d66fdbSdan 
595973d66fdbSdan   pPager->journalOff += 8 + pPager->pageSize;
596099ee3600Sdrh   pPager->nRec++;
5961f5e7bb51Sdrh   assert( pPager->pInJournal!=0 );
59627539b6b8Sdrh   rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
59637539b6b8Sdrh   testcase( rc==SQLITE_NOMEM );
59647539b6b8Sdrh   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
59657539b6b8Sdrh   rc |= addToSavepointBitvecs(pPager, pPg->pgno);
596682ef8775Sdrh   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
596782ef8775Sdrh   return rc;
596882ef8775Sdrh }
596982ef8775Sdrh 
597082ef8775Sdrh /*
597182ef8775Sdrh ** Mark a single data page as writeable. The page is written into the
597282ef8775Sdrh ** main journal or sub-journal as required. If the page is written into
597382ef8775Sdrh ** one of the journals, the corresponding bit is set in the
597482ef8775Sdrh ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
597582ef8775Sdrh ** of any open savepoints as appropriate.
597682ef8775Sdrh */
pager_write(PgHdr * pPg)597782ef8775Sdrh static int pager_write(PgHdr *pPg){
597882ef8775Sdrh   Pager *pPager = pPg->pPager;
597982ef8775Sdrh   int rc = SQLITE_OK;
598082ef8775Sdrh 
598182ef8775Sdrh   /* This routine is not called unless a write-transaction has already
598282ef8775Sdrh   ** been started. The journal file may or may not be open at this point.
598382ef8775Sdrh   ** It is never called in the ERROR state.
598482ef8775Sdrh   */
598582ef8775Sdrh   assert( pPager->eState==PAGER_WRITER_LOCKED
598682ef8775Sdrh        || pPager->eState==PAGER_WRITER_CACHEMOD
598782ef8775Sdrh        || pPager->eState==PAGER_WRITER_DBMOD
598882ef8775Sdrh   );
598982ef8775Sdrh   assert( assert_pager_state(pPager) );
599082ef8775Sdrh   assert( pPager->errCode==0 );
599182ef8775Sdrh   assert( pPager->readOnly==0 );
599282ef8775Sdrh   CHECK_PAGE(pPg);
599382ef8775Sdrh 
599482ef8775Sdrh   /* The journal file needs to be opened. Higher level routines have already
599582ef8775Sdrh   ** obtained the necessary locks to begin the write-transaction, but the
599682ef8775Sdrh   ** rollback journal might not yet be open. Open it now if this is the case.
599782ef8775Sdrh   **
599882ef8775Sdrh   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
599982ef8775Sdrh   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
600082ef8775Sdrh   ** an error might occur and the pager would end up in WRITER_LOCKED state
600182ef8775Sdrh   ** with pages marked as dirty in the cache.
600282ef8775Sdrh   */
600382ef8775Sdrh   if( pPager->eState==PAGER_WRITER_LOCKED ){
600482ef8775Sdrh     rc = pager_open_journal(pPager);
600582ef8775Sdrh     if( rc!=SQLITE_OK ) return rc;
600682ef8775Sdrh   }
600782ef8775Sdrh   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
600882ef8775Sdrh   assert( assert_pager_state(pPager) );
600982ef8775Sdrh 
601082ef8775Sdrh   /* Mark the page that is about to be modified as dirty. */
601182ef8775Sdrh   sqlite3PcacheMakeDirty(pPg);
601282ef8775Sdrh 
601382ef8775Sdrh   /* If a rollback journal is in use, them make sure the page that is about
601482ef8775Sdrh   ** to change is in the rollback journal, or if the page is a new page off
601582ef8775Sdrh   ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
601682ef8775Sdrh   */
601782ef8775Sdrh   assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
6018e399ac2eSdrh   if( pPager->pInJournal!=0
6019e399ac2eSdrh    && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
602082ef8775Sdrh   ){
602182ef8775Sdrh     assert( pagerUseWal(pPager)==0 );
602282ef8775Sdrh     if( pPg->pgno<=pPager->dbOrigSize ){
602382ef8775Sdrh       rc = pagerAddPageToRollbackJournal(pPg);
60247539b6b8Sdrh       if( rc!=SQLITE_OK ){
60257539b6b8Sdrh         return rc;
60267539b6b8Sdrh       }
6027db48ee02Sdrh     }else{
6028937ac9daSdan       if( pPager->eState!=PAGER_WRITER_DBMOD ){
60298c0a791aSdanielk1977         pPg->flags |= PGHDR_NEED_SYNC;
6030db48ee02Sdrh       }
603130d53701Sdrh       PAGERTRACE(("APPEND %d page %d needSync=%d\n",
60328c0a791aSdanielk1977               PAGERID(pPager), pPg->pgno,
603330d53701Sdrh              ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
60348c0a791aSdanielk1977     }
6035d9b0257aSdrh   }
60366446c4dcSdrh 
60371aacbdb3Sdrh   /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
60381aacbdb3Sdrh   ** and before writing the page into the rollback journal.  Wait until now,
60391aacbdb3Sdrh   ** after the page has been successfully journalled, before setting the
60401aacbdb3Sdrh   ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
60411aacbdb3Sdrh   */
60421aacbdb3Sdrh   pPg->flags |= PGHDR_WRITEABLE;
60431aacbdb3Sdrh 
6044ac69b05eSdrh   /* If the statement journal is open and the page is not in it,
604582ef8775Sdrh   ** then write the page into the statement journal.
60466446c4dcSdrh   */
604760e32edbSdrh   if( pPager->nSavepoint>0 ){
604860e32edbSdrh     rc = subjournalPageIfRequired(pPg);
6049ac69b05eSdrh   }
6050fa86c412Sdrh 
605182ef8775Sdrh   /* Update the database size and return. */
6052d92db531Sdanielk1977   if( pPager->dbSize<pPg->pgno ){
6053306dc213Sdrh     pPager->dbSize = pPg->pgno;
6054306dc213Sdrh   }
605569688d5fSdrh   return rc;
6056ed7c855cSdrh }
6057ed7c855cSdrh 
6058ed7c855cSdrh /*
6059f063e08fSdrh ** This is a variant of sqlite3PagerWrite() that runs when the sector size
6060f063e08fSdrh ** is larger than the page size.  SQLite makes the (reasonable) assumption that
6061f063e08fSdrh ** all bytes of a sector are written together by hardware.  Hence, all bytes of
6062f063e08fSdrh ** a sector need to be journalled in case of a power loss in the middle of
6063f063e08fSdrh ** a write.
60644099f6e1Sdanielk1977 **
6065f063e08fSdrh ** Usually, the sector size is less than or equal to the page size, in which
6066e399ac2eSdrh ** case pages can be individually written.  This routine only runs in the
6067e399ac2eSdrh ** exceptional case where the page size is smaller than the sector size.
60684099f6e1Sdanielk1977 */
pagerWriteLargeSector(PgHdr * pPg)6069f063e08fSdrh static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
6070f063e08fSdrh   int rc = SQLITE_OK;          /* Return code */
60714099f6e1Sdanielk1977   Pgno nPageCount;             /* Total number of pages in database file */
60724099f6e1Sdanielk1977   Pgno pg1;                    /* First page of the sector pPg is located on. */
60737d113eb0Sdrh   int nPage = 0;               /* Number of pages starting at pg1 to journal */
6074bea2a948Sdanielk1977   int ii;                      /* Loop counter */
6075bea2a948Sdanielk1977   int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
6076f063e08fSdrh   Pager *pPager = pPg->pPager; /* The pager that owns pPg */
6077c65faab2Sdrh   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
60784099f6e1Sdanielk1977 
607940c3941cSdrh   /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
6080314f30dbSdrh   ** a journal header to be written between the pages journaled by
6081314f30dbSdrh   ** this function.
60824099f6e1Sdanielk1977   */
6083b3175389Sdanielk1977   assert( !MEMDB );
608440c3941cSdrh   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
608540c3941cSdrh   pPager->doNotSpill |= SPILLFLAG_NOSYNC;
60864099f6e1Sdanielk1977 
60874099f6e1Sdanielk1977   /* This trick assumes that both the page-size and sector-size are
60884099f6e1Sdanielk1977   ** an integer power of 2. It sets variable pg1 to the identifier
60894099f6e1Sdanielk1977   ** of the first page of the sector pPg is located on.
60904099f6e1Sdanielk1977   */
60914099f6e1Sdanielk1977   pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
60924099f6e1Sdanielk1977 
6093937ac9daSdan   nPageCount = pPager->dbSize;
60944099f6e1Sdanielk1977   if( pPg->pgno>nPageCount ){
60954099f6e1Sdanielk1977     nPage = (pPg->pgno - pg1)+1;
60964099f6e1Sdanielk1977   }else if( (pg1+nPagePerSector-1)>nPageCount ){
60974099f6e1Sdanielk1977     nPage = nPageCount+1-pg1;
60984099f6e1Sdanielk1977   }else{
60994099f6e1Sdanielk1977     nPage = nPagePerSector;
61004099f6e1Sdanielk1977   }
61014099f6e1Sdanielk1977   assert(nPage>0);
61024099f6e1Sdanielk1977   assert(pg1<=pPg->pgno);
61034099f6e1Sdanielk1977   assert((pg1+nPage)>pPg->pgno);
61044099f6e1Sdanielk1977 
61054099f6e1Sdanielk1977   for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
61064099f6e1Sdanielk1977     Pgno pg = pg1+ii;
6107dd97a49cSdanielk1977     PgHdr *pPage;
6108f5e7bb51Sdrh     if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
6109584bfcaeSdrh       if( pg!=PAGER_SJ_PGNO(pPager) ){
61109584f58cSdrh         rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
61114099f6e1Sdanielk1977         if( rc==SQLITE_OK ){
61124099f6e1Sdanielk1977           rc = pager_write(pPage);
61138c0a791aSdanielk1977           if( pPage->flags&PGHDR_NEED_SYNC ){
6114dd97a49cSdanielk1977             needSync = 1;
6115dd97a49cSdanielk1977           }
6116da8a330aSdrh           sqlite3PagerUnrefNotNull(pPage);
61174099f6e1Sdanielk1977         }
61184099f6e1Sdanielk1977       }
6119c137807aSdrh     }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
61208c0a791aSdanielk1977       if( pPage->flags&PGHDR_NEED_SYNC ){
6121dd97a49cSdanielk1977         needSync = 1;
61224099f6e1Sdanielk1977       }
6123da8a330aSdrh       sqlite3PagerUnrefNotNull(pPage);
61244099f6e1Sdanielk1977     }
6125dd97a49cSdanielk1977   }
6126dd97a49cSdanielk1977 
6127ee03d629Sdrh   /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
6128dd97a49cSdanielk1977   ** starting at pg1, then it needs to be set for all of them. Because
6129dd97a49cSdanielk1977   ** writing to any of these nPage pages may damage the others, the
6130dd97a49cSdanielk1977   ** journal file must contain sync()ed copies of all of them
6131dd97a49cSdanielk1977   ** before any of them can be written out to the database file.
6132dd97a49cSdanielk1977   */
6133a299d612Sdanielk1977   if( rc==SQLITE_OK && needSync ){
613473d66fdbSdan     assert( !MEMDB );
6135b480dc23Sdrh     for(ii=0; ii<nPage; ii++){
6136c137807aSdrh       PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
6137ee03d629Sdrh       if( pPage ){
6138ee03d629Sdrh         pPage->flags |= PGHDR_NEED_SYNC;
6139da8a330aSdrh         sqlite3PagerUnrefNotNull(pPage);
6140dd97a49cSdanielk1977       }
6141ee03d629Sdrh     }
6142dd97a49cSdanielk1977   }
61434099f6e1Sdanielk1977 
614440c3941cSdrh   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
614540c3941cSdrh   pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
61464099f6e1Sdanielk1977   return rc;
61474099f6e1Sdanielk1977 }
61484099f6e1Sdanielk1977 
61494099f6e1Sdanielk1977 /*
6150f063e08fSdrh ** Mark a data page as writeable. This routine must be called before
6151f063e08fSdrh ** making changes to a page. The caller must check the return value
6152f063e08fSdrh ** of this function and be careful not to change any page data unless
6153f063e08fSdrh ** this routine returns SQLITE_OK.
6154f063e08fSdrh **
6155f063e08fSdrh ** The difference between this function and pager_write() is that this
6156f063e08fSdrh ** function also deals with the special case where 2 or more pages
6157f063e08fSdrh ** fit on a single disk sector. In this case all co-resident pages
6158f063e08fSdrh ** must have been written to the journal file before returning.
6159f063e08fSdrh **
6160f063e08fSdrh ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
6161f063e08fSdrh ** as appropriate. Otherwise, SQLITE_OK.
6162f063e08fSdrh */
sqlite3PagerWrite(PgHdr * pPg)6163f063e08fSdrh int sqlite3PagerWrite(PgHdr *pPg){
6164b3475530Sdrh   Pager *pPager = pPg->pPager;
616550642b1dSdrh   assert( (pPg->flags & PGHDR_MMAP)==0 );
616650642b1dSdrh   assert( pPager->eState>=PAGER_WRITER_LOCKED );
616750642b1dSdrh   assert( assert_pager_state(pPager) );
61686606586dSdrh   if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
6169b3475530Sdrh     if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
6170b3475530Sdrh     return SQLITE_OK;
61716606586dSdrh   }else if( pPager->errCode ){
61726606586dSdrh     return pPager->errCode;
6173b3475530Sdrh   }else if( pPager->sectorSize > (u32)pPager->pageSize ){
617441113b64Sdan     assert( pPager->tempFile==0 );
6175f063e08fSdrh     return pagerWriteLargeSector(pPg);
6176f063e08fSdrh   }else{
6177f063e08fSdrh     return pager_write(pPg);
6178f063e08fSdrh   }
6179f063e08fSdrh }
6180f063e08fSdrh 
6181f063e08fSdrh /*
6182aacc543eSdrh ** Return TRUE if the page given in the argument was previously passed
61833b8a05f6Sdanielk1977 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
61846019e168Sdrh ** to change the content of the page.
61856019e168Sdrh */
61867d3a666fSdanielk1977 #ifndef NDEBUG
sqlite3PagerIswriteable(DbPage * pPg)61873b8a05f6Sdanielk1977 int sqlite3PagerIswriteable(DbPage *pPg){
61881aacbdb3Sdrh   return pPg->flags & PGHDR_WRITEABLE;
61896019e168Sdrh }
61907d3a666fSdanielk1977 #endif
61916019e168Sdrh 
6192001bbcbbSdrh /*
619330e58750Sdrh ** A call to this routine tells the pager that it is not necessary to
6194538f570cSdrh ** write the information on page pPg back to the disk, even though
6195dfe88eceSdrh ** that page might be marked as dirty.  This happens, for example, when
6196dfe88eceSdrh ** the page has been added as a leaf of the freelist and so its
6197dfe88eceSdrh ** content no longer matters.
619830e58750Sdrh **
619930e58750Sdrh ** The overlying software layer calls this routine when all of the data
620030e58750Sdrh ** on the given page is unused. The pager marks the page as clean so
620130e58750Sdrh ** that it does not get written to disk.
620230e58750Sdrh **
6203bea2a948Sdanielk1977 ** Tests show that this optimization can quadruple the speed of large
6204bea2a948Sdanielk1977 ** DELETE operations.
6205c88ae52dSdan **
6206c88ae52dSdan ** This optimization cannot be used with a temp-file, as the page may
6207c88ae52dSdan ** have been dirty at the start of the transaction. In that case, if
6208c88ae52dSdan ** memory pressure forces page pPg out of the cache, the data does need
6209c88ae52dSdan ** to be written out to disk so that it may be read back in if the
6210c88ae52dSdan ** current transaction is rolled back.
621130e58750Sdrh */
sqlite3PagerDontWrite(PgHdr * pPg)6212bea2a948Sdanielk1977 void sqlite3PagerDontWrite(PgHdr *pPg){
6213538f570cSdrh   Pager *pPager = pPg->pPager;
6214c88ae52dSdan   if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
621530d53701Sdrh     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
6216538f570cSdrh     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
621733e3216aSdanielk1977     pPg->flags |= PGHDR_DONT_WRITE;
6218b3475530Sdrh     pPg->flags &= ~PGHDR_WRITEABLE;
6219a0f6b124Sdrh     testcase( pPg->flags & PGHDR_NEED_SYNC );
62205f848c3aSdan     pager_set_pagehash(pPg);
622130e58750Sdrh   }
622230e58750Sdrh }
622345d6882fSdanielk1977 
622445d6882fSdanielk1977 /*
6225bea2a948Sdanielk1977 ** This routine is called to increment the value of the database file
6226bea2a948Sdanielk1977 ** change-counter, stored as a 4-byte big-endian integer starting at
622754a7347aSdrh ** byte offset 24 of the pager file.  The secondary change counter at
622854a7347aSdrh ** 92 is also updated, as is the SQLite version number at offset 96.
622954a7347aSdrh **
623054a7347aSdrh ** But this only happens if the pPager->changeCountDone flag is false.
623154a7347aSdrh ** To avoid excess churning of page 1, the update only happens once.
623254a7347aSdrh ** See also the pager_write_changecounter() routine that does an
623354a7347aSdrh ** unconditional update of the change counters.
623445d6882fSdanielk1977 **
6235b480dc23Sdrh ** If the isDirectMode flag is zero, then this is done by calling
6236bea2a948Sdanielk1977 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
6237bea2a948Sdanielk1977 ** page data. In this case the file will be updated when the current
6238bea2a948Sdanielk1977 ** transaction is committed.
623945d6882fSdanielk1977 **
6240b480dc23Sdrh ** The isDirectMode flag may only be non-zero if the library was compiled
6241bea2a948Sdanielk1977 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
6242bea2a948Sdanielk1977 ** if isDirect is non-zero, then the database file is updated directly
6243bea2a948Sdanielk1977 ** by writing an updated version of page 1 using a call to the
6244bea2a948Sdanielk1977 ** sqlite3OsWrite() function.
624545d6882fSdanielk1977 */
pager_incr_changecounter(Pager * pPager,int isDirectMode)6246bea2a948Sdanielk1977 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
6247c7b6017cSdanielk1977   int rc = SQLITE_OK;
624880e35f46Sdrh 
6249d0864087Sdan   assert( pPager->eState==PAGER_WRITER_CACHEMOD
6250d0864087Sdan        || pPager->eState==PAGER_WRITER_DBMOD
6251d0864087Sdan   );
6252d0864087Sdan   assert( assert_pager_state(pPager) );
6253d0864087Sdan 
6254bea2a948Sdanielk1977   /* Declare and initialize constant integer 'isDirect'. If the
6255bea2a948Sdanielk1977   ** atomic-write optimization is enabled in this build, then isDirect
6256bea2a948Sdanielk1977   ** is initialized to the value passed as the isDirectMode parameter
6257bea2a948Sdanielk1977   ** to this function. Otherwise, it is always set to zero.
6258bea2a948Sdanielk1977   **
6259bea2a948Sdanielk1977   ** The idea is that if the atomic-write optimization is not
6260bea2a948Sdanielk1977   ** enabled at compile time, the compiler can omit the tests of
6261bea2a948Sdanielk1977   ** 'isDirect' below, as well as the block enclosed in the
6262bea2a948Sdanielk1977   ** "if( isDirect )" condition.
6263bea2a948Sdanielk1977   */
6264701bb3b4Sdrh #ifndef SQLITE_ENABLE_ATOMIC_WRITE
6265b480dc23Sdrh # define DIRECT_MODE 0
6266bea2a948Sdanielk1977   assert( isDirectMode==0 );
6267dc86e2b2Sdrh   UNUSED_PARAMETER(isDirectMode);
6268bea2a948Sdanielk1977 #else
6269b480dc23Sdrh # define DIRECT_MODE isDirectMode
6270701bb3b4Sdrh #endif
6271bea2a948Sdanielk1977 
6272aa2db79aSdrh   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
6273bea2a948Sdanielk1977     PgHdr *pPgHdr;                /* Reference to page 1 */
6274bea2a948Sdanielk1977 
6275bea2a948Sdanielk1977     assert( !pPager->tempFile && isOpen(pPager->fd) );
6276bea2a948Sdanielk1977 
627780e35f46Sdrh     /* Open page 1 of the file for writing. */
62789584f58cSdrh     rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
6279bea2a948Sdanielk1977     assert( pPgHdr==0 || rc==SQLITE_OK );
6280c7b6017cSdanielk1977 
6281bea2a948Sdanielk1977     /* If page one was fetched successfully, and this function is not
6282ad7516c4Sdrh     ** operating in direct-mode, make page 1 writable.  When not in
6283ad7516c4Sdrh     ** direct mode, page 1 is always held in cache and hence the PagerGet()
6284ad7516c4Sdrh     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
6285bea2a948Sdanielk1977     */
6286c5aae5c9Sdrh     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
628780e35f46Sdrh       rc = sqlite3PagerWrite(pPgHdr);
6288c7b6017cSdanielk1977     }
628980e35f46Sdrh 
6290bea2a948Sdanielk1977     if( rc==SQLITE_OK ){
629154a7347aSdrh       /* Actually do the update of the change counter */
629254a7347aSdrh       pager_write_changecounter(pPgHdr);
6293f92a4e35Sdrh 
6294bea2a948Sdanielk1977       /* If running in direct mode, write the contents of page 1 to the file. */
6295b480dc23Sdrh       if( DIRECT_MODE ){
629668928b6cSdan         const void *zBuf;
62973460d19cSdanielk1977         assert( pPager->dbFileSize>0 );
6298b48c0d59Sdrh         zBuf = pPgHdr->pData;
629968928b6cSdan         if( rc==SQLITE_OK ){
6300c7b6017cSdanielk1977           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
63019ad3ee40Sdrh           pPager->aStat[PAGER_STAT_WRITE]++;
630268928b6cSdan         }
6303bea2a948Sdanielk1977         if( rc==SQLITE_OK ){
63048e4714b3Sdan           /* Update the pager's copy of the change-counter. Otherwise, the
63058e4714b3Sdan           ** next time a read transaction is opened the cache will be
63068e4714b3Sdan           ** flushed (as the change-counter values will not match).  */
63078e4714b3Sdan           const void *pCopy = (const void *)&((const char *)zBuf)[24];
63088e4714b3Sdan           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
6309bea2a948Sdanielk1977           pPager->changeCountDone = 1;
6310bea2a948Sdanielk1977         }
6311b480dc23Sdrh       }else{
6312b480dc23Sdrh         pPager->changeCountDone = 1;
6313b480dc23Sdrh       }
6314bea2a948Sdanielk1977     }
6315c7b6017cSdanielk1977 
631680e35f46Sdrh     /* Release the page reference. */
631780e35f46Sdrh     sqlite3PagerUnref(pPgHdr);
631880e35f46Sdrh   }
6319c7b6017cSdanielk1977   return rc;
632080e35f46Sdrh }
632180e35f46Sdrh 
632280e35f46Sdrh /*
6323c97d8463Sdrh ** Sync the database file to disk. This is a no-op for in-memory databases
6324bea2a948Sdanielk1977 ** or pages with the Pager.noSync flag set.
6325bea2a948Sdanielk1977 **
6326c97d8463Sdrh ** If successful, or if called on a pager for which it is a no-op, this
6327bea2a948Sdanielk1977 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
6328f653d782Sdanielk1977 */
sqlite3PagerSync(Pager * pPager,const char * zSuper)6329067b92baSdrh int sqlite3PagerSync(Pager *pPager, const char *zSuper){
6330534a58a7Sdrh   int rc = SQLITE_OK;
6331067b92baSdrh   void *pArg = (void*)zSuper;
63326f68f164Sdan   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
6333999cd08aSdan   if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
6334a01abc30Sdan   if( rc==SQLITE_OK && !pPager->noSync ){
6335d1cf7e29Sdan     assert( !MEMDB );
6336c97d8463Sdrh     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
6337354bfe03Sdan   }
6338f653d782Sdanielk1977   return rc;
6339f653d782Sdanielk1977 }
6340f653d782Sdanielk1977 
6341f653d782Sdanielk1977 /*
6342eb9444a4Sdan ** This function may only be called while a write-transaction is active in
6343eb9444a4Sdan ** rollback. If the connection is in WAL mode, this call is a no-op.
6344eb9444a4Sdan ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
6345eb9444a4Sdan ** the database file, an attempt is made to obtain one.
6346eb9444a4Sdan **
6347eb9444a4Sdan ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
6348eb9444a4Sdan ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
6349eb9444a4Sdan ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
6350eb9444a4Sdan ** returned.
6351eb9444a4Sdan */
sqlite3PagerExclusiveLock(Pager * pPager)6352eb9444a4Sdan int sqlite3PagerExclusiveLock(Pager *pPager){
6353dbf6773eSdan   int rc = pPager->errCode;
6354dbf6773eSdan   assert( assert_pager_state(pPager) );
6355dbf6773eSdan   if( rc==SQLITE_OK ){
6356d0864087Sdan     assert( pPager->eState==PAGER_WRITER_CACHEMOD
6357d0864087Sdan          || pPager->eState==PAGER_WRITER_DBMOD
6358de1ae34eSdan          || pPager->eState==PAGER_WRITER_LOCKED
6359d0864087Sdan     );
6360d0864087Sdan     assert( assert_pager_state(pPager) );
6361eb9444a4Sdan     if( 0==pagerUseWal(pPager) ){
636254919f82Sdan       rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
6363eb9444a4Sdan     }
6364dbf6773eSdan   }
6365eb9444a4Sdan   return rc;
6366eb9444a4Sdan }
6367eb9444a4Sdan 
6368eb9444a4Sdan /*
6369067b92baSdrh ** Sync the database file for the pager pPager. zSuper points to the name
6370067b92baSdrh ** of a super-journal file that should be written into the individual
6371067b92baSdrh ** journal file. zSuper may be NULL, which is interpreted as no
6372067b92baSdrh ** super-journal (a single database transaction).
637380e35f46Sdrh **
6374bea2a948Sdanielk1977 ** This routine ensures that:
6375bea2a948Sdanielk1977 **
6376bea2a948Sdanielk1977 **   * The database file change-counter is updated,
6377bea2a948Sdanielk1977 **   * the journal is synced (unless the atomic-write optimization is used),
6378bea2a948Sdanielk1977 **   * all dirty pages are written to the database file,
6379bea2a948Sdanielk1977 **   * the database file is truncated (if required), and
6380bea2a948Sdanielk1977 **   * the database file synced.
6381bea2a948Sdanielk1977 **
6382bea2a948Sdanielk1977 ** The only thing that remains to commit the transaction is to finalize
6383bea2a948Sdanielk1977 ** (delete, truncate or zero the first part of) the journal file (or
6384067b92baSdrh ** delete the super-journal file if specified).
638580e35f46Sdrh **
6386067b92baSdrh ** Note that if zSuper==NULL, this does not overwrite a previous value
638780e35f46Sdrh ** passed to an sqlite3PagerCommitPhaseOne() call.
638880e35f46Sdrh **
6389f653d782Sdanielk1977 ** If the final parameter - noSync - is true, then the database file itself
6390f653d782Sdanielk1977 ** is not synced. The caller must call sqlite3PagerSync() directly to
6391f653d782Sdanielk1977 ** sync the database file before calling CommitPhaseTwo() to delete the
6392f653d782Sdanielk1977 ** journal file in this case.
639380e35f46Sdrh */
sqlite3PagerCommitPhaseOne(Pager * pPager,const char * zSuper,int noSync)6394f653d782Sdanielk1977 int sqlite3PagerCommitPhaseOne(
6395bea2a948Sdanielk1977   Pager *pPager,                  /* Pager object */
6396067b92baSdrh   const char *zSuper,            /* If not NULL, the super-journal name */
6397bea2a948Sdanielk1977   int noSync                      /* True to omit the xSync on the db file */
6398f653d782Sdanielk1977 ){
6399bea2a948Sdanielk1977   int rc = SQLITE_OK;             /* Return code */
640080e35f46Sdrh 
6401de1ae34eSdan   assert( pPager->eState==PAGER_WRITER_LOCKED
6402d0864087Sdan        || pPager->eState==PAGER_WRITER_CACHEMOD
6403d0864087Sdan        || pPager->eState==PAGER_WRITER_DBMOD
64045db56401Sdan        || pPager->eState==PAGER_ERROR
6405d0864087Sdan   );
6406d0864087Sdan   assert( assert_pager_state(pPager) );
6407d0864087Sdan 
6408dd3cd977Sdrh   /* If a prior error occurred, report that error again. */
6409719e3a7aSdrh   if( NEVER(pPager->errCode) ) return pPager->errCode;
6410dad31b5eSdanielk1977 
6411ead01fd2Sdrh   /* Provide the ability to easily simulate an I/O error during testing */
6412a7a45973Sdrh   if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
6413ead01fd2Sdrh 
6414067b92baSdrh   PAGERTRACE(("DATABASE SYNC: File=%s zSuper=%s nSize=%d\n",
6415067b92baSdrh       pPager->zFilename, zSuper, pPager->dbSize));
641680e35f46Sdrh 
6417d0864087Sdan   /* If no database changes have been made, return early. */
6418d0864087Sdan   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
6419d0864087Sdan 
642041113b64Sdan   assert( MEMDB==0 || pPager->tempFile );
6421199f56b9Sdan   assert( isOpen(pPager->fd) || pPager->tempFile );
64224bf7d21fSdrh   if( 0==pagerFlushOnCommit(pPager, 1) ){
6423b480dc23Sdrh     /* If this is an in-memory db, or no pages have been written to, or this
6424b480dc23Sdrh     ** function has already been called, it is mostly a no-op.  However, any
642541113b64Sdan     ** backup in progress needs to be restarted.  */
64260410302eSdanielk1977     sqlite3BackupRestart(pPager->pBackup);
6427d0864087Sdan   }else{
6428140a5987Sdan     PgHdr *pList;
64297ed91f23Sdrh     if( pagerUseWal(pPager) ){
6430e5a1320dSdrh       PgHdr *pPageOne = 0;
6431140a5987Sdan       pList = sqlite3PcacheDirtyList(pPager->pPCache);
6432e5a1320dSdrh       if( pList==0 ){
6433e5a1320dSdrh         /* Must have at least one page for the WAL commit flag.
6434e5a1320dSdrh         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
64359584f58cSdrh         rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
6436e5a1320dSdrh         pList = pPageOne;
6437e5a1320dSdrh         pList->pDirty = 0;
6438e5a1320dSdrh       }
643914438d12Sdrh       assert( rc==SQLITE_OK );
644014438d12Sdrh       if( ALWAYS(pList) ){
64414eb02a45Sdrh         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
64427c24610eSdan       }
6443e5a1320dSdrh       sqlite3PagerUnref(pPageOne);
644410ec894cSdan       if( rc==SQLITE_OK ){
64457c24610eSdan         sqlite3PcacheCleanAll(pPager->pPCache);
644610ec894cSdan       }
64477c24610eSdan     }else{
64482df9478fSdrh       /* The bBatch boolean is true if the batch-atomic-write commit method
64492df9478fSdrh       ** should be used.  No rollback journal is created if batch-atomic-write
64502df9478fSdrh       ** is enabled.
64512df9478fSdrh       */
64522df9478fSdrh #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
6453378a2da9Sdrh       sqlite3_file *fd = pPager->fd;
6454067b92baSdrh       int bBatch = zSuper==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
64552df9478fSdrh         && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
64562df9478fSdrh         && !pPager->noSync
64572df9478fSdrh         && sqlite3JournalIsInMemory(pPager->jfd);
64582df9478fSdrh #else
64592df9478fSdrh #     define bBatch 0
64602df9478fSdrh #endif
64612df9478fSdrh 
64622df9478fSdrh #ifdef SQLITE_ENABLE_ATOMIC_WRITE
6463bea2a948Sdanielk1977       /* The following block updates the change-counter. Exactly how it
6464bea2a948Sdanielk1977       ** does this depends on whether or not the atomic-update optimization
6465bea2a948Sdanielk1977       ** was enabled at compile time, and if this transaction meets the
6466bea2a948Sdanielk1977       ** runtime criteria to use the operation:
6467c7b6017cSdanielk1977       **
6468bea2a948Sdanielk1977       **    * The file-system supports the atomic-write property for
6469c7b6017cSdanielk1977       **      blocks of size page-size, and
6470bea2a948Sdanielk1977       **    * This commit is not part of a multi-file transaction, and
6471bea2a948Sdanielk1977       **    * Exactly one page has been modified and store in the journal file.
6472c7b6017cSdanielk1977       **
6473bea2a948Sdanielk1977       ** If the optimization was not enabled at compile time, then the
6474bea2a948Sdanielk1977       ** pager_incr_changecounter() function is called to update the change
6475bea2a948Sdanielk1977       ** counter in 'indirect-mode'. If the optimization is compiled in but
6476bea2a948Sdanielk1977       ** is not applicable to this transaction, call sqlite3JournalCreate()
6477bea2a948Sdanielk1977       ** to make sure the journal file has actually been created, then call
6478bea2a948Sdanielk1977       ** pager_incr_changecounter() to update the change-counter in indirect
6479bea2a948Sdanielk1977       ** mode.
6480bea2a948Sdanielk1977       **
6481bea2a948Sdanielk1977       ** Otherwise, if the optimization is both enabled and applicable,
6482bea2a948Sdanielk1977       ** then call pager_incr_changecounter() to update the change-counter
6483bea2a948Sdanielk1977       ** in 'direct' mode. In this case the journal file will never be
6484bea2a948Sdanielk1977       ** created for this transaction.
6485c7b6017cSdanielk1977       */
6486efe16971Sdan       if( bBatch==0 ){
6487bea2a948Sdanielk1977         PgHdr *pPg;
64883f94b609Sdan         assert( isOpen(pPager->jfd)
64893f94b609Sdan             || pPager->journalMode==PAGER_JOURNALMODE_OFF
64903f94b609Sdan             || pPager->journalMode==PAGER_JOURNALMODE_WAL
64913f94b609Sdan             );
6492067b92baSdrh         if( !zSuper && isOpen(pPager->jfd)
6493bea2a948Sdanielk1977          && pPager->journalOff==jrnlBufferSize(pPager)
64944d9c1b7fSdan          && pPager->dbSize>=pPager->dbOrigSize
6495efe16971Sdan          && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
6496bea2a948Sdanielk1977         ){
6497bea2a948Sdanielk1977           /* Update the db file change counter via the direct-write method. The
6498bea2a948Sdanielk1977           ** following call will modify the in-memory representation of page 1
6499bea2a948Sdanielk1977           ** to include the updated change counter and then write page 1
6500bea2a948Sdanielk1977           ** directly to the database file. Because of the atomic-write
6501bea2a948Sdanielk1977           ** property of the host file-system, this is safe.
6502c7b6017cSdanielk1977           */
6503c7b6017cSdanielk1977           rc = pager_incr_changecounter(pPager, 1);
6504f55b8998Sdanielk1977         }else{
6505f55b8998Sdanielk1977           rc = sqlite3JournalCreate(pPager->jfd);
6506bea2a948Sdanielk1977           if( rc==SQLITE_OK ){
6507c7b6017cSdanielk1977             rc = pager_incr_changecounter(pPager, 0);
6508bea2a948Sdanielk1977           }
6509bea2a948Sdanielk1977         }
6510d67a9770Sdan       }
6511140a5987Sdan #else  /* SQLITE_ENABLE_ATOMIC_WRITE */
6512d67a9770Sdan #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
6513067b92baSdrh       if( zSuper ){
6514d67a9770Sdan         rc = sqlite3JournalCreate(pPager->jfd);
6515d67a9770Sdan         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
6516140a5987Sdan         assert( bBatch==0 );
6517d67a9770Sdan       }
6518bea2a948Sdanielk1977 #endif
6519efe16971Sdan       rc = pager_incr_changecounter(pPager, 0);
6520140a5987Sdan #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
6521bea2a948Sdanielk1977       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
6522bea2a948Sdanielk1977 
6523067b92baSdrh       /* Write the super-journal name into the journal file. If a
6524067b92baSdrh       ** super-journal file name has already been written to the journal file,
6525067b92baSdrh       ** or if zSuper is NULL (no super-journal), then this call is a no-op.
6526bea2a948Sdanielk1977       */
6527067b92baSdrh       rc = writeSuperJournal(pPager, zSuper);
6528bea2a948Sdanielk1977       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
6529bea2a948Sdanielk1977 
653051133eaeSdan       /* Sync the journal file and write all dirty pages to the database.
653151133eaeSdan       ** If the atomic-update optimization is being used, this sync will not
653251133eaeSdan       ** create the journal file or perform any real IO.
653351133eaeSdan       **
653451133eaeSdan       ** Because the change-counter page was just modified, unless the
653551133eaeSdan       ** atomic-update optimization is used it is almost certain that the
653651133eaeSdan       ** journal requires a sync here. However, in locking_mode=exclusive
653751133eaeSdan       ** on a system under memory pressure it is just possible that this is
653851133eaeSdan       ** not the case. In this case it is likely enough that the redundant
653951133eaeSdan       ** xSync() call will be changed to a no-op by the OS anyhow.
6540bea2a948Sdanielk1977       */
6541937ac9daSdan       rc = syncJournal(pPager, 0);
6542bea2a948Sdanielk1977       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
6543bea2a948Sdanielk1977 
6544140a5987Sdan       pList = sqlite3PcacheDirtyList(pPager->pPCache);
65454522c3e8Sdan #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
6546efe16971Sdan       if( bBatch ){
6547efe16971Sdan         rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
6548140a5987Sdan         if( rc==SQLITE_OK ){
6549140a5987Sdan           rc = pager_write_pagelist(pPager, pList);
6550efe16971Sdan           if( rc==SQLITE_OK ){
6551efe16971Sdan             rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
6552b8fff29cSdan           }
6553b8fff29cSdan           if( rc!=SQLITE_OK ){
6554b8fff29cSdan             sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
6555efe16971Sdan           }
6556efe16971Sdan         }
6557efe16971Sdan 
6558140a5987Sdan         if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
6559140a5987Sdan           rc = sqlite3JournalCreate(pPager->jfd);
6560140a5987Sdan           if( rc!=SQLITE_OK ){
6561140a5987Sdan             sqlite3OsClose(pPager->jfd);
6562b0b02300Sdrh             goto commit_phase_one_exit;
6563140a5987Sdan           }
6564140a5987Sdan           bBatch = 0;
6565140a5987Sdan         }else{
6566140a5987Sdan           sqlite3OsClose(pPager->jfd);
6567140a5987Sdan         }
6568140a5987Sdan       }
65694522c3e8Sdan #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
6570140a5987Sdan 
6571b0b02300Sdrh       if( bBatch==0 ){
6572140a5987Sdan         rc = pager_write_pagelist(pPager, pList);
6573140a5987Sdan       }
6574153c62c4Sdrh       if( rc!=SQLITE_OK ){
657504c3a46eSdrh         assert( rc!=SQLITE_IOERR_BLOCKED );
6576bea2a948Sdanielk1977         goto commit_phase_one_exit;
6577153c62c4Sdrh       }
65788c0a791aSdanielk1977       sqlite3PcacheCleanAll(pPager->pPCache);
657980e35f46Sdrh 
6580bc1a3c6cSdan       /* If the file on disk is smaller than the database image, use
6581bc1a3c6cSdan       ** pager_truncate to grow the file here. This can happen if the database
6582bc1a3c6cSdan       ** image was extended as part of the current transaction and then the
6583bc1a3c6cSdan       ** last page in the db image moved to the free-list. In this case the
6584bc1a3c6cSdan       ** last page is never written out to disk, leaving the database file
6585bc1a3c6cSdan       ** undersized. Fix this now if it is the case.  */
6586bc1a3c6cSdan       if( pPager->dbSize>pPager->dbFileSize ){
6587584bfcaeSdrh         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_SJ_PGNO(pPager));
6588d0864087Sdan         assert( pPager->eState==PAGER_WRITER_DBMOD );
6589bea2a948Sdanielk1977         rc = pager_truncate(pPager, nNew);
6590bea2a948Sdanielk1977         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
6591f90b7260Sdanielk1977       }
6592f90b7260Sdanielk1977 
6593bea2a948Sdanielk1977       /* Finally, sync the database file. */
6594354bfe03Sdan       if( !noSync ){
6595067b92baSdrh         rc = sqlite3PagerSync(pPager, zSuper);
659680e35f46Sdrh       }
659780e35f46Sdrh       IOTRACE(("DBSYNC %p\n", pPager))
65987c24610eSdan     }
659980e35f46Sdrh   }
660080e35f46Sdrh 
6601bea2a948Sdanielk1977 commit_phase_one_exit:
6602d0864087Sdan   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
6603d0864087Sdan     pPager->eState = PAGER_WRITER_FINISHED;
6604d0864087Sdan   }
660580e35f46Sdrh   return rc;
660680e35f46Sdrh }
660780e35f46Sdrh 
660880e35f46Sdrh 
660980e35f46Sdrh /*
6610bea2a948Sdanielk1977 ** When this function is called, the database file has been completely
6611bea2a948Sdanielk1977 ** updated to reflect the changes made by the current transaction and
6612bea2a948Sdanielk1977 ** synced to disk. The journal file still exists in the file-system
6613bea2a948Sdanielk1977 ** though, and if a failure occurs at this point it will eventually
6614bea2a948Sdanielk1977 ** be used as a hot-journal and the current transaction rolled back.
6615d9b0257aSdrh **
6616bea2a948Sdanielk1977 ** This function finalizes the journal file, either by deleting,
6617bea2a948Sdanielk1977 ** truncating or partially zeroing it, so that it cannot be used
6618bea2a948Sdanielk1977 ** for hot-journal rollback. Once this is done the transaction is
6619bea2a948Sdanielk1977 ** irrevocably committed.
6620bea2a948Sdanielk1977 **
6621bea2a948Sdanielk1977 ** If an error occurs, an IO error code is returned and the pager
6622bea2a948Sdanielk1977 ** moves into the error state. Otherwise, SQLITE_OK is returned.
6623ed7c855cSdrh */
sqlite3PagerCommitPhaseTwo(Pager * pPager)662480e35f46Sdrh int sqlite3PagerCommitPhaseTwo(Pager *pPager){
6625bea2a948Sdanielk1977   int rc = SQLITE_OK;                  /* Return code */
6626d9b0257aSdrh 
6627b480dc23Sdrh   /* This routine should not be called if a prior error has occurred.
6628b480dc23Sdrh   ** But if (due to a coding error elsewhere in the system) it does get
6629b480dc23Sdrh   ** called, just return the same error code without doing anything. */
6630b480dc23Sdrh   if( NEVER(pPager->errCode) ) return pPager->errCode;
66317a1d7c39Sdan   pPager->iDataVersion++;
6632bea2a948Sdanielk1977 
6633de1ae34eSdan   assert( pPager->eState==PAGER_WRITER_LOCKED
6634d0864087Sdan        || pPager->eState==PAGER_WRITER_FINISHED
6635d0864087Sdan        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
6636d0864087Sdan   );
6637d0864087Sdan   assert( assert_pager_state(pPager) );
6638d0864087Sdan 
6639bea2a948Sdanielk1977   /* An optimization. If the database was not actually modified during
6640bea2a948Sdanielk1977   ** this transaction, the pager is running in exclusive-mode and is
6641bea2a948Sdanielk1977   ** using persistent journals, then this function is a no-op.
6642bea2a948Sdanielk1977   **
6643bea2a948Sdanielk1977   ** The start of the journal file currently contains a single journal
6644bea2a948Sdanielk1977   ** header with the nRec field set to 0. If such a journal is used as
6645bea2a948Sdanielk1977   ** a hot-journal during hot-journal rollback, 0 changes will be made
6646bea2a948Sdanielk1977   ** to the database file. So there is no need to zero the journal
6647bea2a948Sdanielk1977   ** header. Since the pager is in exclusive mode, there is no need
6648bea2a948Sdanielk1977   ** to drop any locks either.
6649bea2a948Sdanielk1977   */
6650de1ae34eSdan   if( pPager->eState==PAGER_WRITER_LOCKED
6651d0864087Sdan    && pPager->exclusiveMode
66523cfe0703Sdanielk1977    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
66533cfe0703Sdanielk1977   ){
66546b63ab47Sdan     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
6655d0864087Sdan     pPager->eState = PAGER_READER;
6656d138c016Sdrh     return SQLITE_OK;
6657d138c016Sdrh   }
6658bea2a948Sdanielk1977 
665930d53701Sdrh   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
6660067b92baSdrh   rc = pager_end_transaction(pPager, pPager->setSuper, 1);
6661bea2a948Sdanielk1977   return pager_error(pPager, rc);
6662ed7c855cSdrh }
6663ed7c855cSdrh 
6664ed7c855cSdrh /*
666573d66fdbSdan ** If a write transaction is open, then all changes made within the
666673d66fdbSdan ** transaction are reverted and the current write-transaction is closed.
666773d66fdbSdan ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
666873d66fdbSdan ** state if an error occurs.
6669d9b0257aSdrh **
667073d66fdbSdan ** If the pager is already in PAGER_ERROR state when this function is called,
667173d66fdbSdan ** it returns Pager.errCode immediately. No work is performed in this case.
667273d66fdbSdan **
667373d66fdbSdan ** Otherwise, in rollback mode, this function performs two functions:
6674bea2a948Sdanielk1977 **
6675bea2a948Sdanielk1977 **   1) It rolls back the journal file, restoring all database file and
6676bea2a948Sdanielk1977 **      in-memory cache pages to the state they were in when the transaction
6677bea2a948Sdanielk1977 **      was opened, and
667873d66fdbSdan **
6679bea2a948Sdanielk1977 **   2) It finalizes the journal file, so that it is not used for hot
6680bea2a948Sdanielk1977 **      rollback at any point in the future.
6681bea2a948Sdanielk1977 **
668273d66fdbSdan ** Finalization of the journal file (task 2) is only performed if the
668373d66fdbSdan ** rollback is successful.
6684bea2a948Sdanielk1977 **
668573d66fdbSdan ** In WAL mode, all cache-entries containing data modified within the
668673d66fdbSdan ** current transaction are either expelled from the cache or reverted to
668773d66fdbSdan ** their pre-transaction state by re-reading data from the database or
668873d66fdbSdan ** WAL files. The WAL transaction is then closed.
6689ed7c855cSdrh */
sqlite3PagerRollback(Pager * pPager)66903b8a05f6Sdanielk1977 int sqlite3PagerRollback(Pager *pPager){
6691bea2a948Sdanielk1977   int rc = SQLITE_OK;                  /* Return code */
669230d53701Sdrh   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
6693d0864087Sdan 
6694de1ae34eSdan   /* PagerRollback() is a no-op if called in READER or OPEN state. If
6695a42c66bdSdan   ** the pager is already in the ERROR state, the rollback is not
6696a42c66bdSdan   ** attempted here. Instead, the error code is returned to the caller.
6697a42c66bdSdan   */
6698d0864087Sdan   assert( assert_pager_state(pPager) );
6699a42c66bdSdan   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
6700d0864087Sdan   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
6701d0864087Sdan 
67027ed91f23Sdrh   if( pagerUseWal(pPager) ){
67037c24610eSdan     int rc2;
67047c24610eSdan     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
6705067b92baSdrh     rc2 = pager_end_transaction(pPager, pPager->setSuper, 0);
67067c24610eSdan     if( rc==SQLITE_OK ) rc = rc2;
670773d66fdbSdan   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
67089f4beedbSdan     int eState = pPager->eState;
6709bc1a3c6cSdan     rc = pager_end_transaction(pPager, 0, 0);
67109f4beedbSdan     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
67119f4beedbSdan       /* This can happen using journal_mode=off. Move the pager to the error
67129f4beedbSdan       ** state to indicate that the contents of the cache may not be trusted.
67139f4beedbSdan       ** Any active readers will get SQLITE_ABORT.
67149f4beedbSdan       */
67159f4beedbSdan       pPager->errCode = SQLITE_ABORT;
67169f4beedbSdan       pPager->eState = PAGER_ERROR;
671712e6f682Sdrh       setGetterMethod(pPager);
67189f4beedbSdan       return rc;
67199f4beedbSdan     }
6720a6abd041Sdrh   }else{
6721e277be05Sdanielk1977     rc = pager_playback(pPager, 0);
6722a6abd041Sdrh   }
672373d66fdbSdan 
6724a42c66bdSdan   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
6725d4097928Sdan   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
6726a01abc30Sdan           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
6727a01abc30Sdan           || rc==SQLITE_CANTOPEN
6728a01abc30Sdan   );
67298c0a791aSdanielk1977 
673007cb560bSdanielk1977   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
6731b22aa4a6Sdan   ** cache. So call pager_error() on the way out to make any error persistent.
673207cb560bSdanielk1977   */
6733b22aa4a6Sdan   return pager_error(pPager, rc);
673498808babSdrh }
6735d9b0257aSdrh 
6736d9b0257aSdrh /*
67375e00f6c7Sdrh ** Return TRUE if the database file is opened read-only.  Return FALSE
67385e00f6c7Sdrh ** if the database is (in theory) writable.
67395e00f6c7Sdrh */
sqlite3PagerIsreadonly(Pager * pPager)6740f49661a4Sdrh u8 sqlite3PagerIsreadonly(Pager *pPager){
6741be0072d2Sdrh   return pPager->readOnly;
67425e00f6c7Sdrh }
67435e00f6c7Sdrh 
6744e05b3f8fSdrh #ifdef SQLITE_DEBUG
67455e00f6c7Sdrh /*
674695a0b371Sdrh ** Return the sum of the reference counts for all pages held by pPager.
67470f7eb611Sdrh */
sqlite3PagerRefcount(Pager * pPager)67483b8a05f6Sdanielk1977 int sqlite3PagerRefcount(Pager *pPager){
67498c0a791aSdanielk1977   return sqlite3PcacheRefCount(pPager->pPCache);
67500f7eb611Sdrh }
6751e05b3f8fSdrh #endif
67520f7eb611Sdrh 
675371d5d2cdSdanielk1977 /*
675463da0893Sdrh ** Return the approximate number of bytes of memory currently
675563da0893Sdrh ** used by the pager and its associated cache.
675663da0893Sdrh */
sqlite3PagerMemUsed(Pager * pPager)675763da0893Sdrh int sqlite3PagerMemUsed(Pager *pPager){
6758b01f1389Slarrybr   int perPageSize = pPager->pageSize + pPager->nExtra
6759b01f1389Slarrybr     + (int)(sizeof(PgHdr) + 5*sizeof(void*));
676063da0893Sdrh   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
6761233f816bSdrh            + sqlite3MallocSize(pPager)
67620cf68a9bSdrh            + pPager->pageSize;
676363da0893Sdrh }
676463da0893Sdrh 
676563da0893Sdrh /*
676671d5d2cdSdanielk1977 ** Return the number of references to the specified page.
676771d5d2cdSdanielk1977 */
sqlite3PagerPageRefcount(DbPage * pPage)676871d5d2cdSdanielk1977 int sqlite3PagerPageRefcount(DbPage *pPage){
676971d5d2cdSdanielk1977   return sqlite3PcachePageRefcount(pPage);
677071d5d2cdSdanielk1977 }
677171d5d2cdSdanielk1977 
67720f7eb611Sdrh #ifdef SQLITE_TEST
67730f7eb611Sdrh /*
6774d9b0257aSdrh ** This routine is used for testing and analysis only.
6775d9b0257aSdrh */
sqlite3PagerStats(Pager * pPager)67763b8a05f6Sdanielk1977 int *sqlite3PagerStats(Pager *pPager){
677742741be9Sdanielk1977   static int a[11];
67788c0a791aSdanielk1977   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
67798c0a791aSdanielk1977   a[1] = sqlite3PcachePagecount(pPager->pPCache);
67808c0a791aSdanielk1977   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
6781de1ae34eSdan   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
6782d0864087Sdan   a[4] = pPager->eState;
6783efaaf579Sdanielk1977   a[5] = pPager->errCode;
67849ad3ee40Sdrh   a[6] = pPager->aStat[PAGER_STAT_HIT];
67859ad3ee40Sdrh   a[7] = pPager->aStat[PAGER_STAT_MISS];
67867c4ac0c5Sdrh   a[8] = 0;  /* Used to be pPager->nOvfl */
678742741be9Sdanielk1977   a[9] = pPager->nRead;
67889ad3ee40Sdrh   a[10] = pPager->aStat[PAGER_STAT_WRITE];
6789d9b0257aSdrh   return a;
6790d9b0257aSdrh }
67910410302eSdanielk1977 #endif
67920410302eSdanielk1977 
67930410302eSdanielk1977 /*
6794ffc78a41Sdrh ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
6795ffc78a41Sdrh ** or _WRITE+1.  The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
6796ffc78a41Sdrh ** of SQLITE_DBSTATUS_CACHE_SPILL.  The _SPILL case is not contiguous because
6797ffc78a41Sdrh ** it was added later.
6798ffc78a41Sdrh **
6799ffc78a41Sdrh ** Before returning, *pnVal is incremented by the
680058ca31c9Sdan ** current cache hit or miss count, according to the value of eStat. If the
680158ca31c9Sdan ** reset parameter is non-zero, the cache hit or miss count is zeroed before
680258ca31c9Sdan ** returning.
680358ca31c9Sdan */
sqlite3PagerCacheStat(Pager * pPager,int eStat,int reset,int * pnVal)680458ca31c9Sdan void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
680558ca31c9Sdan 
680658ca31c9Sdan   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
680758ca31c9Sdan        || eStat==SQLITE_DBSTATUS_CACHE_MISS
68089ad3ee40Sdrh        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
6809ffc78a41Sdrh        || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
681058ca31c9Sdan   );
681158ca31c9Sdan 
68129ad3ee40Sdrh   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
68139ad3ee40Sdrh   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
6814ffc78a41Sdrh   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
6815ffc78a41Sdrh            && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
68169ad3ee40Sdrh 
6817ffc78a41Sdrh   eStat -= SQLITE_DBSTATUS_CACHE_HIT;
6818ffc78a41Sdrh   *pnVal += pPager->aStat[eStat];
681958ca31c9Sdan   if( reset ){
6820ffc78a41Sdrh     pPager->aStat[eStat] = 0;
682158ca31c9Sdan   }
682258ca31c9Sdan }
682358ca31c9Sdan 
682458ca31c9Sdan /*
68259131ab93Sdan ** Return true if this is an in-memory or temp-file backed pager.
68260410302eSdanielk1977 */
sqlite3PagerIsMemdb(Pager * pPager)682717b90b53Sdanielk1977 int sqlite3PagerIsMemdb(Pager *pPager){
6828021e228eSdrh   return pPager->tempFile || pPager->memVfs;
682917b90b53Sdanielk1977 }
6830dd79342eSdrh 
6831fa86c412Sdrh /*
6832bea2a948Sdanielk1977 ** Check that there are at least nSavepoint savepoints open. If there are
6833bea2a948Sdanielk1977 ** currently less than nSavepoints open, then open one or more savepoints
6834bea2a948Sdanielk1977 ** to make up the difference. If the number of savepoints is already
6835bea2a948Sdanielk1977 ** equal to nSavepoint, then this function is a no-op.
6836bea2a948Sdanielk1977 **
6837bea2a948Sdanielk1977 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
6838bea2a948Sdanielk1977 ** occurs while opening the sub-journal file, then an IO error code is
6839bea2a948Sdanielk1977 ** returned. Otherwise, SQLITE_OK.
6840fa86c412Sdrh */
pagerOpenSavepoint(Pager * pPager,int nSavepoint)68413169906dSdrh static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
6842bea2a948Sdanielk1977   int rc = SQLITE_OK;                       /* Return code */
6843bea2a948Sdanielk1977   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
68443169906dSdrh   int ii;                                   /* Iterator variable */
68453169906dSdrh   PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
6846fd7f0452Sdanielk1977 
6847de1ae34eSdan   assert( pPager->eState>=PAGER_WRITER_LOCKED );
6848937ac9daSdan   assert( assert_pager_state(pPager) );
68493169906dSdrh   assert( nSavepoint>nCurrent && pPager->useJournal );
6850dd3cd977Sdrh 
6851fd7f0452Sdanielk1977   /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
6852fd7f0452Sdanielk1977   ** if the allocation fails. Otherwise, zero the new portion in case a
6853fd7f0452Sdanielk1977   ** malloc failure occurs while populating it in the for(...) loop below.
6854fd7f0452Sdanielk1977   */
685549b9d338Sdrh   aNew = (PagerSavepoint *)sqlite3Realloc(
6856fd7f0452Sdanielk1977       pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
6857fd7f0452Sdanielk1977   );
6858fd7f0452Sdanielk1977   if( !aNew ){
6859fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
6860fa86c412Sdrh   }
6861bea2a948Sdanielk1977   memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
6862fd7f0452Sdanielk1977   pPager->aSavepoint = aNew;
6863fa86c412Sdrh 
6864fd7f0452Sdanielk1977   /* Populate the PagerSavepoint structures just allocated. */
6865bea2a948Sdanielk1977   for(ii=nCurrent; ii<nSavepoint; ii++){
6866937ac9daSdan     aNew[ii].nOrig = pPager->dbSize;
6867ba726f49Sdrh     if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
686867ddef69Sdanielk1977       aNew[ii].iOffset = pPager->journalOff;
686967ddef69Sdanielk1977     }else{
687067ddef69Sdanielk1977       aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
687167ddef69Sdanielk1977     }
6872bea2a948Sdanielk1977     aNew[ii].iSubRec = pPager->nSubRec;
6873937ac9daSdan     aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
6874f43fef29Sdan     aNew[ii].bTruncateOnRelease = 1;
6875fd7f0452Sdanielk1977     if( !aNew[ii].pInSavepoint ){
6876fad3039cSmistachkin       return SQLITE_NOMEM_BKPT;
6877fa86c412Sdrh     }
68787ed91f23Sdrh     if( pagerUseWal(pPager) ){
687971d89919Sdan       sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
68804cd78b4dSdan     }
68818e64db2bSdan     pPager->nSavepoint = ii+1;
6882fa86c412Sdrh   }
68838e64db2bSdan   assert( pPager->nSavepoint==nSavepoint );
68849f0b6be8Sdanielk1977   assertTruncateConstraint(pPager);
688586f8c197Sdrh   return rc;
688686f8c197Sdrh }
sqlite3PagerOpenSavepoint(Pager * pPager,int nSavepoint)68873169906dSdrh int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
68883169906dSdrh   assert( pPager->eState>=PAGER_WRITER_LOCKED );
68893169906dSdrh   assert( assert_pager_state(pPager) );
68903169906dSdrh 
68913169906dSdrh   if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
68923169906dSdrh     return pagerOpenSavepoint(pPager, nSavepoint);
68933169906dSdrh   }else{
68943169906dSdrh     return SQLITE_OK;
68953169906dSdrh   }
68963169906dSdrh }
68973169906dSdrh 
6898fa86c412Sdrh 
6899fa86c412Sdrh /*
6900bea2a948Sdanielk1977 ** This function is called to rollback or release (commit) a savepoint.
6901bea2a948Sdanielk1977 ** The savepoint to release or rollback need not be the most recently
6902bea2a948Sdanielk1977 ** created savepoint.
6903bea2a948Sdanielk1977 **
6904fd7f0452Sdanielk1977 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
6905fd7f0452Sdanielk1977 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
6906fd7f0452Sdanielk1977 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
6907be217793Sshane ** that have occurred since the specified savepoint was created.
6908fd7f0452Sdanielk1977 **
6909bea2a948Sdanielk1977 ** The savepoint to rollback or release is identified by parameter
6910bea2a948Sdanielk1977 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
6911bea2a948Sdanielk1977 ** (the first created). A value of (Pager.nSavepoint-1) means operate
6912bea2a948Sdanielk1977 ** on the most recently created savepoint. If iSavepoint is greater than
6913bea2a948Sdanielk1977 ** (Pager.nSavepoint-1), then this function is a no-op.
6914fd7f0452Sdanielk1977 **
6915bea2a948Sdanielk1977 ** If a negative value is passed to this function, then the current
6916bea2a948Sdanielk1977 ** transaction is rolled back. This is different to calling
6917bea2a948Sdanielk1977 ** sqlite3PagerRollback() because this function does not terminate
6918bea2a948Sdanielk1977 ** the transaction or unlock the database, it just restores the
6919bea2a948Sdanielk1977 ** contents of the database to its original state.
6920bea2a948Sdanielk1977 **
6921bea2a948Sdanielk1977 ** In any case, all savepoints with an index greater than iSavepoint
6922bea2a948Sdanielk1977 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
6923bea2a948Sdanielk1977 ** then savepoint iSavepoint is also destroyed.
6924bea2a948Sdanielk1977 **
6925bea2a948Sdanielk1977 ** This function may return SQLITE_NOMEM if a memory allocation fails,
6926bea2a948Sdanielk1977 ** or an IO error code if an IO error occurs while rolling back a
6927bea2a948Sdanielk1977 ** savepoint. If no errors occur, SQLITE_OK is returned.
6928fa86c412Sdrh */
sqlite3PagerSavepoint(Pager * pPager,int op,int iSavepoint)6929fd7f0452Sdanielk1977 int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
6930d0d49b9cSdan   int rc = pPager->errCode;
6931d0d49b9cSdan 
6932d0d49b9cSdan #ifdef SQLITE_ENABLE_ZIPVFS
6933d0d49b9cSdan   if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
6934d0d49b9cSdan #endif
6935fd7f0452Sdanielk1977 
6936fd7f0452Sdanielk1977   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
6937bea2a948Sdanielk1977   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
6938fd7f0452Sdanielk1977 
69394e004aa6Sdan   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
6940bea2a948Sdanielk1977     int ii;            /* Iterator variable */
6941bea2a948Sdanielk1977     int nNew;          /* Number of remaining savepoints after this op. */
6942bea2a948Sdanielk1977 
6943bea2a948Sdanielk1977     /* Figure out how many savepoints will still be active after this
6944bea2a948Sdanielk1977     ** operation. Store this value in nNew. Then free resources associated
6945bea2a948Sdanielk1977     ** with any savepoints that are destroyed by this operation.
6946bea2a948Sdanielk1977     */
69476885de36Sshaneh     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
6948fd7f0452Sdanielk1977     for(ii=nNew; ii<pPager->nSavepoint; ii++){
6949fd7f0452Sdanielk1977       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
6950b3175389Sdanielk1977     }
6951fd7f0452Sdanielk1977     pPager->nSavepoint = nNew;
6952fd7f0452Sdanielk1977 
695357dd7e6aSdrh     /* Truncate the sub-journal so that it only includes the parts
695457dd7e6aSdrh     ** that are still in use. */
69556885de36Sshaneh     if( op==SAVEPOINT_RELEASE ){
6956f43fef29Sdan       PagerSavepoint *pRel = &pPager->aSavepoint[nNew];
6957f43fef29Sdan       if( pRel->bTruncateOnRelease && isOpen(pPager->sjfd) ){
69586885de36Sshaneh         /* Only truncate if it is an in-memory sub-journal. */
69592491de28Sdan         if( sqlite3JournalIsInMemory(pPager->sjfd) ){
696057dd7e6aSdrh           i64 sz = (pPager->pageSize+4)*(i64)pRel->iSubRec;
6961f43fef29Sdan           rc = sqlite3OsTruncate(pPager->sjfd, sz);
69623517324dSdrh           assert( rc==SQLITE_OK );
69636885de36Sshaneh         }
6964f43fef29Sdan         pPager->nSubRec = pRel->iSubRec;
69656885de36Sshaneh       }
69666885de36Sshaneh     }
69676885de36Sshaneh     /* Else this is a rollback operation, playback the specified savepoint.
6968bea2a948Sdanielk1977     ** If this is a temp-file, it is possible that the journal file has
6969bea2a948Sdanielk1977     ** not yet been opened. In this case there have been no changes to
6970bea2a948Sdanielk1977     ** the database file, so the playback operation can be skipped.
6971bea2a948Sdanielk1977     */
69727ed91f23Sdrh     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
6973fd7f0452Sdanielk1977       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
6974fd7f0452Sdanielk1977       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
6975fd7f0452Sdanielk1977       assert(rc!=SQLITE_DONE);
6976fa86c412Sdrh     }
6977d0d49b9cSdan 
6978d0d49b9cSdan #ifdef SQLITE_ENABLE_ZIPVFS
6979d0d49b9cSdan     /* If the cache has been modified but the savepoint cannot be rolled
6980d0d49b9cSdan     ** back journal_mode=off, put the pager in the error state. This way,
6981d0d49b9cSdan     ** if the VFS used by this pager includes ZipVFS, the entire transaction
6982d0d49b9cSdan     ** can be rolled back at the ZipVFS level.  */
6983d0d49b9cSdan     else if(
6984d0d49b9cSdan         pPager->journalMode==PAGER_JOURNALMODE_OFF
6985d0d49b9cSdan      && pPager->eState>=PAGER_WRITER_CACHEMOD
6986d0d49b9cSdan     ){
6987d0d49b9cSdan       pPager->errCode = SQLITE_ABORT;
6988d0d49b9cSdan       pPager->eState = PAGER_ERROR;
6989fc4111f7Sdrh       setGetterMethod(pPager);
6990d0d49b9cSdan     }
6991d0d49b9cSdan #endif
6992fd7f0452Sdanielk1977   }
69934e004aa6Sdan 
6994fa86c412Sdrh   return rc;
6995fa86c412Sdrh }
6996fa86c412Sdrh 
699773509eeeSdrh /*
699873509eeeSdrh ** Return the full pathname of the database file.
6999d4e0bb0eSdrh **
7000d4e0bb0eSdrh ** Except, if the pager is in-memory only, then return an empty string if
7001d4e0bb0eSdrh ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
7002d4e0bb0eSdrh ** used to report the filename to the user, for compatibility with legacy
7003d4e0bb0eSdrh ** behavior.  But when the Btree needs to know the filename for matching to
7004d4e0bb0eSdrh ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
7005d4e0bb0eSdrh ** participate in shared-cache.
70068080403eSdrh **
70078080403eSdrh ** The return value to this routine is always safe to use with
70088080403eSdrh ** sqlite3_uri_parameter() and sqlite3_filename_database() and friends.
700973509eeeSdrh */
sqlite3PagerFilename(const Pager * pPager,int nullIfMemDb)70108875b9e7Sdrh const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){
7011be284e4eSdrh   static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
7012532b0d23Sdrh   return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename;
70138875b9e7Sdrh }
70148875b9e7Sdrh 
70158875b9e7Sdrh /*
7016d0679edcSdrh ** Return the VFS structure for the pager.
7017d0679edcSdrh */
sqlite3PagerVfs(Pager * pPager)7018790f287cSdrh sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
7019d0679edcSdrh   return pPager->pVfs;
7020d0679edcSdrh }
7021d0679edcSdrh 
7022d0679edcSdrh /*
7023cc6bb3eaSdrh ** Return the file handle for the database file associated
7024cc6bb3eaSdrh ** with the pager.  This might return NULL if the file has
7025cc6bb3eaSdrh ** not yet been opened.
7026cc6bb3eaSdrh */
sqlite3PagerFile(Pager * pPager)7027cc6bb3eaSdrh sqlite3_file *sqlite3PagerFile(Pager *pPager){
7028cc6bb3eaSdrh   return pPager->fd;
7029cc6bb3eaSdrh }
7030cc6bb3eaSdrh 
7031cc6bb3eaSdrh /*
703221d61853Sdrh ** Return the file handle for the journal file (if it exists).
703321d61853Sdrh ** This will be either the rollback journal or the WAL file.
703421d61853Sdrh */
sqlite3PagerJrnlFile(Pager * pPager)703521d61853Sdrh sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
7036b4acd6a8Sdrh #if SQLITE_OMIT_WAL
7037b4acd6a8Sdrh   return pPager->jfd;
7038b4acd6a8Sdrh #else
703921d61853Sdrh   return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
7040b4acd6a8Sdrh #endif
704121d61853Sdrh }
704221d61853Sdrh 
704321d61853Sdrh /*
70445865e3d5Sdanielk1977 ** Return the full pathname of the journal file.
70455865e3d5Sdanielk1977 */
sqlite3PagerJournalname(Pager * pPager)70463b8a05f6Sdanielk1977 const char *sqlite3PagerJournalname(Pager *pPager){
70475865e3d5Sdanielk1977   return pPager->zJournal;
70485865e3d5Sdanielk1977 }
70495865e3d5Sdanielk1977 
7050687566d7Sdanielk1977 #ifndef SQLITE_OMIT_AUTOVACUUM
7051687566d7Sdanielk1977 /*
70525e385311Sdrh ** Move the page pPg to location pgno in the file.
7053687566d7Sdanielk1977 **
70545e385311Sdrh ** There must be no references to the page previously located at
70555e385311Sdrh ** pgno (which we call pPgOld) though that page is allowed to be
7056b3df2e1cSdrh ** in cache.  If the page previously located at pgno is not already
70575e385311Sdrh ** in the rollback journal, it is not put there by by this routine.
7058687566d7Sdanielk1977 **
70595e385311Sdrh ** References to the page pPg remain valid. Updating any
70605e385311Sdrh ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
7061687566d7Sdanielk1977 ** allocated along with the page) is the responsibility of the caller.
7062687566d7Sdanielk1977 **
70635fd057afSdanielk1977 ** A transaction must be active when this routine is called. It used to be
70645fd057afSdanielk1977 ** required that a statement transaction was not active, but this restriction
70655fd057afSdanielk1977 ** has been removed (CREATE INDEX needs to move a page when a statement
70665fd057afSdanielk1977 ** transaction is active).
70674c999999Sdanielk1977 **
70684c999999Sdanielk1977 ** If the fourth argument, isCommit, is non-zero, then this page is being
70694c999999Sdanielk1977 ** moved as part of a database reorganization just before the transaction
70704c999999Sdanielk1977 ** is being committed. In this case, it is guaranteed that the database page
70714c999999Sdanielk1977 ** pPg refers to will not be written to again within this transaction.
7072bea2a948Sdanielk1977 **
7073bea2a948Sdanielk1977 ** This function may return SQLITE_NOMEM or an IO error code if an error
7074bea2a948Sdanielk1977 ** occurs. Otherwise, it returns SQLITE_OK.
7075687566d7Sdanielk1977 */
sqlite3PagerMovepage(Pager * pPager,DbPage * pPg,Pgno pgno,int isCommit)70764c999999Sdanielk1977 int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
70775e385311Sdrh   PgHdr *pPgOld;               /* The page being overwritten. */
7078bea2a948Sdanielk1977   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
7079bea2a948Sdanielk1977   int rc;                      /* Return code */
708086655a1dSdrh   Pgno origPgno;               /* The original page number */
7081687566d7Sdanielk1977 
7082687566d7Sdanielk1977   assert( pPg->nRef>0 );
7083d0864087Sdan   assert( pPager->eState==PAGER_WRITER_CACHEMOD
7084d0864087Sdan        || pPager->eState==PAGER_WRITER_DBMOD
7085d0864087Sdan   );
7086d0864087Sdan   assert( assert_pager_state(pPager) );
7087687566d7Sdanielk1977 
70888c30f72dSdrh   /* In order to be able to rollback, an in-memory database must journal
70898c30f72dSdrh   ** the page we are moving from.
70908c30f72dSdrh   */
7091d22f5099Sdrh   assert( pPager->tempFile || !MEMDB );
7092d87efd72Sdan   if( pPager->tempFile ){
70938c30f72dSdrh     rc = sqlite3PagerWrite(pPg);
70948c30f72dSdrh     if( rc ) return rc;
70958c30f72dSdrh   }
70968c30f72dSdrh 
70971fab7b66Sdanielk1977   /* If the page being moved is dirty and has not been saved by the latest
70981fab7b66Sdanielk1977   ** savepoint, then save the current contents of the page into the
70991fab7b66Sdanielk1977   ** sub-journal now. This is required to handle the following scenario:
71001fab7b66Sdanielk1977   **
71011fab7b66Sdanielk1977   **   BEGIN;
71021fab7b66Sdanielk1977   **     <journal page X, then modify it in memory>
71031fab7b66Sdanielk1977   **     SAVEPOINT one;
71041fab7b66Sdanielk1977   **       <Move page X to location Y>
71051fab7b66Sdanielk1977   **     ROLLBACK TO one;
71061fab7b66Sdanielk1977   **
71071fab7b66Sdanielk1977   ** If page X were not written to the sub-journal here, it would not
71081fab7b66Sdanielk1977   ** be possible to restore its contents when the "ROLLBACK TO one"
7109bea2a948Sdanielk1977   ** statement were is processed.
7110bea2a948Sdanielk1977   **
7111bea2a948Sdanielk1977   ** subjournalPage() may need to allocate space to store pPg->pgno into
7112bea2a948Sdanielk1977   ** one or more savepoint bitvecs. This is the reason this function
7113bea2a948Sdanielk1977   ** may return SQLITE_NOMEM.
71141fab7b66Sdanielk1977   */
711560e32edbSdrh   if( (pPg->flags & PGHDR_DIRTY)!=0
711660e32edbSdrh    && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
71171fab7b66Sdanielk1977   ){
71181fab7b66Sdanielk1977     return rc;
71191fab7b66Sdanielk1977   }
71201fab7b66Sdanielk1977 
712130d53701Sdrh   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
712230d53701Sdrh       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
7123b0603416Sdrh   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
7124ef73ee9aSdanielk1977 
71254c999999Sdanielk1977   /* If the journal needs to be sync()ed before page pPg->pgno can
71264c999999Sdanielk1977   ** be written to, store pPg->pgno in local variable needSyncPgno.
71274c999999Sdanielk1977   **
71284c999999Sdanielk1977   ** If the isCommit flag is set, there is no need to remember that
71294c999999Sdanielk1977   ** the journal needs to be sync()ed before database page pPg->pgno
71304c999999Sdanielk1977   ** can be written to. The caller has already promised not to write to it.
71314c999999Sdanielk1977   */
71327f8def28Sdan   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
713394daf7fdSdanielk1977     needSyncPgno = pPg->pgno;
71346ffb4975Sdrh     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
71355dee6afcSdrh             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
71368c0a791aSdanielk1977     assert( pPg->flags&PGHDR_DIRTY );
713794daf7fdSdanielk1977   }
713894daf7fdSdanielk1977 
7139ef73ee9aSdanielk1977   /* If the cache contains a page with page-number pgno, remove it
714051133eaeSdan   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
7141599fcbaeSdanielk1977   ** page pgno before the 'move' operation, it needs to be retained
7142599fcbaeSdanielk1977   ** for the page moved there.
7143f5fdda82Sdanielk1977   */
7144bc2ca9ebSdanielk1977   pPg->flags &= ~PGHDR_NEED_SYNC;
7145c137807aSdrh   pPgOld = sqlite3PagerLookup(pPager, pgno);
7146aff0fd48Sdrh   assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
71476e2ef431Sdrh   if( pPgOld ){
7148da125367Sdrh     if( NEVER(pPgOld->nRef>1) ){
7149aff0fd48Sdrh       sqlite3PagerUnrefNotNull(pPgOld);
7150aff0fd48Sdrh       return SQLITE_CORRUPT_BKPT;
7151aff0fd48Sdrh     }
71528c0a791aSdanielk1977     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
7153d87efd72Sdan     if( pPager->tempFile ){
715498829a65Sdrh       /* Do not discard pages from an in-memory database since we might
715598829a65Sdrh       ** need to rollback later.  Just move the page out of the way. */
715698829a65Sdrh       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
715798829a65Sdrh     }else{
7158be20e8ecSdanielk1977       sqlite3PcacheDrop(pPgOld);
7159ef73ee9aSdanielk1977     }
716098829a65Sdrh   }
7161687566d7Sdanielk1977 
716286655a1dSdrh   origPgno = pPg->pgno;
71638c0a791aSdanielk1977   sqlite3PcacheMove(pPg, pgno);
7164c047b9f7Sdrh   sqlite3PcacheMakeDirty(pPg);
7165687566d7Sdanielk1977 
71664e004aa6Sdan   /* For an in-memory database, make sure the original page continues
71674e004aa6Sdan   ** to exist, in case the transaction needs to roll back.  Use pPgOld
71684e004aa6Sdan   ** as the original page since it has already been allocated.
71694e004aa6Sdan   */
7170d12bc602Sdrh   if( pPager->tempFile && pPgOld ){
71714e004aa6Sdan     sqlite3PcacheMove(pPgOld, origPgno);
7172da8a330aSdrh     sqlite3PagerUnrefNotNull(pPgOld);
71734e004aa6Sdan   }
71744e004aa6Sdan 
717594daf7fdSdanielk1977   if( needSyncPgno ){
717694daf7fdSdanielk1977     /* If needSyncPgno is non-zero, then the journal file needs to be
717794daf7fdSdanielk1977     ** sync()ed before any data is written to database file page needSyncPgno.
717894daf7fdSdanielk1977     ** Currently, no such page exists in the page-cache and the
71794c999999Sdanielk1977     ** "is journaled" bitvec flag has been set. This needs to be remedied by
718051133eaeSdan     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
71814c999999Sdanielk1977     ** flag.
7182ae82558bSdanielk1977     **
7183a98d7b47Sdanielk1977     ** If the attempt to load the page into the page-cache fails, (due
7184f5e7bb51Sdrh     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
7185a98d7b47Sdanielk1977     ** array. Otherwise, if the page is loaded and written again in
7186a98d7b47Sdanielk1977     ** this transaction, it may be written to the database file before
7187a98d7b47Sdanielk1977     ** it is synced into the journal file. This way, it may end up in
7188a98d7b47Sdanielk1977     ** the journal file twice, but that is not a problem.
718994daf7fdSdanielk1977     */
71903b8a05f6Sdanielk1977     PgHdr *pPgHdr;
71919584f58cSdrh     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
719287c29a94Sdanielk1977     if( rc!=SQLITE_OK ){
71936aac11dcSdrh       if( needSyncPgno<=pPager->dbOrigSize ){
7194e98c9049Sdrh         assert( pPager->pTmpSpace!=0 );
7195e98c9049Sdrh         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
7196a98d7b47Sdanielk1977       }
719787c29a94Sdanielk1977       return rc;
719887c29a94Sdanielk1977     }
71998c0a791aSdanielk1977     pPgHdr->flags |= PGHDR_NEED_SYNC;
7200c047b9f7Sdrh     sqlite3PcacheMakeDirty(pPgHdr);
7201da8a330aSdrh     sqlite3PagerUnrefNotNull(pPgHdr);
720294daf7fdSdanielk1977   }
720394daf7fdSdanielk1977 
7204687566d7Sdanielk1977   return SQLITE_OK;
7205687566d7Sdanielk1977 }
7206e6593d8eSdan #endif
720733ea4866Sdan 
7208e6593d8eSdan /*
7209e6593d8eSdan ** The page handle passed as the first argument refers to a dirty page
7210e6593d8eSdan ** with a page number other than iNew. This function changes the page's
7211e6593d8eSdan ** page number to iNew and sets the value of the PgHdr.flags field to
7212e6593d8eSdan ** the value passed as the third parameter.
7213e6593d8eSdan */
sqlite3PagerRekey(DbPage * pPg,Pgno iNew,u16 flags)721431f4e99dSdan void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
7215e6593d8eSdan   assert( pPg->pgno!=iNew );
7216e6593d8eSdan   pPg->flags = flags;
721733ea4866Sdan   sqlite3PcacheMove(pPg, iNew);
721833ea4866Sdan }
721933ea4866Sdan 
72203b8a05f6Sdanielk1977 /*
72213b8a05f6Sdanielk1977 ** Return a pointer to the data for the specified page.
72223b8a05f6Sdanielk1977 */
sqlite3PagerGetData(DbPage * pPg)72233b8a05f6Sdanielk1977 void *sqlite3PagerGetData(DbPage *pPg){
722471d5d2cdSdanielk1977   assert( pPg->nRef>0 || pPg->pPager->memDb );
72258c0a791aSdanielk1977   return pPg->pData;
72263b8a05f6Sdanielk1977 }
72273b8a05f6Sdanielk1977 
72283b8a05f6Sdanielk1977 /*
72293b8a05f6Sdanielk1977 ** Return a pointer to the Pager.nExtra bytes of "extra" space
72303b8a05f6Sdanielk1977 ** allocated along with the specified page.
72313b8a05f6Sdanielk1977 */
sqlite3PagerGetExtra(DbPage * pPg)72323b8a05f6Sdanielk1977 void *sqlite3PagerGetExtra(DbPage *pPg){
72336aac11dcSdrh   return pPg->pExtra;
72343b8a05f6Sdanielk1977 }
72353b8a05f6Sdanielk1977 
723641483468Sdanielk1977 /*
723741483468Sdanielk1977 ** Get/set the locking-mode for this pager. Parameter eMode must be one
723841483468Sdanielk1977 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
723941483468Sdanielk1977 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
724041483468Sdanielk1977 ** the locking-mode is set to the value specified.
724141483468Sdanielk1977 **
724241483468Sdanielk1977 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
724341483468Sdanielk1977 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
724441483468Sdanielk1977 ** locking-mode.
724541483468Sdanielk1977 */
sqlite3PagerLockingMode(Pager * pPager,int eMode)724641483468Sdanielk1977 int sqlite3PagerLockingMode(Pager *pPager, int eMode){
7247369339dbSdrh   assert( eMode==PAGER_LOCKINGMODE_QUERY
7248369339dbSdrh             || eMode==PAGER_LOCKINGMODE_NORMAL
7249369339dbSdrh             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
7250369339dbSdrh   assert( PAGER_LOCKINGMODE_QUERY<0 );
7251369339dbSdrh   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
72528c408004Sdan   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
72538c408004Sdan   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
72541bd10f8aSdrh     pPager->exclusiveMode = (u8)eMode;
725541483468Sdanielk1977   }
725641483468Sdanielk1977   return (int)pPager->exclusiveMode;
725741483468Sdanielk1977 }
725841483468Sdanielk1977 
72593b02013eSdrh /*
72600b9b4301Sdrh ** Set the journal-mode for this pager. Parameter eMode must be one of:
72613b02013eSdrh **
726204335886Sdrh **    PAGER_JOURNALMODE_DELETE
726304335886Sdrh **    PAGER_JOURNALMODE_TRUNCATE
726404335886Sdrh **    PAGER_JOURNALMODE_PERSIST
726504335886Sdrh **    PAGER_JOURNALMODE_OFF
7266bea2a948Sdanielk1977 **    PAGER_JOURNALMODE_MEMORY
72677c24610eSdan **    PAGER_JOURNALMODE_WAL
726804335886Sdrh **
72690b9b4301Sdrh ** The journalmode is set to the value specified if the change is allowed.
72700b9b4301Sdrh ** The change may be disallowed for the following reasons:
72718a939190Sdrh **
72728a939190Sdrh **   *  An in-memory database can only have its journal_mode set to _OFF
72738a939190Sdrh **      or _MEMORY.
72748a939190Sdrh **
72750b9b4301Sdrh **   *  Temporary databases cannot have _WAL journalmode.
727604335886Sdrh **
7277bea2a948Sdanielk1977 ** The returned indicate the current (possibly updated) journal-mode.
72783b02013eSdrh */
sqlite3PagerSetJournalMode(Pager * pPager,int eMode)72790b9b4301Sdrh int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
72800b9b4301Sdrh   u8 eOld = pPager->journalMode;    /* Prior journalmode */
72810b9b4301Sdrh 
72820b9b4301Sdrh   /* The eMode parameter is always valid */
7283d0fa3484Sdrh   assert(      eMode==PAGER_JOURNALMODE_DELETE    /* 0 */
7284d0fa3484Sdrh             || eMode==PAGER_JOURNALMODE_PERSIST   /* 1 */
7285d0fa3484Sdrh             || eMode==PAGER_JOURNALMODE_OFF       /* 2 */
7286d0fa3484Sdrh             || eMode==PAGER_JOURNALMODE_TRUNCATE  /* 3 */
7287d0fa3484Sdrh             || eMode==PAGER_JOURNALMODE_MEMORY    /* 4 */
7288d0fa3484Sdrh             || eMode==PAGER_JOURNALMODE_WAL       /* 5 */ );
7289e04dc88bSdan 
7290a485cccdSdrh   /* This routine is only called from the OP_JournalMode opcode, and
7291a485cccdSdrh   ** the logic there will never allow a temporary file to be changed
7292a485cccdSdrh   ** to WAL mode.
72930b9b4301Sdrh   */
7294a485cccdSdrh   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
72950b9b4301Sdrh 
72960b9b4301Sdrh   /* Do allow the journalmode of an in-memory database to be set to
72970b9b4301Sdrh   ** anything other than MEMORY or OFF
72980b9b4301Sdrh   */
72990b9b4301Sdrh   if( MEMDB ){
73000b9b4301Sdrh     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
73010b9b4301Sdrh     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
73020b9b4301Sdrh       eMode = eOld;
73030b9b4301Sdrh     }
73040b9b4301Sdrh   }
73050b9b4301Sdrh 
73060b9b4301Sdrh   if( eMode!=eOld ){
73070b9b4301Sdrh 
73080b9b4301Sdrh     /* Change the journal mode. */
7309e5953ccdSdan     assert( pPager->eState!=PAGER_ERROR );
73100b9b4301Sdrh     pPager->journalMode = (u8)eMode;
7311731bf5bcSdan 
7312731bf5bcSdan     /* When transistioning from TRUNCATE or PERSIST to any other journal
7313e5953ccdSdan     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
7314731bf5bcSdan     ** delete the journal file.
7315731bf5bcSdan     */
7316731bf5bcSdan     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
7317731bf5bcSdan     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
7318731bf5bcSdan     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
7319731bf5bcSdan     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
7320731bf5bcSdan     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
7321731bf5bcSdan     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
7322731bf5bcSdan 
7323731bf5bcSdan     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
7324731bf5bcSdan     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
7325731bf5bcSdan       /* In this case we would like to delete the journal file. If it is
7326731bf5bcSdan       ** not possible, then that is not a problem. Deleting the journal file
7327731bf5bcSdan       ** here is an optimization only.
7328731bf5bcSdan       **
7329731bf5bcSdan       ** Before deleting the journal file, obtain a RESERVED lock on the
7330731bf5bcSdan       ** database file. This ensures that the journal file is not deleted
7331731bf5bcSdan       ** while it is in use by some other client.
7332731bf5bcSdan       */
7333e5953ccdSdan       sqlite3OsClose(pPager->jfd);
7334e5953ccdSdan       if( pPager->eLock>=RESERVED_LOCK ){
7335e5953ccdSdan         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
7336e5953ccdSdan       }else{
7337731bf5bcSdan         int rc = SQLITE_OK;
7338d0864087Sdan         int state = pPager->eState;
73395653e4daSdan         assert( state==PAGER_OPEN || state==PAGER_READER );
7340de1ae34eSdan         if( state==PAGER_OPEN ){
7341731bf5bcSdan           rc = sqlite3PagerSharedLock(pPager);
7342731bf5bcSdan         }
7343d0864087Sdan         if( pPager->eState==PAGER_READER ){
7344731bf5bcSdan           assert( rc==SQLITE_OK );
73454e004aa6Sdan           rc = pagerLockDb(pPager, RESERVED_LOCK);
7346731bf5bcSdan         }
73478119aab3Sdrh         if( rc==SQLITE_OK ){
7348731bf5bcSdan           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
7349731bf5bcSdan         }
7350d0864087Sdan         if( rc==SQLITE_OK && state==PAGER_READER ){
73514e004aa6Sdan           pagerUnlockDb(pPager, SHARED_LOCK);
7352de1ae34eSdan         }else if( state==PAGER_OPEN ){
7353731bf5bcSdan           pager_unlock(pPager);
7354731bf5bcSdan         }
7355d0864087Sdan         assert( state==pPager->eState );
7356731bf5bcSdan       }
7357929b9233Sdan     }else if( eMode==PAGER_JOURNALMODE_OFF ){
7358929b9233Sdan       sqlite3OsClose(pPager->jfd);
7359b3175389Sdanielk1977     }
7360e5953ccdSdan   }
73610b9b4301Sdrh 
73620b9b4301Sdrh   /* Return the new journal mode */
7363fdc40e91Sdrh   return (int)pPager->journalMode;
73643b02013eSdrh }
73653b02013eSdrh 
7366b53e4960Sdanielk1977 /*
73670b9b4301Sdrh ** Return the current journal mode.
73680b9b4301Sdrh */
sqlite3PagerGetJournalMode(Pager * pPager)73690b9b4301Sdrh int sqlite3PagerGetJournalMode(Pager *pPager){
73700b9b4301Sdrh   return (int)pPager->journalMode;
73710b9b4301Sdrh }
73720b9b4301Sdrh 
73730b9b4301Sdrh /*
73740b9b4301Sdrh ** Return TRUE if the pager is in a state where it is OK to change the
73750b9b4301Sdrh ** journalmode.  Journalmode changes can only happen when the database
73760b9b4301Sdrh ** is unmodified.
73770b9b4301Sdrh */
sqlite3PagerOkToChangeJournalMode(Pager * pPager)73780b9b4301Sdrh int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
73794e004aa6Sdan   assert( assert_pager_state(pPager) );
7380d0864087Sdan   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
738189ccf448Sdan   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
73820b9b4301Sdrh   return 1;
73830b9b4301Sdrh }
73840b9b4301Sdrh 
73850b9b4301Sdrh /*
7386b53e4960Sdanielk1977 ** Get/set the size-limit used for persistent journal files.
73875d73854bSdrh **
73885d73854bSdrh ** Setting the size limit to -1 means no limit is enforced.
73895d73854bSdrh ** An attempt to set a limit smaller than -1 is a no-op.
7390b53e4960Sdanielk1977 */
sqlite3PagerJournalSizeLimit(Pager * pPager,i64 iLimit)7391b53e4960Sdanielk1977 i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
7392b53e4960Sdanielk1977   if( iLimit>=-1 ){
7393b53e4960Sdanielk1977     pPager->journalSizeLimit = iLimit;
739485a83755Sdrh     sqlite3WalLimit(pPager->pWal, iLimit);
7395b53e4960Sdanielk1977   }
7396b53e4960Sdanielk1977   return pPager->journalSizeLimit;
7397b53e4960Sdanielk1977 }
7398b53e4960Sdanielk1977 
73990410302eSdanielk1977 /*
74000410302eSdanielk1977 ** Return a pointer to the pPager->pBackup variable. The backup module
74010410302eSdanielk1977 ** in backup.c maintains the content of this variable. This module
74020410302eSdanielk1977 ** uses it opaquely as an argument to sqlite3BackupRestart() and
74030410302eSdanielk1977 ** sqlite3BackupUpdate() only.
74040410302eSdanielk1977 */
sqlite3PagerBackupPtr(Pager * pPager)74050410302eSdanielk1977 sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
74060410302eSdanielk1977   return &pPager->pBackup;
74070410302eSdanielk1977 }
74080410302eSdanielk1977 
740943c1ce39Sdan #ifndef SQLITE_OMIT_VACUUM
741043c1ce39Sdan /*
741143c1ce39Sdan ** Unless this is an in-memory or temporary database, clear the pager cache.
741243c1ce39Sdan */
sqlite3PagerClearCache(Pager * pPager)741343c1ce39Sdan void sqlite3PagerClearCache(Pager *pPager){
741443c1ce39Sdan   assert( MEMDB==0 || pPager->tempFile );
741543c1ce39Sdan   if( pPager->tempFile==0 ) pager_reset(pPager);
741643c1ce39Sdan }
741743c1ce39Sdan #endif
741843c1ce39Sdan 
741943c1ce39Sdan 
74205cf53537Sdan #ifndef SQLITE_OMIT_WAL
74217c24610eSdan /*
7422a58f26f9Sdan ** This function is called when the user invokes "PRAGMA wal_checkpoint",
7423a58f26f9Sdan ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
7424a58f26f9Sdan ** or wal_blocking_checkpoint() API functions.
7425a58f26f9Sdan **
7426cdc1f049Sdan ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
74277c24610eSdan */
sqlite3PagerCheckpoint(Pager * pPager,sqlite3 * db,int eMode,int * pnLog,int * pnCkpt)74287fb89906Sdan int sqlite3PagerCheckpoint(
74297fb89906Sdan   Pager *pPager,                  /* Checkpoint on this pager */
74307fb89906Sdan   sqlite3 *db,                    /* Db handle used to check for interrupts */
74317fb89906Sdan   int eMode,                      /* Type of checkpoint */
74327fb89906Sdan   int *pnLog,                     /* OUT: Final number of frames in log */
74337fb89906Sdan   int *pnCkpt                     /* OUT: Final number of checkpointed frames */
74347fb89906Sdan ){
74357c24610eSdan   int rc = SQLITE_OK;
7436e2adc0eeSdrh   if( pPager->pWal==0 && pPager->journalMode==PAGER_JOURNALMODE_WAL ){
7437e2adc0eeSdrh     /* This only happens when a database file is zero bytes in size opened and
7438e2adc0eeSdrh     ** then "PRAGMA journal_mode=WAL" is run and then sqlite3_wal_checkpoint()
7439e2adc0eeSdrh     ** is invoked without any intervening transactions.  We need to start
7440e2adc0eeSdrh     ** a transaction to initialize pWal.  The PRAGMA table_list statement is
7441e2adc0eeSdrh     ** used for this since it starts transactions on every database file,
7442e2adc0eeSdrh     ** including all ATTACHed databases.  This seems expensive for a single
7443e2adc0eeSdrh     ** sqlite3_wal_checkpoint() call, but it happens very rarely.
7444e2adc0eeSdrh     ** https://sqlite.org/forum/forumpost/fd0f19d229156939
7445e2adc0eeSdrh     */
7446e2adc0eeSdrh     sqlite3_exec(db, "PRAGMA table_list",0,0,0);
7447e2adc0eeSdrh   }
74487ed91f23Sdrh   if( pPager->pWal ){
74497fb89906Sdan     rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
7450dd90d7eeSdrh         (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
7451dd90d7eeSdrh         pPager->pBusyHandlerArg,
7452daaae7b9Sdrh         pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
7453cdc1f049Sdan         pnLog, pnCkpt
745464d039e5Sdan     );
74557c24610eSdan   }
74567c24610eSdan   return rc;
74577c24610eSdan }
74587c24610eSdan 
sqlite3PagerWalCallback(Pager * pPager)74597ed91f23Sdrh int sqlite3PagerWalCallback(Pager *pPager){
74607ed91f23Sdrh   return sqlite3WalCallback(pPager->pWal);
74618d22a174Sdan }
74628d22a174Sdan 
7463e04dc88bSdan /*
7464d9e5c4f6Sdrh ** Return true if the underlying VFS for the given pager supports the
7465d9e5c4f6Sdrh ** primitives necessary for write-ahead logging.
7466d9e5c4f6Sdrh */
sqlite3PagerWalSupported(Pager * pPager)7467d9e5c4f6Sdrh int sqlite3PagerWalSupported(Pager *pPager){
7468d9e5c4f6Sdrh   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
7469ffbb02a3Sdrh   if( pPager->noLock ) return 0;
7470d4e0bb0eSdrh   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
7471d9e5c4f6Sdrh }
7472d9e5c4f6Sdrh 
7473d9e5c4f6Sdrh /*
74748c408004Sdan ** Attempt to take an exclusive lock on the database file. If a PENDING lock
74758c408004Sdan ** is obtained instead, immediately release it.
74768c408004Sdan */
pagerExclusiveLock(Pager * pPager)74778c408004Sdan static int pagerExclusiveLock(Pager *pPager){
74788c408004Sdan   int rc;                         /* Return code */
74798c408004Sdan 
74808c408004Sdan   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
74818c408004Sdan   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
74828c408004Sdan   if( rc!=SQLITE_OK ){
74837f0857c4Sdrh     /* If the attempt to grab the exclusive lock failed, release the
74847f0857c4Sdrh     ** pending lock that may have been obtained instead.  */
74858c408004Sdan     pagerUnlockDb(pPager, SHARED_LOCK);
74868c408004Sdan   }
74878c408004Sdan 
74888c408004Sdan   return rc;
74898c408004Sdan }
74908c408004Sdan 
74918c408004Sdan /*
74928c408004Sdan ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
74938c408004Sdan ** exclusive-locking mode when this function is called, take an EXCLUSIVE
74948c408004Sdan ** lock on the database file and use heap-memory to store the wal-index
74958c408004Sdan ** in. Otherwise, use the normal shared-memory.
74968c408004Sdan */
pagerOpenWal(Pager * pPager)74978c408004Sdan static int pagerOpenWal(Pager *pPager){
74988c408004Sdan   int rc = SQLITE_OK;
74998c408004Sdan 
75008c408004Sdan   assert( pPager->pWal==0 && pPager->tempFile==0 );
750133f111dcSdrh   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
75028c408004Sdan 
75038c408004Sdan   /* If the pager is already in exclusive-mode, the WAL module will use
75048c408004Sdan   ** heap-memory for the wal-index instead of the VFS shared-memory
75058c408004Sdan   ** implementation. Take the exclusive lock now, before opening the WAL
75068c408004Sdan   ** file, to make sure this is safe.
75078c408004Sdan   */
75088c408004Sdan   if( pPager->exclusiveMode ){
75098c408004Sdan     rc = pagerExclusiveLock(pPager);
75108c408004Sdan   }
75118c408004Sdan 
75128c408004Sdan   /* Open the connection to the log file. If this operation fails,
75138c408004Sdan   ** (e.g. due to malloc() failure), return an error code.
75148c408004Sdan   */
75158c408004Sdan   if( rc==SQLITE_OK ){
7516f23da966Sdan     rc = sqlite3WalOpen(pPager->pVfs,
751785a83755Sdrh         pPager->fd, pPager->zWal, pPager->exclusiveMode,
751885a83755Sdrh         pPager->journalSizeLimit, &pPager->pWal
75198c408004Sdan     );
75208c408004Sdan   }
75215d8a1372Sdan   pagerFixMaplimit(pPager);
75228c408004Sdan 
75238c408004Sdan   return rc;
75248c408004Sdan }
75258c408004Sdan 
75268c408004Sdan 
75278c408004Sdan /*
7528e04dc88bSdan ** The caller must be holding a SHARED lock on the database file to call
7529e04dc88bSdan ** this function.
753040e459e0Sdrh **
753140e459e0Sdrh ** If the pager passed as the first argument is open on a real database
753240e459e0Sdrh ** file (not a temp file or an in-memory database), and the WAL file
753340e459e0Sdrh ** is not already open, make an attempt to open it now. If successful,
753440e459e0Sdrh ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
7535763afe62Sdan ** not support the xShmXXX() methods, return an error code. *pbOpen is
753640e459e0Sdrh ** not modified in either case.
753740e459e0Sdrh **
753840e459e0Sdrh ** If the pager is open on a temp-file (or in-memory database), or if
7539763afe62Sdan ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
754040e459e0Sdrh ** without doing anything.
7541e04dc88bSdan */
sqlite3PagerOpenWal(Pager * pPager,int * pbOpen)754240e459e0Sdrh int sqlite3PagerOpenWal(
754340e459e0Sdrh   Pager *pPager,                  /* Pager object */
7544763afe62Sdan   int *pbOpen                     /* OUT: Set to true if call is a no-op */
754540e459e0Sdrh ){
7546e04dc88bSdan   int rc = SQLITE_OK;             /* Return code */
7547e04dc88bSdan 
7548763afe62Sdan   assert( assert_pager_state(pPager) );
7549de1ae34eSdan   assert( pPager->eState==PAGER_OPEN   || pbOpen );
7550763afe62Sdan   assert( pPager->eState==PAGER_READER || !pbOpen );
7551763afe62Sdan   assert( pbOpen==0 || *pbOpen==0 );
7552763afe62Sdan   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
755340e459e0Sdrh 
755440e459e0Sdrh   if( !pPager->tempFile && !pPager->pWal ){
7555d9e5c4f6Sdrh     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
7556e04dc88bSdan 
7557919fc66eSdrh     /* Close any rollback journal previously open */
75584e004aa6Sdan     sqlite3OsClose(pPager->jfd);
75594e004aa6Sdan 
75608c408004Sdan     rc = pagerOpenWal(pPager);
7561e04dc88bSdan     if( rc==SQLITE_OK ){
7562e04dc88bSdan       pPager->journalMode = PAGER_JOURNALMODE_WAL;
7563de1ae34eSdan       pPager->eState = PAGER_OPEN;
7564e04dc88bSdan     }
7565e04dc88bSdan   }else{
7566763afe62Sdan     *pbOpen = 1;
7567e04dc88bSdan   }
7568e04dc88bSdan 
7569e04dc88bSdan   return rc;
7570e04dc88bSdan }
7571e04dc88bSdan 
7572e04dc88bSdan /*
7573e04dc88bSdan ** This function is called to close the connection to the log file prior
7574e04dc88bSdan ** to switching from WAL to rollback mode.
7575e04dc88bSdan **
7576e04dc88bSdan ** Before closing the log file, this function attempts to take an
7577e04dc88bSdan ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
7578e04dc88bSdan ** error (SQLITE_BUSY) is returned and the log connection is not closed.
7579e04dc88bSdan ** If successful, the EXCLUSIVE lock is not released before returning.
7580e04dc88bSdan */
sqlite3PagerCloseWal(Pager * pPager,sqlite3 * db)75817fb89906Sdan int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
7582e04dc88bSdan   int rc = SQLITE_OK;
7583e04dc88bSdan 
7584ede6eb8dSdan   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
7585ede6eb8dSdan 
7586ede6eb8dSdan   /* If the log file is not already open, but does exist in the file-system,
7587ede6eb8dSdan   ** it may need to be checkpointed before the connection can switch to
7588ede6eb8dSdan   ** rollback mode. Open it now so this can happen.
7589ede6eb8dSdan   */
75907ed91f23Sdrh   if( !pPager->pWal ){
7591ede6eb8dSdan     int logexists = 0;
75924e004aa6Sdan     rc = pagerLockDb(pPager, SHARED_LOCK);
7593ede6eb8dSdan     if( rc==SQLITE_OK ){
7594db10f082Sdan       rc = sqlite3OsAccess(
7595db10f082Sdan           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
7596db10f082Sdan       );
7597ede6eb8dSdan     }
7598ede6eb8dSdan     if( rc==SQLITE_OK && logexists ){
75998c408004Sdan       rc = pagerOpenWal(pPager);
7600ede6eb8dSdan     }
7601ede6eb8dSdan   }
7602ede6eb8dSdan 
7603ede6eb8dSdan   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
7604ede6eb8dSdan   ** the database file, the log and log-summary files will be deleted.
7605ede6eb8dSdan   */
76067ed91f23Sdrh   if( rc==SQLITE_OK && pPager->pWal ){
76078c408004Sdan     rc = pagerExclusiveLock(pPager);
7608e04dc88bSdan     if( rc==SQLITE_OK ){
7609daaae7b9Sdrh       rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
7610c97d8463Sdrh                            pPager->pageSize, (u8*)pPager->pTmpSpace);
76117ed91f23Sdrh       pPager->pWal = 0;
76125d8a1372Sdan       pagerFixMaplimit(pPager);
7613cdce61e1Sdrh       if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
7614e04dc88bSdan     }
7615e04dc88bSdan   }
7616e04dc88bSdan   return rc;
7617e04dc88bSdan }
761847ee386fSdan 
761958021b23Sdan #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
762058021b23Sdan /*
762158021b23Sdan ** If pager pPager is a wal-mode database not in exclusive locking mode,
762258021b23Sdan ** invoke the sqlite3WalWriteLock() function on the associated Wal object
762358021b23Sdan ** with the same db and bLock parameters as were passed to this function.
762458021b23Sdan ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
762558021b23Sdan */
sqlite3PagerWalWriteLock(Pager * pPager,int bLock)7626861fb1e9Sdan int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){
762758021b23Sdan   int rc = SQLITE_OK;
762858021b23Sdan   if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
7629861fb1e9Sdan     rc = sqlite3WalWriteLock(pPager->pWal, bLock);
763058021b23Sdan   }
763158021b23Sdan   return rc;
763258021b23Sdan }
7633861fb1e9Sdan 
7634861fb1e9Sdan /*
7635861fb1e9Sdan ** Set the database handle used by the wal layer to determine if
7636861fb1e9Sdan ** blocking locks are required.
7637861fb1e9Sdan */
sqlite3PagerWalDb(Pager * pPager,sqlite3 * db)7638861fb1e9Sdan void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){
7639861fb1e9Sdan   if( pagerUseWal(pPager) ){
7640861fb1e9Sdan     sqlite3WalDb(pPager->pWal, db);
7641861fb1e9Sdan   }
7642861fb1e9Sdan }
764358021b23Sdan #endif
76448875b9e7Sdrh 
7645fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
7646fc1acf33Sdan /*
7647fc1acf33Sdan ** If this is a WAL database, obtain a snapshot handle for the snapshot
7648fc1acf33Sdan ** currently open. Otherwise, return an error.
7649fc1acf33Sdan */
sqlite3PagerSnapshotGet(Pager * pPager,sqlite3_snapshot ** ppSnapshot)7650fc1acf33Sdan int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
7651fc1acf33Sdan   int rc = SQLITE_ERROR;
7652fc1acf33Sdan   if( pPager->pWal ){
7653fc1acf33Sdan     rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
7654fc1acf33Sdan   }
7655fc1acf33Sdan   return rc;
7656fc1acf33Sdan }
7657fc1acf33Sdan 
7658fc1acf33Sdan /*
7659fc1acf33Sdan ** If this is a WAL database, store a pointer to pSnapshot. Next time a
7660fc1acf33Sdan ** read transaction is opened, attempt to read from the snapshot it
7661fc1acf33Sdan ** identifies. If this is not a WAL database, return an error.
7662fc1acf33Sdan */
sqlite3PagerSnapshotOpen(Pager * pPager,sqlite3_snapshot * pSnapshot)76638714de97Sdan int sqlite3PagerSnapshotOpen(
76648714de97Sdan   Pager *pPager,
76658714de97Sdan   sqlite3_snapshot *pSnapshot
76668714de97Sdan ){
7667fc1acf33Sdan   int rc = SQLITE_OK;
7668fc1acf33Sdan   if( pPager->pWal ){
7669861fb1e9Sdan     sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
7670fc1acf33Sdan   }else{
7671fc1acf33Sdan     rc = SQLITE_ERROR;
7672fc1acf33Sdan   }
7673fc1acf33Sdan   return rc;
7674fc1acf33Sdan }
76751158498dSdan 
76761158498dSdan /*
76771158498dSdan ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
76781158498dSdan ** is not a WAL database, return an error.
76791158498dSdan */
sqlite3PagerSnapshotRecover(Pager * pPager)76801158498dSdan int sqlite3PagerSnapshotRecover(Pager *pPager){
76811158498dSdan   int rc;
76821158498dSdan   if( pPager->pWal ){
76831158498dSdan     rc = sqlite3WalSnapshotRecover(pPager->pWal);
76841158498dSdan   }else{
76851158498dSdan     rc = SQLITE_ERROR;
76861158498dSdan   }
76871158498dSdan   return rc;
76881158498dSdan }
7689fa3d4c19Sdan 
7690fa3d4c19Sdan /*
7691fa3d4c19Sdan ** The caller currently has a read transaction open on the database.
7692fa3d4c19Sdan ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
7693fa3d4c19Sdan ** this function takes a SHARED lock on the CHECKPOINTER slot and then
7694fa3d4c19Sdan ** checks if the snapshot passed as the second argument is still
7695fa3d4c19Sdan ** available. If so, SQLITE_OK is returned.
7696fa3d4c19Sdan **
7697fa3d4c19Sdan ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
7698fa3d4c19Sdan ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
7699fa3d4c19Sdan ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
7700fa3d4c19Sdan ** lock is released before returning.
7701fa3d4c19Sdan */
sqlite3PagerSnapshotCheck(Pager * pPager,sqlite3_snapshot * pSnapshot)7702fa3d4c19Sdan int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
7703fa3d4c19Sdan   int rc;
7704fa3d4c19Sdan   if( pPager->pWal ){
7705fa3d4c19Sdan     rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
7706fa3d4c19Sdan   }else{
7707fa3d4c19Sdan     rc = SQLITE_ERROR;
7708fa3d4c19Sdan   }
7709fa3d4c19Sdan   return rc;
7710fa3d4c19Sdan }
7711fa3d4c19Sdan 
7712fa3d4c19Sdan /*
7713fa3d4c19Sdan ** Release a lock obtained by an earlier successful call to
7714fa3d4c19Sdan ** sqlite3PagerSnapshotCheck().
7715fa3d4c19Sdan */
sqlite3PagerSnapshotUnlock(Pager * pPager)7716fa3d4c19Sdan void sqlite3PagerSnapshotUnlock(Pager *pPager){
7717fa3d4c19Sdan   assert( pPager->pWal );
77183fd7eaf3Sdan   sqlite3WalSnapshotUnlock(pPager->pWal);
7719fa3d4c19Sdan }
7720fa3d4c19Sdan 
7721fc1acf33Sdan #endif /* SQLITE_ENABLE_SNAPSHOT */
7722f7c7031fSdrh #endif /* !SQLITE_OMIT_WAL */
7723f7c7031fSdrh 
772470708600Sdrh #ifdef SQLITE_ENABLE_ZIPVFS
7725b3bdc72dSdan /*
7726b3bdc72dSdan ** A read-lock must be held on the pager when this function is called. If
7727b3bdc72dSdan ** the pager is in WAL mode and the WAL file currently contains one or more
7728b3bdc72dSdan ** frames, return the size in bytes of the page images stored within the
7729b3bdc72dSdan ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
7730b3bdc72dSdan ** is empty, return 0.
7731b3bdc72dSdan */
sqlite3PagerWalFramesize(Pager * pPager)7732b3bdc72dSdan int sqlite3PagerWalFramesize(Pager *pPager){
77339675d5daSdan   assert( pPager->eState>=PAGER_READER );
7734b3bdc72dSdan   return sqlite3WalFramesize(pPager->pWal);
7735b3bdc72dSdan }
773670708600Sdrh #endif
7737b3bdc72dSdan 
77382e66f0b9Sdrh #endif /* SQLITE_OMIT_DISKIO */
7739