1c438efd6Sdrh /*
27ed91f23Sdrh ** 2010 February 1
37ed91f23Sdrh **
47ed91f23Sdrh ** The author disclaims copyright to this source code. In place of
57ed91f23Sdrh ** a legal notice, here is a blessing:
67ed91f23Sdrh **
77ed91f23Sdrh ** May you do good and not evil.
87ed91f23Sdrh ** May you find forgiveness for yourself and forgive others.
97ed91f23Sdrh ** May you share freely, never taking more than you give.
107ed91f23Sdrh **
117ed91f23Sdrh *************************************************************************
127ed91f23Sdrh **
13027a128aSdrh ** This file contains the implementation of a write-ahead log (WAL) used in
14027a128aSdrh ** "journal_mode=WAL" mode.
1529d4dbefSdrh **
167ed91f23Sdrh ** WRITE-AHEAD LOG (WAL) FILE FORMAT
17c438efd6Sdrh **
187e263728Sdrh ** A WAL file consists of a header followed by zero or more "frames".
19027a128aSdrh ** Each frame records the revised content of a single page from the
2029d4dbefSdrh ** database file. All changes to the database are recorded by writing
2129d4dbefSdrh ** frames into the WAL. Transactions commit when a frame is written that
2229d4dbefSdrh ** contains a commit marker. A single WAL can and usually does record
2329d4dbefSdrh ** multiple transactions. Periodically, the content of the WAL is
2429d4dbefSdrh ** transferred back into the database file in an operation called a
2529d4dbefSdrh ** "checkpoint".
2629d4dbefSdrh **
2729d4dbefSdrh ** A single WAL file can be used multiple times. In other words, the
28027a128aSdrh ** WAL can fill up with frames and then be checkpointed and then new
2929d4dbefSdrh ** frames can overwrite the old ones. A WAL always grows from beginning
3029d4dbefSdrh ** toward the end. Checksums and counters attached to each frame are
3129d4dbefSdrh ** used to determine which frames within the WAL are valid and which
3229d4dbefSdrh ** are leftovers from prior checkpoints.
3329d4dbefSdrh **
34cd28508eSdrh ** The WAL header is 32 bytes in size and consists of the following eight
35c438efd6Sdrh ** big-endian 32-bit unsigned integer values:
36c438efd6Sdrh **
371b78eaf0Sdrh ** 0: Magic number. 0x377f0682 or 0x377f0683
3823ea97b6Sdrh ** 4: File format version. Currently 3007000
3923ea97b6Sdrh ** 8: Database page size. Example: 1024
4023ea97b6Sdrh ** 12: Checkpoint sequence number
417e263728Sdrh ** 16: Salt-1, random integer incremented with each checkpoint
427e263728Sdrh ** 20: Salt-2, a different random integer changing with each ckpt
4310f5a50eSdan ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
4410f5a50eSdan ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
45c438efd6Sdrh **
4623ea97b6Sdrh ** Immediately following the wal-header are zero or more frames. Each
4723ea97b6Sdrh ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48cd28508eSdrh ** of page data. The frame-header is six big-endian 32-bit unsigned
49c438efd6Sdrh ** integer values, as follows:
50c438efd6Sdrh **
51c438efd6Sdrh ** 0: Page number.
52c438efd6Sdrh ** 4: For commit records, the size of the database image in pages
53c438efd6Sdrh ** after the commit. For all other records, zero.
547e263728Sdrh ** 8: Salt-1 (copied from the header)
557e263728Sdrh ** 12: Salt-2 (copied from the header)
5623ea97b6Sdrh ** 16: Checksum-1.
5723ea97b6Sdrh ** 20: Checksum-2.
5829d4dbefSdrh **
597e263728Sdrh ** A frame is considered valid if and only if the following conditions are
607e263728Sdrh ** true:
617e263728Sdrh **
627e263728Sdrh ** (1) The salt-1 and salt-2 values in the frame-header match
637e263728Sdrh ** salt values in the wal-header
647e263728Sdrh **
657e263728Sdrh ** (2) The checksum values in the final 8 bytes of the frame-header
661b78eaf0Sdrh ** exactly match the checksum computed consecutively on the
671b78eaf0Sdrh ** WAL header and the first 8 bytes and the content of all frames
681b78eaf0Sdrh ** up to and including the current frame.
691b78eaf0Sdrh **
701b78eaf0Sdrh ** The checksum is computed using 32-bit big-endian integers if the
711b78eaf0Sdrh ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
721b78eaf0Sdrh ** is computed using little-endian if the magic number is 0x377f0682.
7351b21b16Sdrh ** The checksum values are always stored in the frame header in a
7451b21b16Sdrh ** big-endian format regardless of which byte order is used to compute
7551b21b16Sdrh ** the checksum. The checksum is computed by interpreting the input as
7651b21b16Sdrh ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
77ffca4301Sdrh ** algorithm used for the checksum is as follows:
7851b21b16Sdrh **
7951b21b16Sdrh ** for i from 0 to n-1 step 2:
8051b21b16Sdrh ** s0 += x[i] + s1;
8151b21b16Sdrh ** s1 += x[i+1] + s0;
8251b21b16Sdrh ** endfor
837e263728Sdrh **
84cd28508eSdrh ** Note that s0 and s1 are both weighted checksums using fibonacci weights
85cd28508eSdrh ** in reverse order (the largest fibonacci weight occurs on the first element
86cd28508eSdrh ** of the sequence being summed.) The s1 value spans all 32-bit
87cd28508eSdrh ** terms of the sequence whereas s0 omits the final term.
88cd28508eSdrh **
897e263728Sdrh ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
907e263728Sdrh ** WAL is transferred into the database, then the database is VFS.xSync-ed.
91ffca4301Sdrh ** The VFS.xSync operations serve as write barriers - all writes launched
927e263728Sdrh ** before the xSync must complete before any write that launches after the
937e263728Sdrh ** xSync begins.
947e263728Sdrh **
957e263728Sdrh ** After each checkpoint, the salt-1 value is incremented and the salt-2
967e263728Sdrh ** value is randomized. This prevents old and new frames in the WAL from
977e263728Sdrh ** being considered valid at the same time and being checkpointing together
987e263728Sdrh ** following a crash.
997e263728Sdrh **
10029d4dbefSdrh ** READER ALGORITHM
10129d4dbefSdrh **
10229d4dbefSdrh ** To read a page from the database (call it page number P), a reader
10329d4dbefSdrh ** first checks the WAL to see if it contains page P. If so, then the
10473b64e4dSdrh ** last valid instance of page P that is a followed by a commit frame
10573b64e4dSdrh ** or is a commit frame itself becomes the value read. If the WAL
10673b64e4dSdrh ** contains no copies of page P that are valid and which are a commit
10773b64e4dSdrh ** frame or are followed by a commit frame, then page P is read from
10873b64e4dSdrh ** the database file.
10929d4dbefSdrh **
11073b64e4dSdrh ** To start a read transaction, the reader records the index of the last
11173b64e4dSdrh ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
11273b64e4dSdrh ** for all subsequent read operations. New transactions can be appended
11373b64e4dSdrh ** to the WAL, but as long as the reader uses its original mxFrame value
11473b64e4dSdrh ** and ignores the newly appended content, it will see a consistent snapshot
11573b64e4dSdrh ** of the database from a single point in time. This technique allows
11673b64e4dSdrh ** multiple concurrent readers to view different versions of the database
11773b64e4dSdrh ** content simultaneously.
11873b64e4dSdrh **
11973b64e4dSdrh ** The reader algorithm in the previous paragraphs works correctly, but
12029d4dbefSdrh ** because frames for page P can appear anywhere within the WAL, the
121027a128aSdrh ** reader has to scan the entire WAL looking for page P frames. If the
12229d4dbefSdrh ** WAL is large (multiple megabytes is typical) that scan can be slow,
123027a128aSdrh ** and read performance suffers. To overcome this problem, a separate
12429d4dbefSdrh ** data structure called the wal-index is maintained to expedite the
12529d4dbefSdrh ** search for frames of a particular page.
12629d4dbefSdrh **
12729d4dbefSdrh ** WAL-INDEX FORMAT
12829d4dbefSdrh **
12929d4dbefSdrh ** Conceptually, the wal-index is shared memory, though VFS implementations
13029d4dbefSdrh ** might choose to implement the wal-index using a mmapped file. Because
13129d4dbefSdrh ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
13229d4dbefSdrh ** on a network filesystem. All users of the database must be able to
13329d4dbefSdrh ** share memory.
13429d4dbefSdrh **
13507dae088Sdrh ** In the default unix and windows implementation, the wal-index is a mmapped
13607dae088Sdrh ** file whose name is the database name with a "-shm" suffix added. For that
13707dae088Sdrh ** reason, the wal-index is sometimes called the "shm" file.
13807dae088Sdrh **
13929d4dbefSdrh ** The wal-index is transient. After a crash, the wal-index can (and should
14029d4dbefSdrh ** be) reconstructed from the original WAL file. In fact, the VFS is required
14129d4dbefSdrh ** to either truncate or zero the header of the wal-index when the last
14229d4dbefSdrh ** connection to it closes. Because the wal-index is transient, it can
14329d4dbefSdrh ** use an architecture-specific format; it does not have to be cross-platform.
14429d4dbefSdrh ** Hence, unlike the database and WAL file formats which store all values
14529d4dbefSdrh ** as big endian, the wal-index can store multi-byte values in the native
14629d4dbefSdrh ** byte order of the host computer.
14729d4dbefSdrh **
14829d4dbefSdrh ** The purpose of the wal-index is to answer this question quickly: Given
149610b8d85Sdrh ** a page number P and a maximum frame index M, return the index of the
150610b8d85Sdrh ** last frame in the wal before frame M for page P in the WAL, or return
151610b8d85Sdrh ** NULL if there are no frames for page P in the WAL prior to M.
15229d4dbefSdrh **
15329d4dbefSdrh ** The wal-index consists of a header region, followed by an one or
15429d4dbefSdrh ** more index blocks.
15529d4dbefSdrh **
156027a128aSdrh ** The wal-index header contains the total number of frames within the WAL
157d5578433Smistachkin ** in the mxFrame field.
158ad3cadd8Sdan **
159ad3cadd8Sdan ** Each index block except for the first contains information on
160ad3cadd8Sdan ** HASHTABLE_NPAGE frames. The first index block contains information on
161ad3cadd8Sdan ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
162ad3cadd8Sdan ** HASHTABLE_NPAGE are selected so that together the wal-index header and
163ad3cadd8Sdan ** first index block are the same size as all other index blocks in the
164fd4c7862Sdrh ** wal-index. The values are:
165fd4c7862Sdrh **
166fd4c7862Sdrh ** HASHTABLE_NPAGE 4096
167fd4c7862Sdrh ** HASHTABLE_NPAGE_ONE 4062
168ad3cadd8Sdan **
169ad3cadd8Sdan ** Each index block contains two sections, a page-mapping that contains the
170ad3cadd8Sdan ** database page number associated with each wal frame, and a hash-table
171ffca4301Sdrh ** that allows readers to query an index block for a specific page number.
172ad3cadd8Sdan ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
173ad3cadd8Sdan ** for the first index block) 32-bit page numbers. The first entry in the
174ad3cadd8Sdan ** first index-block contains the database page number corresponding to the
175ad3cadd8Sdan ** first frame in the WAL file. The first entry in the second index block
176ad3cadd8Sdan ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
177ad3cadd8Sdan ** the log, and so on.
178ad3cadd8Sdan **
179ad3cadd8Sdan ** The last index block in a wal-index usually contains less than the full
180ad3cadd8Sdan ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
181ad3cadd8Sdan ** depending on the contents of the WAL file. This does not change the
182ad3cadd8Sdan ** allocated size of the page-mapping array - the page-mapping array merely
183ad3cadd8Sdan ** contains unused entries.
184027a128aSdrh **
185027a128aSdrh ** Even without using the hash table, the last frame for page P
186ad3cadd8Sdan ** can be found by scanning the page-mapping sections of each index block
187027a128aSdrh ** starting with the last index block and moving toward the first, and
188027a128aSdrh ** within each index block, starting at the end and moving toward the
189027a128aSdrh ** beginning. The first entry that equals P corresponds to the frame
190027a128aSdrh ** holding the content for that page.
191027a128aSdrh **
192027a128aSdrh ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
193027a128aSdrh ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
194027a128aSdrh ** hash table for each page number in the mapping section, so the hash
195027a128aSdrh ** table is never more than half full. The expected number of collisions
196027a128aSdrh ** prior to finding a match is 1. Each entry of the hash table is an
197027a128aSdrh ** 1-based index of an entry in the mapping section of the same
198027a128aSdrh ** index block. Let K be the 1-based index of the largest entry in
199027a128aSdrh ** the mapping section. (For index blocks other than the last, K will
200027a128aSdrh ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
201027a128aSdrh ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
20273b64e4dSdrh ** contain a value of 0.
203027a128aSdrh **
204027a128aSdrh ** To look for page P in the hash table, first compute a hash iKey on
205027a128aSdrh ** P as follows:
206027a128aSdrh **
207027a128aSdrh ** iKey = (P * 383) % HASHTABLE_NSLOT
208027a128aSdrh **
209027a128aSdrh ** Then start scanning entries of the hash table, starting with iKey
210027a128aSdrh ** (wrapping around to the beginning when the end of the hash table is
211027a128aSdrh ** reached) until an unused hash slot is found. Let the first unused slot
212027a128aSdrh ** be at index iUnused. (iUnused might be less than iKey if there was
213027a128aSdrh ** wrap-around.) Because the hash table is never more than half full,
214027a128aSdrh ** the search is guaranteed to eventually hit an unused entry. Let
215027a128aSdrh ** iMax be the value between iKey and iUnused, closest to iUnused,
216027a128aSdrh ** where aHash[iMax]==P. If there is no iMax entry (if there exists
217027a128aSdrh ** no hash slot such that aHash[i]==p) then page P is not in the
218027a128aSdrh ** current index block. Otherwise the iMax-th mapping entry of the
219027a128aSdrh ** current index block corresponds to the last entry that references
220027a128aSdrh ** page P.
221027a128aSdrh **
222027a128aSdrh ** A hash search begins with the last index block and moves toward the
223027a128aSdrh ** first index block, looking for entries corresponding to page P. On
224027a128aSdrh ** average, only two or three slots in each index block need to be
225027a128aSdrh ** examined in order to either find the last entry for page P, or to
226027a128aSdrh ** establish that no such entry exists in the block. Each index block
227027a128aSdrh ** holds over 4000 entries. So two or three index blocks are sufficient
228027a128aSdrh ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
229027a128aSdrh ** comparisons (on average) suffice to either locate a frame in the
230027a128aSdrh ** WAL or to establish that the frame does not exist in the WAL. This
231027a128aSdrh ** is much faster than scanning the entire 10MB WAL.
232027a128aSdrh **
233027a128aSdrh ** Note that entries are added in order of increasing K. Hence, one
234027a128aSdrh ** reader might be using some value K0 and a second reader that started
235027a128aSdrh ** at a later time (after additional transactions were added to the WAL
236027a128aSdrh ** and to the wal-index) might be using a different value K1, where K1>K0.
237027a128aSdrh ** Both readers can use the same hash table and mapping section to get
238027a128aSdrh ** the correct result. There may be entries in the hash table with
239027a128aSdrh ** K>K0 but to the first reader, those entries will appear to be unused
240027a128aSdrh ** slots in the hash table and so the first reader will get an answer as
241027a128aSdrh ** if no values greater than K0 had ever been inserted into the hash table
242027a128aSdrh ** in the first place - which is what reader one wants. Meanwhile, the
243027a128aSdrh ** second reader using K1 will see additional values that were inserted
244027a128aSdrh ** later, which is exactly what reader two wants.
245027a128aSdrh **
2466f150148Sdan ** When a rollback occurs, the value of K is decreased. Hash table entries
2476f150148Sdan ** that correspond to frames greater than the new K value are removed
2486f150148Sdan ** from the hash table at this point.
249c438efd6Sdrh */
25029d4dbefSdrh #ifndef SQLITE_OMIT_WAL
251c438efd6Sdrh
25229d4dbefSdrh #include "wal.h"
25329d4dbefSdrh
25473b64e4dSdrh /*
255c74c3334Sdrh ** Trace output macros
256c74c3334Sdrh */
257c74c3334Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25815d68092Sdrh int sqlite3WalTrace = 0;
259c74c3334Sdrh # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
260c74c3334Sdrh #else
261c74c3334Sdrh # define WALTRACE(X)
262c74c3334Sdrh #endif
263c74c3334Sdrh
26410f5a50eSdan /*
26510f5a50eSdan ** The maximum (and only) versions of the wal and wal-index formats
26610f5a50eSdan ** that may be interpreted by this version of SQLite.
26710f5a50eSdan **
26810f5a50eSdan ** If a client begins recovering a WAL file and finds that (a) the checksum
26910f5a50eSdan ** values in the wal-header are correct and (b) the version field is not
27010f5a50eSdan ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
27110f5a50eSdan **
27210f5a50eSdan ** Similarly, if a client successfully reads a wal-index header (i.e. the
27310f5a50eSdan ** checksum test is successful) and finds that the version field is not
27410f5a50eSdan ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
27510f5a50eSdan ** returns SQLITE_CANTOPEN.
27610f5a50eSdan */
27710f5a50eSdan #define WAL_MAX_VERSION 3007000
27810f5a50eSdan #define WALINDEX_MAX_VERSION 3007000
279c74c3334Sdrh
280c74c3334Sdrh /*
28107dae088Sdrh ** Index numbers for various locking bytes. WAL_NREADER is the number
282998147ecSdrh ** of available reader locks and should be at least 3. The default
283998147ecSdrh ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
28407dae088Sdrh **
28507dae088Sdrh ** Technically, the various VFSes are free to implement these locks however
28607dae088Sdrh ** they see fit. However, compatibility is encouraged so that VFSes can
28707dae088Sdrh ** interoperate. The standard implemention used on both unix and windows
28807dae088Sdrh ** is for the index number to indicate a byte offset into the
28907dae088Sdrh ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
29007dae088Sdrh ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
29107dae088Sdrh ** should be 120) is the location in the shm file for the first locking
29207dae088Sdrh ** byte.
29373b64e4dSdrh */
29473b64e4dSdrh #define WAL_WRITE_LOCK 0
29573b64e4dSdrh #define WAL_ALL_BUT_WRITE 1
29673b64e4dSdrh #define WAL_CKPT_LOCK 1
29773b64e4dSdrh #define WAL_RECOVER_LOCK 2
29873b64e4dSdrh #define WAL_READ_LOCK(I) (3+(I))
29973b64e4dSdrh #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
30073b64e4dSdrh
301c438efd6Sdrh
3027ed91f23Sdrh /* Object declarations */
3037ed91f23Sdrh typedef struct WalIndexHdr WalIndexHdr;
3047ed91f23Sdrh typedef struct WalIterator WalIterator;
30573b64e4dSdrh typedef struct WalCkptInfo WalCkptInfo;
306c438efd6Sdrh
307c438efd6Sdrh
308c438efd6Sdrh /*
309286a2884Sdrh ** The following object holds a copy of the wal-index header content.
310286a2884Sdrh **
311286a2884Sdrh ** The actual header in the wal-index consists of two copies of this
312998147ecSdrh ** object followed by one instance of the WalCkptInfo object.
313998147ecSdrh ** For all versions of SQLite through 3.10.0 and probably beyond,
314998147ecSdrh ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
315998147ecSdrh ** the total header size is 136 bytes.
3169b78f791Sdrh **
3179b78f791Sdrh ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
3189b78f791Sdrh ** Or it can be 1 to represent a 65536-byte page. The latter case was
3199b78f791Sdrh ** added in 3.7.1 when support for 64K pages was added.
320c438efd6Sdrh */
3217ed91f23Sdrh struct WalIndexHdr {
32210f5a50eSdan u32 iVersion; /* Wal-index version */
32310f5a50eSdan u32 unused; /* Unused (padding) field */
324c438efd6Sdrh u32 iChange; /* Counter incremented each transaction */
3254b82c387Sdrh u8 isInit; /* 1 when initialized */
3264b82c387Sdrh u8 bigEndCksum; /* True if checksums in WAL are big-endian */
3279b78f791Sdrh u16 szPage; /* Database page size in bytes. 1==64K */
328027a128aSdrh u32 mxFrame; /* Index of last valid frame in the WAL */
329c438efd6Sdrh u32 nPage; /* Size of database in pages */
33071d89919Sdan u32 aFrameCksum[2]; /* Checksum of last frame in log */
33171d89919Sdan u32 aSalt[2]; /* Two salt values copied from WAL header */
3327e263728Sdrh u32 aCksum[2]; /* Checksum over all prior fields */
333c438efd6Sdrh };
334c438efd6Sdrh
33573b64e4dSdrh /*
33673b64e4dSdrh ** A copy of the following object occurs in the wal-index immediately
33773b64e4dSdrh ** following the second copy of the WalIndexHdr. This object stores
33873b64e4dSdrh ** information used by checkpoint.
33973b64e4dSdrh **
34073b64e4dSdrh ** nBackfill is the number of frames in the WAL that have been written
34173b64e4dSdrh ** back into the database. (We call the act of moving content from WAL to
34273b64e4dSdrh ** database "backfilling".) The nBackfill number is never greater than
34373b64e4dSdrh ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
34473b64e4dSdrh ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
34573b64e4dSdrh ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
34673b64e4dSdrh ** mxFrame back to zero when the WAL is reset.
34773b64e4dSdrh **
348998147ecSdrh ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
349998147ecSdrh ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
350998147ecSdrh ** the nBackfillAttempted is set before any backfilling is done and the
351998147ecSdrh ** nBackfill is only set after all backfilling completes. So if a checkpoint
352998147ecSdrh ** crashes, nBackfillAttempted might be larger than nBackfill. The
353998147ecSdrh ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
354998147ecSdrh **
355998147ecSdrh ** The aLock[] field is a set of bytes used for locking. These bytes should
356998147ecSdrh ** never be read or written.
357998147ecSdrh **
35873b64e4dSdrh ** There is one entry in aReadMark[] for each reader lock. If a reader
35973b64e4dSdrh ** holds read-lock K, then the value in aReadMark[K] is no greater than
360db7f647eSdrh ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
361db7f647eSdrh ** for any aReadMark[] means that entry is unused. aReadMark[0] is
362db7f647eSdrh ** a special case; its value is never used and it exists as a place-holder
363db7f647eSdrh ** to avoid having to offset aReadMark[] indexs by one. Readers holding
364db7f647eSdrh ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
365db7f647eSdrh ** directly from the database.
36673b64e4dSdrh **
36773b64e4dSdrh ** The value of aReadMark[K] may only be changed by a thread that
36873b64e4dSdrh ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
36973b64e4dSdrh ** aReadMark[K] cannot changed while there is a reader is using that mark
37073b64e4dSdrh ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
37173b64e4dSdrh **
37273b64e4dSdrh ** The checkpointer may only transfer frames from WAL to database where
37373b64e4dSdrh ** the frame numbers are less than or equal to every aReadMark[] that is
37473b64e4dSdrh ** in use (that is, every aReadMark[j] for which there is a corresponding
37573b64e4dSdrh ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
37673b64e4dSdrh ** largest value and will increase an unused aReadMark[] to mxFrame if there
37773b64e4dSdrh ** is not already an aReadMark[] equal to mxFrame. The exception to the
37873b64e4dSdrh ** previous sentence is when nBackfill equals mxFrame (meaning that everything
37973b64e4dSdrh ** in the WAL has been backfilled into the database) then new readers
38073b64e4dSdrh ** will choose aReadMark[0] which has value 0 and hence such reader will
38173b64e4dSdrh ** get all their all content directly from the database file and ignore
38273b64e4dSdrh ** the WAL.
38373b64e4dSdrh **
38473b64e4dSdrh ** Writers normally append new frames to the end of the WAL. However,
38573b64e4dSdrh ** if nBackfill equals mxFrame (meaning that all WAL content has been
38673b64e4dSdrh ** written back into the database) and if no readers are using the WAL
38773b64e4dSdrh ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
38873b64e4dSdrh ** the writer will first "reset" the WAL back to the beginning and start
38973b64e4dSdrh ** writing new content beginning at frame 1.
39073b64e4dSdrh **
39173b64e4dSdrh ** We assume that 32-bit loads are atomic and so no locks are needed in
39273b64e4dSdrh ** order to read from any aReadMark[] entries.
39373b64e4dSdrh */
39473b64e4dSdrh struct WalCkptInfo {
39573b64e4dSdrh u32 nBackfill; /* Number of WAL frames backfilled into DB */
39673b64e4dSdrh u32 aReadMark[WAL_NREADER]; /* Reader marks */
397998147ecSdrh u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
398998147ecSdrh u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
399998147ecSdrh u32 notUsed0; /* Available for future enhancements */
40073b64e4dSdrh };
401db7f647eSdrh #define READMARK_NOT_USED 0xffffffff
40273b64e4dSdrh
403f873392dSdrh /*
404f873392dSdrh ** This is a schematic view of the complete 136-byte header of the
405f873392dSdrh ** wal-index file (also known as the -shm file):
406f873392dSdrh **
407f873392dSdrh ** +-----------------------------+
408f873392dSdrh ** 0: | iVersion | \
409f873392dSdrh ** +-----------------------------+ |
410f873392dSdrh ** 4: | (unused padding) | |
411f873392dSdrh ** +-----------------------------+ |
412f873392dSdrh ** 8: | iChange | |
413f873392dSdrh ** +-------+-------+-------------+ |
414f873392dSdrh ** 12: | bInit | bBig | szPage | |
415f873392dSdrh ** +-------+-------+-------------+ |
416f873392dSdrh ** 16: | mxFrame | | First copy of the
417f873392dSdrh ** +-----------------------------+ | WalIndexHdr object
418f873392dSdrh ** 20: | nPage | |
419f873392dSdrh ** +-----------------------------+ |
420f873392dSdrh ** 24: | aFrameCksum | |
421f873392dSdrh ** | | |
422f873392dSdrh ** +-----------------------------+ |
423f873392dSdrh ** 32: | aSalt | |
424f873392dSdrh ** | | |
425f873392dSdrh ** +-----------------------------+ |
426f873392dSdrh ** 40: | aCksum | |
427f873392dSdrh ** | | /
428f873392dSdrh ** +-----------------------------+
429f873392dSdrh ** 48: | iVersion | \
430f873392dSdrh ** +-----------------------------+ |
431f873392dSdrh ** 52: | (unused padding) | |
432f873392dSdrh ** +-----------------------------+ |
433f873392dSdrh ** 56: | iChange | |
434f873392dSdrh ** +-------+-------+-------------+ |
435f873392dSdrh ** 60: | bInit | bBig | szPage | |
436f873392dSdrh ** +-------+-------+-------------+ | Second copy of the
437f873392dSdrh ** 64: | mxFrame | | WalIndexHdr
438f873392dSdrh ** +-----------------------------+ |
439f873392dSdrh ** 68: | nPage | |
440f873392dSdrh ** +-----------------------------+ |
441f873392dSdrh ** 72: | aFrameCksum | |
442f873392dSdrh ** | | |
443f873392dSdrh ** +-----------------------------+ |
444f873392dSdrh ** 80: | aSalt | |
445f873392dSdrh ** | | |
446f873392dSdrh ** +-----------------------------+ |
447f873392dSdrh ** 88: | aCksum | |
448f873392dSdrh ** | | /
449f873392dSdrh ** +-----------------------------+
450f873392dSdrh ** 96: | nBackfill |
451f873392dSdrh ** +-----------------------------+
452f873392dSdrh ** 100: | 5 read marks |
453f873392dSdrh ** | |
454f873392dSdrh ** | |
455f873392dSdrh ** | |
456f873392dSdrh ** | |
457f873392dSdrh ** +-------+-------+------+------+
458f873392dSdrh ** 120: | Write | Ckpt | Rcvr | Rd0 | \
459f873392dSdrh ** +-------+-------+------+------+ ) 8 lock bytes
460f873392dSdrh ** | Read1 | Read2 | Rd3 | Rd4 | /
461f873392dSdrh ** +-------+-------+------+------+
462f873392dSdrh ** 128: | nBackfillAttempted |
463f873392dSdrh ** +-----------------------------+
464f873392dSdrh ** 132: | (unused padding) |
465f873392dSdrh ** +-----------------------------+
466f873392dSdrh */
46773b64e4dSdrh
4687e263728Sdrh /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
4697e263728Sdrh ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
4707e263728Sdrh ** only support mandatory file-locks, we do not read or write data
4717e263728Sdrh ** from the region of the file on which locks are applied.
472c438efd6Sdrh */
473998147ecSdrh #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
474998147ecSdrh #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
475c438efd6Sdrh
4767ed91f23Sdrh /* Size of header before each frame in wal */
47723ea97b6Sdrh #define WAL_FRAME_HDRSIZE 24
478c438efd6Sdrh
47910f5a50eSdan /* Size of write ahead log header, including checksum. */
48010f5a50eSdan #define WAL_HDRSIZE 32
481c438efd6Sdrh
482b8fd6c2fSdan /* WAL magic value. Either this value, or the same value with the least
483b8fd6c2fSdan ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
484b8fd6c2fSdan ** big-endian format in the first 4 bytes of a WAL file.
485b8fd6c2fSdan **
486b8fd6c2fSdan ** If the LSB is set, then the checksums for each frame within the WAL
487b8fd6c2fSdan ** file are calculated by treating all data as an array of 32-bit
488b8fd6c2fSdan ** big-endian words. Otherwise, they are calculated by interpreting
489b8fd6c2fSdan ** all data as 32-bit little-endian words.
490b8fd6c2fSdan */
491b8fd6c2fSdan #define WAL_MAGIC 0x377f0682
492b8fd6c2fSdan
493c438efd6Sdrh /*
4947ed91f23Sdrh ** Return the offset of frame iFrame in the write-ahead log file,
4956e81096fSdrh ** assuming a database page size of szPage bytes. The offset returned
4967ed91f23Sdrh ** is to the start of the write-ahead log frame-header.
497c438efd6Sdrh */
4986e81096fSdrh #define walFrameOffset(iFrame, szPage) ( \
499bd0e9070Sdan WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
500c438efd6Sdrh )
501c438efd6Sdrh
502c438efd6Sdrh /*
5037ed91f23Sdrh ** An open write-ahead log file is represented by an instance of the
5047ed91f23Sdrh ** following object.
505c438efd6Sdrh */
5067ed91f23Sdrh struct Wal {
50773b64e4dSdrh sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
508d9e5c4f6Sdrh sqlite3_file *pDbFd; /* File handle for the database file */
509d9e5c4f6Sdrh sqlite3_file *pWalFd; /* File handle for WAL file */
510c438efd6Sdrh u32 iCallback; /* Value to pass to log callback (or 0) */
51185a83755Sdrh i64 mxWalSize; /* Truncate WAL to this size upon reset */
51213a3cb82Sdan int nWiData; /* Size of array apWiData */
51388f975a7Sdrh int szFirstBlock; /* Size of first block written to WAL file */
51413a3cb82Sdan volatile u32 **apWiData; /* Pointer to wal-index content in memory */
515b2eced5dSdrh u32 szPage; /* Database page size */
51673b64e4dSdrh i16 readLock; /* Which read lock is being held. -1 for none */
5174eb02a45Sdrh u8 syncFlags; /* Flags to use to sync header writes */
5185543759bSdan u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
51973b64e4dSdrh u8 writeLock; /* True if in a write transaction */
52073b64e4dSdrh u8 ckptLock; /* True if holding a checkpoint lock */
52166dfec8bSdrh u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
522f60b7f36Sdan u8 truncateOnCommit; /* True to truncate WAL file on commit */
523d992b150Sdrh u8 syncHeader; /* Fsync the WAL header if true */
524374f4a04Sdrh u8 padToSectorBoundary; /* Pad transactions out to the next sector */
52585bc6df2Sdrh u8 bShmUnreliable; /* SHM content is read-only and unreliable */
52673b64e4dSdrh WalIndexHdr hdr; /* Wal-index header for current transaction */
527b8c7cfb8Sdan u32 minFrame; /* Ignore wal frames before this one */
528c9a9022bSdan u32 iReCksum; /* On commit, recalculate checksums from here */
5293e875ef3Sdan const char *zWalName; /* Name of WAL file */
5307e263728Sdrh u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
531aab4c02eSdrh #ifdef SQLITE_DEBUG
532aab4c02eSdrh u8 lockError; /* True if a locking error has occurred */
533aab4c02eSdrh #endif
534fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
535998147ecSdrh WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
5368714de97Sdan #endif
537861fb1e9Sdan #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
538861fb1e9Sdan sqlite3 *db;
539fc1acf33Sdan #endif
540c438efd6Sdrh };
541c438efd6Sdrh
54273b64e4dSdrh /*
5438c408004Sdan ** Candidate values for Wal.exclusiveMode.
5448c408004Sdan */
5458c408004Sdan #define WAL_NORMAL_MODE 0
5468c408004Sdan #define WAL_EXCLUSIVE_MODE 1
5478c408004Sdan #define WAL_HEAPMEMORY_MODE 2
5488c408004Sdan
5498c408004Sdan /*
55066dfec8bSdrh ** Possible values for WAL.readOnly
55166dfec8bSdrh */
55266dfec8bSdrh #define WAL_RDWR 0 /* Normal read/write connection */
55366dfec8bSdrh #define WAL_RDONLY 1 /* The WAL file is readonly */
55466dfec8bSdrh #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
55566dfec8bSdrh
55666dfec8bSdrh /*
557067f3165Sdan ** Each page of the wal-index mapping contains a hash-table made up of
558067f3165Sdan ** an array of HASHTABLE_NSLOT elements of the following type.
559067f3165Sdan */
560067f3165Sdan typedef u16 ht_slot;
561067f3165Sdan
562067f3165Sdan /*
563ad3cadd8Sdan ** This structure is used to implement an iterator that loops through
564ad3cadd8Sdan ** all frames in the WAL in database page order. Where two or more frames
565ad3cadd8Sdan ** correspond to the same database page, the iterator visits only the
566ad3cadd8Sdan ** frame most recently written to the WAL (in other words, the frame with
567ad3cadd8Sdan ** the largest index).
568ad3cadd8Sdan **
569ad3cadd8Sdan ** The internals of this structure are only accessed by:
570ad3cadd8Sdan **
571ad3cadd8Sdan ** walIteratorInit() - Create a new iterator,
572ad3cadd8Sdan ** walIteratorNext() - Step an iterator,
573ad3cadd8Sdan ** walIteratorFree() - Free an iterator.
574ad3cadd8Sdan **
575ad3cadd8Sdan ** This functionality is used by the checkpoint code (see walCheckpoint()).
576ad3cadd8Sdan */
577ad3cadd8Sdan struct WalIterator {
5788deae5adSdrh u32 iPrior; /* Last result returned from the iterator */
579d9c9b78eSdrh int nSegment; /* Number of entries in aSegment[] */
580ad3cadd8Sdan struct WalSegment {
581ad3cadd8Sdan int iNext; /* Next slot in aIndex[] not yet returned */
582ad3cadd8Sdan ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
583ad3cadd8Sdan u32 *aPgno; /* Array of page numbers. */
584d9c9b78eSdrh int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
585ad3cadd8Sdan int iZero; /* Frame number associated with aPgno[0] */
586d9c9b78eSdrh } aSegment[1]; /* One for every 32KB page in the wal-index */
587ad3cadd8Sdan };
588ad3cadd8Sdan
589ad3cadd8Sdan /*
59013a3cb82Sdan ** Define the parameters of the hash tables in the wal-index file. There
59113a3cb82Sdan ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
59213a3cb82Sdan ** wal-index.
59313a3cb82Sdan **
59413a3cb82Sdan ** Changing any of these constants will alter the wal-index format and
59513a3cb82Sdan ** create incompatibilities.
59613a3cb82Sdan */
597067f3165Sdan #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
59813a3cb82Sdan #define HASHTABLE_HASH_1 383 /* Should be prime */
59913a3cb82Sdan #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
60013a3cb82Sdan
601ad3cadd8Sdan /*
602ad3cadd8Sdan ** The block of page numbers associated with the first hash-table in a
60313a3cb82Sdan ** wal-index is smaller than usual. This is so that there is a complete
60413a3cb82Sdan ** hash-table on each aligned 32KB page of the wal-index.
60513a3cb82Sdan */
606067f3165Sdan #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
60713a3cb82Sdan
608067f3165Sdan /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
609067f3165Sdan #define WALINDEX_PGSZ ( \
610067f3165Sdan sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
611067f3165Sdan )
61213a3cb82Sdan
61313a3cb82Sdan /*
61413a3cb82Sdan ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
615067f3165Sdan ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
61613a3cb82Sdan ** numbered from zero.
61713a3cb82Sdan **
618c05a063cSdrh ** If the wal-index is currently smaller the iPage pages then the size
619c05a063cSdrh ** of the wal-index might be increased, but only if it is safe to do
620c05a063cSdrh ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
621c05a063cSdrh ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
622c05a063cSdrh **
6235f25627aSdrh ** Three possible result scenarios:
6245f25627aSdrh **
6255f25627aSdrh ** (1) rc==SQLITE_OK and *ppPage==Requested-Wal-Index-Page
6265f25627aSdrh ** (2) rc>=SQLITE_ERROR and *ppPage==NULL
6275f25627aSdrh ** (3) rc==SQLITE_OK and *ppPage==NULL // only if iPage==0
6285f25627aSdrh **
6295f25627aSdrh ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
63013a3cb82Sdan */
walIndexPageRealloc(Wal * pWal,int iPage,volatile u32 ** ppPage)6312e178d73Sdrh static SQLITE_NOINLINE int walIndexPageRealloc(
6322e178d73Sdrh Wal *pWal, /* The WAL context */
6332e178d73Sdrh int iPage, /* The page we seek */
6342e178d73Sdrh volatile u32 **ppPage /* Write the page pointer here */
6352e178d73Sdrh ){
63613a3cb82Sdan int rc = SQLITE_OK;
63713a3cb82Sdan
63813a3cb82Sdan /* Enlarge the pWal->apWiData[] array if required */
63913a3cb82Sdan if( pWal->nWiData<=iPage ){
640f6ad201aSdrh sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
64113a3cb82Sdan volatile u32 **apNew;
642d924e7bcSdrh apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
64313a3cb82Sdan if( !apNew ){
64413a3cb82Sdan *ppPage = 0;
645fad3039cSmistachkin return SQLITE_NOMEM_BKPT;
64613a3cb82Sdan }
647519426aaSdrh memset((void*)&apNew[pWal->nWiData], 0,
648519426aaSdrh sizeof(u32*)*(iPage+1-pWal->nWiData));
64913a3cb82Sdan pWal->apWiData = apNew;
65013a3cb82Sdan pWal->nWiData = iPage+1;
65113a3cb82Sdan }
65213a3cb82Sdan
65313a3cb82Sdan /* Request a pointer to the required page from the VFS */
654c0ec2f77Sdrh assert( pWal->apWiData[iPage]==0 );
6558c408004Sdan if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
6568c408004Sdan pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
657fad3039cSmistachkin if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
6588c408004Sdan }else{
65918801915Sdan rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
66013a3cb82Sdan pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
66113a3cb82Sdan );
6625f25627aSdrh assert( pWal->apWiData[iPage]!=0
6635f25627aSdrh || rc!=SQLITE_OK
6645f25627aSdrh || (pWal->writeLock==0 && iPage==0) );
665c05a063cSdrh testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
666e7f3edcdSdrh if( rc==SQLITE_OK ){
667e7f3edcdSdrh if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
668e7f3edcdSdrh }else if( (rc&0xff)==SQLITE_READONLY ){
66966dfec8bSdrh pWal->readOnly |= WAL_SHM_RDONLY;
67092c02da3Sdan if( rc==SQLITE_READONLY ){
67166dfec8bSdrh rc = SQLITE_OK;
6724edc6bf3Sdan }
67313a3cb82Sdan }
6748c408004Sdan }
675b6d2f9c5Sdan
67666dfec8bSdrh *ppPage = pWal->apWiData[iPage];
67713a3cb82Sdan assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
67813a3cb82Sdan return rc;
67913a3cb82Sdan }
walIndexPage(Wal * pWal,int iPage,volatile u32 ** ppPage)6802e178d73Sdrh static int walIndexPage(
6812e178d73Sdrh Wal *pWal, /* The WAL context */
6822e178d73Sdrh int iPage, /* The page we seek */
6832e178d73Sdrh volatile u32 **ppPage /* Write the page pointer here */
6842e178d73Sdrh ){
6852e178d73Sdrh if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
6862e178d73Sdrh return walIndexPageRealloc(pWal, iPage, ppPage);
6872e178d73Sdrh }
6882e178d73Sdrh return SQLITE_OK;
6892e178d73Sdrh }
69013a3cb82Sdan
69113a3cb82Sdan /*
69273b64e4dSdrh ** Return a pointer to the WalCkptInfo structure in the wal-index.
69373b64e4dSdrh */
walCkptInfo(Wal * pWal)69473b64e4dSdrh static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
6954280eb30Sdan assert( pWal->nWiData>0 && pWal->apWiData[0] );
6964280eb30Sdan return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
6974280eb30Sdan }
6984280eb30Sdan
6994280eb30Sdan /*
7004280eb30Sdan ** Return a pointer to the WalIndexHdr structure in the wal-index.
7014280eb30Sdan */
walIndexHdr(Wal * pWal)7024280eb30Sdan static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
7034280eb30Sdan assert( pWal->nWiData>0 && pWal->apWiData[0] );
7044280eb30Sdan return (volatile WalIndexHdr*)pWal->apWiData[0];
70573b64e4dSdrh }
70673b64e4dSdrh
707c438efd6Sdrh /*
708b8fd6c2fSdan ** The argument to this macro must be of type u32. On a little-endian
709b8fd6c2fSdan ** architecture, it returns the u32 value that results from interpreting
710b8fd6c2fSdan ** the 4 bytes as a big-endian value. On a big-endian architecture, it
71160ec914cSpeter.d.reid ** returns the value that would be produced by interpreting the 4 bytes
712b8fd6c2fSdan ** of the input value as a little-endian integer.
713b8fd6c2fSdan */
714b8fd6c2fSdan #define BYTESWAP32(x) ( \
715b8fd6c2fSdan (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
716b8fd6c2fSdan + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
717b8fd6c2fSdan )
718c438efd6Sdrh
719c438efd6Sdrh /*
7207e263728Sdrh ** Generate or extend an 8 byte checksum based on the data in
7217e263728Sdrh ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
7227e263728Sdrh ** initial values of 0 and 0 if aIn==NULL).
7237e263728Sdrh **
7247e263728Sdrh ** The checksum is written back into aOut[] before returning.
7257e263728Sdrh **
7267e263728Sdrh ** nByte must be a positive multiple of 8.
727c438efd6Sdrh */
walChecksumBytes(int nativeCksum,u8 * a,int nByte,const u32 * aIn,u32 * aOut)7287e263728Sdrh static void walChecksumBytes(
729b8fd6c2fSdan int nativeCksum, /* True for native byte-order, false for non-native */
7307e263728Sdrh u8 *a, /* Content to be checksummed */
7317e263728Sdrh int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
7327e263728Sdrh const u32 *aIn, /* Initial checksum value input */
7337e263728Sdrh u32 *aOut /* OUT: Final checksum value output */
7347e263728Sdrh ){
7357e263728Sdrh u32 s1, s2;
736b8fd6c2fSdan u32 *aData = (u32 *)a;
737b8fd6c2fSdan u32 *aEnd = (u32 *)&a[nByte];
738b8fd6c2fSdan
7397e263728Sdrh if( aIn ){
7407e263728Sdrh s1 = aIn[0];
7417e263728Sdrh s2 = aIn[1];
7427e263728Sdrh }else{
7437e263728Sdrh s1 = s2 = 0;
7447e263728Sdrh }
745c438efd6Sdrh
746584c754dSdrh assert( nByte>=8 );
747b8fd6c2fSdan assert( (nByte&0x00000007)==0 );
748f6ad201aSdrh assert( nByte<=65536 );
749c438efd6Sdrh
750b8fd6c2fSdan if( nativeCksum ){
751c438efd6Sdrh do {
752b8fd6c2fSdan s1 += *aData++ + s2;
753b8fd6c2fSdan s2 += *aData++ + s1;
754b8fd6c2fSdan }while( aData<aEnd );
755b8fd6c2fSdan }else{
756b8fd6c2fSdan do {
757b8fd6c2fSdan s1 += BYTESWAP32(aData[0]) + s2;
758b8fd6c2fSdan s2 += BYTESWAP32(aData[1]) + s1;
759b8fd6c2fSdan aData += 2;
760b8fd6c2fSdan }while( aData<aEnd );
761b8fd6c2fSdan }
762b8fd6c2fSdan
7637e263728Sdrh aOut[0] = s1;
7647e263728Sdrh aOut[1] = s2;
765c438efd6Sdrh }
766c438efd6Sdrh
767f16cf653Sdrh /*
768f16cf653Sdrh ** If there is the possibility of concurrent access to the SHM file
769f16cf653Sdrh ** from multiple threads and/or processes, then do a memory barrier.
770f16cf653Sdrh */
walShmBarrier(Wal * pWal)7718c408004Sdan static void walShmBarrier(Wal *pWal){
7728c408004Sdan if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
7738c408004Sdan sqlite3OsShmBarrier(pWal->pDbFd);
7748c408004Sdan }
7758c408004Sdan }
7768c408004Sdan
777c438efd6Sdrh /*
7785a8cd2e4Sdrh ** Add the SQLITE_NO_TSAN as part of the return-type of a function
7795a8cd2e4Sdrh ** definition as a hint that the function contains constructs that
7805a8cd2e4Sdrh ** might give false-positive TSAN warnings.
7815a8cd2e4Sdrh **
7825a8cd2e4Sdrh ** See tag-20200519-1.
7835a8cd2e4Sdrh */
7845a8cd2e4Sdrh #if defined(__clang__) && !defined(SQLITE_NO_TSAN)
7855a8cd2e4Sdrh # define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
7865a8cd2e4Sdrh #else
7875a8cd2e4Sdrh # define SQLITE_NO_TSAN
7885a8cd2e4Sdrh #endif
7895a8cd2e4Sdrh
7905a8cd2e4Sdrh /*
7917e263728Sdrh ** Write the header information in pWal->hdr into the wal-index.
7927e263728Sdrh **
7937e263728Sdrh ** The checksum on pWal->hdr is updated before it is written.
7947ed91f23Sdrh */
walIndexWriteHdr(Wal * pWal)7955a8cd2e4Sdrh static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
7964280eb30Sdan volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
7974280eb30Sdan const int nCksum = offsetof(WalIndexHdr, aCksum);
79873b64e4dSdrh
79973b64e4dSdrh assert( pWal->writeLock );
8004b82c387Sdrh pWal->hdr.isInit = 1;
80110f5a50eSdan pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
8024280eb30Sdan walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
803f16cf653Sdrh /* Possible TSAN false-positive. See tag-20200519-1 */
804f6bff3f5Sdrh memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
8058c408004Sdan walShmBarrier(pWal);
806f6bff3f5Sdrh memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
807c438efd6Sdrh }
808c438efd6Sdrh
809c438efd6Sdrh /*
810c438efd6Sdrh ** This function encodes a single frame header and writes it to a buffer
8117ed91f23Sdrh ** supplied by the caller. A frame-header is made up of a series of
812c438efd6Sdrh ** 4-byte big-endian integers, as follows:
813c438efd6Sdrh **
81423ea97b6Sdrh ** 0: Page number.
81523ea97b6Sdrh ** 4: For commit records, the size of the database image in pages
81623ea97b6Sdrh ** after the commit. For all other records, zero.
8177e263728Sdrh ** 8: Salt-1 (copied from the wal-header)
8187e263728Sdrh ** 12: Salt-2 (copied from the wal-header)
81923ea97b6Sdrh ** 16: Checksum-1.
82023ea97b6Sdrh ** 20: Checksum-2.
821c438efd6Sdrh */
walEncodeFrame(Wal * pWal,u32 iPage,u32 nTruncate,u8 * aData,u8 * aFrame)8227ed91f23Sdrh static void walEncodeFrame(
82323ea97b6Sdrh Wal *pWal, /* The write-ahead log */
824c438efd6Sdrh u32 iPage, /* Database page number for frame */
825c438efd6Sdrh u32 nTruncate, /* New db size (or 0 for non-commit frames) */
8267e263728Sdrh u8 *aData, /* Pointer to page data */
827c438efd6Sdrh u8 *aFrame /* OUT: Write encoded frame here */
828c438efd6Sdrh ){
829b8fd6c2fSdan int nativeCksum; /* True for native byte-order checksums */
83071d89919Sdan u32 *aCksum = pWal->hdr.aFrameCksum;
83123ea97b6Sdrh assert( WAL_FRAME_HDRSIZE==24 );
832c438efd6Sdrh sqlite3Put4byte(&aFrame[0], iPage);
833c438efd6Sdrh sqlite3Put4byte(&aFrame[4], nTruncate);
834c9a9022bSdan if( pWal->iReCksum==0 ){
8357e263728Sdrh memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
836c438efd6Sdrh
837b8fd6c2fSdan nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
83871d89919Sdan walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
839b8fd6c2fSdan walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
840c438efd6Sdrh
84123ea97b6Sdrh sqlite3Put4byte(&aFrame[16], aCksum[0]);
84223ea97b6Sdrh sqlite3Put4byte(&aFrame[20], aCksum[1]);
843869aaf09Sdrh }else{
844869aaf09Sdrh memset(&aFrame[8], 0, 16);
845c438efd6Sdrh }
846c9a9022bSdan }
847c438efd6Sdrh
848c438efd6Sdrh /*
8497e263728Sdrh ** Check to see if the frame with header in aFrame[] and content
8507e263728Sdrh ** in aData[] is valid. If it is a valid frame, fill *piPage and
8517e263728Sdrh ** *pnTruncate and return true. Return if the frame is not valid.
852c438efd6Sdrh */
walDecodeFrame(Wal * pWal,u32 * piPage,u32 * pnTruncate,u8 * aData,u8 * aFrame)8537ed91f23Sdrh static int walDecodeFrame(
85423ea97b6Sdrh Wal *pWal, /* The write-ahead log */
855c438efd6Sdrh u32 *piPage, /* OUT: Database page number for frame */
856c438efd6Sdrh u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
857c438efd6Sdrh u8 *aData, /* Pointer to page data (for checksum) */
858c438efd6Sdrh u8 *aFrame /* Frame data */
859c438efd6Sdrh ){
860b8fd6c2fSdan int nativeCksum; /* True for native byte-order checksums */
86171d89919Sdan u32 *aCksum = pWal->hdr.aFrameCksum;
862c8179157Sdrh u32 pgno; /* Page number of the frame */
86323ea97b6Sdrh assert( WAL_FRAME_HDRSIZE==24 );
86423ea97b6Sdrh
8657e263728Sdrh /* A frame is only valid if the salt values in the frame-header
8667e263728Sdrh ** match the salt values in the wal-header.
8677e263728Sdrh */
8687e263728Sdrh if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
86923ea97b6Sdrh return 0;
87023ea97b6Sdrh }
871c438efd6Sdrh
872c8179157Sdrh /* A frame is only valid if the page number is creater than zero.
873c8179157Sdrh */
874c8179157Sdrh pgno = sqlite3Get4byte(&aFrame[0]);
875c8179157Sdrh if( pgno==0 ){
876c8179157Sdrh return 0;
877c8179157Sdrh }
878c8179157Sdrh
879519426aaSdrh /* A frame is only valid if a checksum of the WAL header,
880519426aaSdrh ** all prior frams, the first 16 bytes of this frame-header,
881519426aaSdrh ** and the frame-data matches the checksum in the last 8
882519426aaSdrh ** bytes of this frame-header.
8837e263728Sdrh */
884b8fd6c2fSdan nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
88571d89919Sdan walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
886b8fd6c2fSdan walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
88723ea97b6Sdrh if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
88823ea97b6Sdrh || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
889c438efd6Sdrh ){
890c438efd6Sdrh /* Checksum failed. */
891c438efd6Sdrh return 0;
892c438efd6Sdrh }
893c438efd6Sdrh
8947e263728Sdrh /* If we reach this point, the frame is valid. Return the page number
8957e263728Sdrh ** and the new database size.
8967e263728Sdrh */
897c8179157Sdrh *piPage = pgno;
898c438efd6Sdrh *pnTruncate = sqlite3Get4byte(&aFrame[4]);
899c438efd6Sdrh return 1;
900c438efd6Sdrh }
901c438efd6Sdrh
902c438efd6Sdrh
903c74c3334Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
904c74c3334Sdrh /*
905181e091fSdrh ** Names of locks. This routine is used to provide debugging output and is not
906181e091fSdrh ** a part of an ordinary build.
907c74c3334Sdrh */
walLockName(int lockIdx)908c74c3334Sdrh static const char *walLockName(int lockIdx){
909c74c3334Sdrh if( lockIdx==WAL_WRITE_LOCK ){
910c74c3334Sdrh return "WRITE-LOCK";
911c74c3334Sdrh }else if( lockIdx==WAL_CKPT_LOCK ){
912c74c3334Sdrh return "CKPT-LOCK";
913c74c3334Sdrh }else if( lockIdx==WAL_RECOVER_LOCK ){
914c74c3334Sdrh return "RECOVER-LOCK";
915c74c3334Sdrh }else{
916c74c3334Sdrh static char zName[15];
917c74c3334Sdrh sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
918c74c3334Sdrh lockIdx-WAL_READ_LOCK(0));
919c74c3334Sdrh return zName;
920c74c3334Sdrh }
921c74c3334Sdrh }
922c74c3334Sdrh #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
923c74c3334Sdrh
924c74c3334Sdrh
925c438efd6Sdrh /*
926181e091fSdrh ** Set or release locks on the WAL. Locks are either shared or exclusive.
927181e091fSdrh ** A lock cannot be moved directly between shared and exclusive - it must go
928181e091fSdrh ** through the unlocked state first.
92973b64e4dSdrh **
93073b64e4dSdrh ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
93173b64e4dSdrh */
walLockShared(Wal * pWal,int lockIdx)93273b64e4dSdrh static int walLockShared(Wal *pWal, int lockIdx){
933c74c3334Sdrh int rc;
93473b64e4dSdrh if( pWal->exclusiveMode ) return SQLITE_OK;
935c74c3334Sdrh rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
93673b64e4dSdrh SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
937c74c3334Sdrh WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
938c74c3334Sdrh walLockName(lockIdx), rc ? "failed" : "ok"));
9397bb8b8a4Sdan VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
940c74c3334Sdrh return rc;
94173b64e4dSdrh }
walUnlockShared(Wal * pWal,int lockIdx)94273b64e4dSdrh static void walUnlockShared(Wal *pWal, int lockIdx){
94373b64e4dSdrh if( pWal->exclusiveMode ) return;
94473b64e4dSdrh (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
94573b64e4dSdrh SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
946c74c3334Sdrh WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
94773b64e4dSdrh }
walLockExclusive(Wal * pWal,int lockIdx,int n)948ab372773Sdrh static int walLockExclusive(Wal *pWal, int lockIdx, int n){
949c74c3334Sdrh int rc;
95073b64e4dSdrh if( pWal->exclusiveMode ) return SQLITE_OK;
951c74c3334Sdrh rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
95273b64e4dSdrh SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
953c74c3334Sdrh WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
954c74c3334Sdrh walLockName(lockIdx), n, rc ? "failed" : "ok"));
9557bb8b8a4Sdan VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
956c74c3334Sdrh return rc;
95773b64e4dSdrh }
walUnlockExclusive(Wal * pWal,int lockIdx,int n)95873b64e4dSdrh static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
95973b64e4dSdrh if( pWal->exclusiveMode ) return;
96073b64e4dSdrh (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
96173b64e4dSdrh SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
962c74c3334Sdrh WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
963c74c3334Sdrh walLockName(lockIdx), n));
96473b64e4dSdrh }
96573b64e4dSdrh
96673b64e4dSdrh /*
96729d4dbefSdrh ** Compute a hash on a page number. The resulting hash value must land
968181e091fSdrh ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
969181e091fSdrh ** the hash to the next value in the event of a collision.
97029d4dbefSdrh */
walHash(u32 iPage)97129d4dbefSdrh static int walHash(u32 iPage){
97229d4dbefSdrh assert( iPage>0 );
97329d4dbefSdrh assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
97429d4dbefSdrh return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
97529d4dbefSdrh }
walNextHash(int iPriorHash)97629d4dbefSdrh static int walNextHash(int iPriorHash){
97729d4dbefSdrh return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
978bb23aff3Sdan }
979bb23aff3Sdan
9804280eb30Sdan /*
9814ece2f26Sdrh ** An instance of the WalHashLoc object is used to describe the location
9824ece2f26Sdrh ** of a page hash table in the wal-index. This becomes the return value
9834ece2f26Sdrh ** from walHashGet().
9844ece2f26Sdrh */
9854ece2f26Sdrh typedef struct WalHashLoc WalHashLoc;
9864ece2f26Sdrh struct WalHashLoc {
9874ece2f26Sdrh volatile ht_slot *aHash; /* Start of the wal-index hash table */
9884ece2f26Sdrh volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
9894ece2f26Sdrh u32 iZero; /* One less than the frame number of first indexed*/
9904ece2f26Sdrh };
9914ece2f26Sdrh
9924ece2f26Sdrh /*
9934280eb30Sdan ** Return pointers to the hash table and page number array stored on
9944280eb30Sdan ** page iHash of the wal-index. The wal-index is broken into 32KB pages
9954280eb30Sdan ** numbered starting from 0.
9964280eb30Sdan **
9974ece2f26Sdrh ** Set output variable pLoc->aHash to point to the start of the hash table
9984ece2f26Sdrh ** in the wal-index file. Set pLoc->iZero to one less than the frame
9994280eb30Sdan ** number of the first frame indexed by this hash table. If a
10004280eb30Sdan ** slot in the hash table is set to N, it refers to frame number
10014ece2f26Sdrh ** (pLoc->iZero+N) in the log.
10024280eb30Sdan **
100371c3ea75Sdrh ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
100471c3ea75Sdrh ** first frame indexed by the hash table, frame (pLoc->iZero).
10054280eb30Sdan */
walHashGet(Wal * pWal,int iHash,WalHashLoc * pLoc)10064280eb30Sdan static int walHashGet(
100713a3cb82Sdan Wal *pWal, /* WAL handle */
100813a3cb82Sdan int iHash, /* Find the iHash'th table */
10094ece2f26Sdrh WalHashLoc *pLoc /* OUT: Hash table location */
101013a3cb82Sdan ){
10114280eb30Sdan int rc; /* Return code */
10124280eb30Sdan
10134ece2f26Sdrh rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
10144280eb30Sdan assert( rc==SQLITE_OK || iHash>0 );
10154280eb30Sdan
1016eaad533eSdrh if( pLoc->aPgno ){
10174ece2f26Sdrh pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
101813a3cb82Sdan if( iHash==0 ){
10194ece2f26Sdrh pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
10204ece2f26Sdrh pLoc->iZero = 0;
102113a3cb82Sdan }else{
10224ece2f26Sdrh pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
102313a3cb82Sdan }
1024eaad533eSdrh }else if( NEVER(rc==SQLITE_OK) ){
1025eaad533eSdrh rc = SQLITE_ERROR;
102613a3cb82Sdan }
10274280eb30Sdan return rc;
10284280eb30Sdan }
102913a3cb82Sdan
10304280eb30Sdan /*
10314280eb30Sdan ** Return the number of the wal-index page that contains the hash-table
10324280eb30Sdan ** and page-number array that contain entries corresponding to WAL frame
10334280eb30Sdan ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
10344280eb30Sdan ** are numbered starting from 0.
10354280eb30Sdan */
walFramePage(u32 iFrame)103613a3cb82Sdan static int walFramePage(u32 iFrame){
103713a3cb82Sdan int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
103813a3cb82Sdan assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
103913a3cb82Sdan && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
104013a3cb82Sdan && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
104113a3cb82Sdan && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
104213a3cb82Sdan && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
104313a3cb82Sdan );
10448deae5adSdrh assert( iHash>=0 );
104513a3cb82Sdan return iHash;
104613a3cb82Sdan }
104713a3cb82Sdan
104813a3cb82Sdan /*
104913a3cb82Sdan ** Return the page number associated with frame iFrame in this WAL.
105013a3cb82Sdan */
walFramePgno(Wal * pWal,u32 iFrame)105113a3cb82Sdan static u32 walFramePgno(Wal *pWal, u32 iFrame){
105213a3cb82Sdan int iHash = walFramePage(iFrame);
105313a3cb82Sdan if( iHash==0 ){
105413a3cb82Sdan return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
105513a3cb82Sdan }
105613a3cb82Sdan return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
105713a3cb82Sdan }
1058bb23aff3Sdan
1059bb23aff3Sdan /*
1060ca6b5babSdan ** Remove entries from the hash table that point to WAL slots greater
1061ca6b5babSdan ** than pWal->hdr.mxFrame.
1062ca6b5babSdan **
1063ca6b5babSdan ** This function is called whenever pWal->hdr.mxFrame is decreased due
1064ca6b5babSdan ** to a rollback or savepoint.
1065ca6b5babSdan **
1066181e091fSdrh ** At most only the hash table containing pWal->hdr.mxFrame needs to be
1067181e091fSdrh ** updated. Any later hash tables will be automatically cleared when
1068181e091fSdrh ** pWal->hdr.mxFrame advances to the point where those hash tables are
1069181e091fSdrh ** actually needed.
1070ca6b5babSdan */
walCleanupHash(Wal * pWal)1071ca6b5babSdan static void walCleanupHash(Wal *pWal){
10724ece2f26Sdrh WalHashLoc sLoc; /* Hash table location */
1073f77bbd9fSdrh int iLimit = 0; /* Zero values greater than this */
107413a3cb82Sdan int nByte; /* Number of bytes to zero in aPgno[] */
107513a3cb82Sdan int i; /* Used to iterate through aHash[] */
1076ca6b5babSdan
107773b64e4dSdrh assert( pWal->writeLock );
1078ffca4301Sdrh testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
1079ffca4301Sdrh testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
1080ffca4301Sdrh testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
10819c156477Sdrh
10824280eb30Sdan if( pWal->hdr.mxFrame==0 ) return;
10834280eb30Sdan
10844280eb30Sdan /* Obtain pointers to the hash-table and page-number array containing
10854280eb30Sdan ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
1086b92d7d26Sdrh ** that the page said hash-table and array reside on is already mapped.(1)
10874280eb30Sdan */
10884280eb30Sdan assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
10894280eb30Sdan assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
10900449f656Sdrh i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
10910449f656Sdrh if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
10924280eb30Sdan
10934280eb30Sdan /* Zero all hash-table entries that correspond to frame numbers greater
10944280eb30Sdan ** than pWal->hdr.mxFrame.
10954280eb30Sdan */
10964ece2f26Sdrh iLimit = pWal->hdr.mxFrame - sLoc.iZero;
10979c156477Sdrh assert( iLimit>0 );
1098ca6b5babSdan for(i=0; i<HASHTABLE_NSLOT; i++){
10994ece2f26Sdrh if( sLoc.aHash[i]>iLimit ){
11004ece2f26Sdrh sLoc.aHash[i] = 0;
1101ca6b5babSdan }
1102ca6b5babSdan }
1103ca6b5babSdan
1104ca6b5babSdan /* Zero the entries in the aPgno array that correspond to frames with
1105ca6b5babSdan ** frame numbers greater than pWal->hdr.mxFrame.
1106ca6b5babSdan */
110771c3ea75Sdrh nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
110871c3ea75Sdrh assert( nByte>=0 );
110971c3ea75Sdrh memset((void *)&sLoc.aPgno[iLimit], 0, nByte);
1110ca6b5babSdan
1111ca6b5babSdan #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
1112ca6b5babSdan /* Verify that the every entry in the mapping region is still reachable
1113ca6b5babSdan ** via the hash table even after the cleanup.
1114ca6b5babSdan */
1115f77bbd9fSdrh if( iLimit ){
11166b67a8aeSmistachkin int j; /* Loop counter */
1117ca6b5babSdan int iKey; /* Hash key */
111871c3ea75Sdrh for(j=0; j<iLimit; j++){
11194ece2f26Sdrh for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
112071c3ea75Sdrh if( sLoc.aHash[iKey]==j+1 ) break;
1121ca6b5babSdan }
112271c3ea75Sdrh assert( sLoc.aHash[iKey]==j+1 );
1123ca6b5babSdan }
1124ca6b5babSdan }
1125ca6b5babSdan #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
1126ca6b5babSdan }
1127ca6b5babSdan
1128bb23aff3Sdan
11297ed91f23Sdrh /*
113029d4dbefSdrh ** Set an entry in the wal-index that will map database page number
113129d4dbefSdrh ** pPage into WAL frame iFrame.
1132c438efd6Sdrh */
walIndexAppend(Wal * pWal,u32 iFrame,u32 iPage)11337ed91f23Sdrh static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
11344280eb30Sdan int rc; /* Return code */
11354ece2f26Sdrh WalHashLoc sLoc; /* Wal-index hash table location */
11364280eb30Sdan
11374ece2f26Sdrh rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
11384280eb30Sdan
11394280eb30Sdan /* Assuming the wal-index file was successfully mapped, populate the
11404280eb30Sdan ** page number array and hash table entry.
11414280eb30Sdan */
1142e7f3edcdSdrh if( rc==SQLITE_OK ){
11434280eb30Sdan int iKey; /* Hash table key */
1144bb23aff3Sdan int idx; /* Value to write to hash-table slot */
1145519426aaSdrh int nCollide; /* Number of hash collisions */
1146c438efd6Sdrh
11474ece2f26Sdrh idx = iFrame - sLoc.iZero;
11484280eb30Sdan assert( idx <= HASHTABLE_NSLOT/2 + 1 );
11494280eb30Sdan
11504280eb30Sdan /* If this is the first entry to be added to this hash-table, zero the
115160ec914cSpeter.d.reid ** entire hash table and aPgno[] array before proceeding.
11524280eb30Sdan */
1153ca6b5babSdan if( idx==1 ){
115471c3ea75Sdrh int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
115571c3ea75Sdrh assert( nByte>=0 );
115671c3ea75Sdrh memset((void*)sLoc.aPgno, 0, nByte);
1157ca6b5babSdan }
1158ca6b5babSdan
1159ca6b5babSdan /* If the entry in aPgno[] is already set, then the previous writer
1160ca6b5babSdan ** must have exited unexpectedly in the middle of a transaction (after
1161ca6b5babSdan ** writing one or more dirty pages to the WAL to free up memory).
1162ca6b5babSdan ** Remove the remnants of that writers uncommitted transaction from
1163ca6b5babSdan ** the hash-table before writing any new entries.
1164ca6b5babSdan */
116571c3ea75Sdrh if( sLoc.aPgno[idx-1] ){
1166ca6b5babSdan walCleanupHash(pWal);
116771c3ea75Sdrh assert( !sLoc.aPgno[idx-1] );
1168ca6b5babSdan }
11694280eb30Sdan
11704280eb30Sdan /* Write the aPgno[] array entry and the hash-table slot. */
1171519426aaSdrh nCollide = idx;
11724ece2f26Sdrh for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
1173519426aaSdrh if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
117429d4dbefSdrh }
117571c3ea75Sdrh sLoc.aPgno[idx-1] = iPage;
1176ec206a7dSdan AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
11774fa95bfcSdrh
11784fa95bfcSdrh #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11794fa95bfcSdrh /* Verify that the number of entries in the hash table exactly equals
11804fa95bfcSdrh ** the number of entries in the mapping region.
11814fa95bfcSdrh */
11824fa95bfcSdrh {
11834fa95bfcSdrh int i; /* Loop counter */
11844fa95bfcSdrh int nEntry = 0; /* Number of entries in the hash table */
11854ece2f26Sdrh for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
11864fa95bfcSdrh assert( nEntry==idx );
1187c438efd6Sdrh }
118831f98fc8Sdan
11894fa95bfcSdrh /* Verify that the every entry in the mapping region is reachable
11904fa95bfcSdrh ** via the hash table. This turns out to be a really, really expensive
11914fa95bfcSdrh ** thing to check, so only do this occasionally - not on every
11924fa95bfcSdrh ** iteration.
11934fa95bfcSdrh */
11944fa95bfcSdrh if( (idx&0x3ff)==0 ){
11954fa95bfcSdrh int i; /* Loop counter */
119671c3ea75Sdrh for(i=0; i<idx; i++){
11974ece2f26Sdrh for(iKey=walHash(sLoc.aPgno[i]);
11984ece2f26Sdrh sLoc.aHash[iKey];
11994ece2f26Sdrh iKey=walNextHash(iKey)){
120071c3ea75Sdrh if( sLoc.aHash[iKey]==i+1 ) break;
12014fa95bfcSdrh }
120271c3ea75Sdrh assert( sLoc.aHash[iKey]==i+1 );
12034fa95bfcSdrh }
12044fa95bfcSdrh }
12054fa95bfcSdrh #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
12064fa95bfcSdrh }
12074fa95bfcSdrh
1208bb23aff3Sdan return rc;
1209c438efd6Sdrh }
1210c438efd6Sdrh
1211c438efd6Sdrh
1212c438efd6Sdrh /*
12137ed91f23Sdrh ** Recover the wal-index by reading the write-ahead log file.
121473b64e4dSdrh **
121573b64e4dSdrh ** This routine first tries to establish an exclusive lock on the
121673b64e4dSdrh ** wal-index to prevent other threads/processes from doing anything
121773b64e4dSdrh ** with the WAL or wal-index while recovery is running. The
121873b64e4dSdrh ** WAL_RECOVER_LOCK is also held so that other threads will know
121973b64e4dSdrh ** that this thread is running recovery. If unable to establish
122073b64e4dSdrh ** the necessary locks, this routine returns SQLITE_BUSY.
1221c438efd6Sdrh */
walIndexRecover(Wal * pWal)12227ed91f23Sdrh static int walIndexRecover(Wal *pWal){
1223c438efd6Sdrh int rc; /* Return Code */
1224c438efd6Sdrh i64 nSize; /* Size of log file */
122571d89919Sdan u32 aFrameCksum[2] = {0, 0};
1226d0aa3427Sdan int iLock; /* Lock offset to lock for checkpoint */
1227c438efd6Sdrh
1228d0aa3427Sdan /* Obtain an exclusive lock on all byte in the locking range not already
1229d0aa3427Sdan ** locked by the caller. The caller is guaranteed to have locked the
1230d0aa3427Sdan ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
1231d0aa3427Sdan ** If successful, the same bytes that are locked here are unlocked before
1232d0aa3427Sdan ** this function returns.
1233d0aa3427Sdan */
1234d0aa3427Sdan assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
1235d0aa3427Sdan assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
1236d0aa3427Sdan assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
1237d0aa3427Sdan assert( pWal->writeLock );
1238d0aa3427Sdan iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
1239dea5ce36Sdan rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
124073b64e4dSdrh if( rc ){
124173b64e4dSdrh return rc;
124273b64e4dSdrh }
1243dea5ce36Sdan
1244c74c3334Sdrh WALTRACE(("WAL%p: recovery begin...\n", pWal));
124573b64e4dSdrh
124671d89919Sdan memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
1247c438efd6Sdrh
1248d9e5c4f6Sdrh rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
1249c438efd6Sdrh if( rc!=SQLITE_OK ){
125073b64e4dSdrh goto recovery_error;
1251c438efd6Sdrh }
1252c438efd6Sdrh
1253b8fd6c2fSdan if( nSize>WAL_HDRSIZE ){
1254b8fd6c2fSdan u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
1255d3e38b7cSdan u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */
1256c438efd6Sdrh u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
1257584c754dSdrh int szFrame; /* Number of bytes in buffer aFrame[] */
1258c438efd6Sdrh u8 *aData; /* Pointer to data part of aFrame buffer */
12596e81096fSdrh int szPage; /* Page size according to the log */
1260b8fd6c2fSdan u32 magic; /* Magic value read from WAL header */
126110f5a50eSdan u32 version; /* Magic value read from WAL header */
1262fe6163d7Sdrh int isValid; /* True if this frame is valid */
12638deae5adSdrh u32 iPg; /* Current 32KB wal-index page */
12648deae5adSdrh u32 iLastFrame; /* Last frame in wal, based on nSize alone */
1265c438efd6Sdrh
1266b8fd6c2fSdan /* Read in the WAL header. */
1267d9e5c4f6Sdrh rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
1268c438efd6Sdrh if( rc!=SQLITE_OK ){
126973b64e4dSdrh goto recovery_error;
1270c438efd6Sdrh }
1271c438efd6Sdrh
1272c438efd6Sdrh /* If the database page size is not a power of two, or is greater than
1273b8fd6c2fSdan ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
1274b8fd6c2fSdan ** data. Similarly, if the 'magic' value is invalid, ignore the whole
1275b8fd6c2fSdan ** WAL file.
1276c438efd6Sdrh */
1277b8fd6c2fSdan magic = sqlite3Get4byte(&aBuf[0]);
127823ea97b6Sdrh szPage = sqlite3Get4byte(&aBuf[8]);
1279b8fd6c2fSdan if( (magic&0xFFFFFFFE)!=WAL_MAGIC
1280b8fd6c2fSdan || szPage&(szPage-1)
1281b8fd6c2fSdan || szPage>SQLITE_MAX_PAGE_SIZE
1282b8fd6c2fSdan || szPage<512
1283b8fd6c2fSdan ){
1284c438efd6Sdrh goto finished;
1285c438efd6Sdrh }
12865eba1f60Sshaneh pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
1287b2eced5dSdrh pWal->szPage = szPage;
128823ea97b6Sdrh pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
12897e263728Sdrh memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
1290cd28508eSdrh
1291cd28508eSdrh /* Verify that the WAL header checksum is correct */
129271d89919Sdan walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
129310f5a50eSdan aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
129471d89919Sdan );
129510f5a50eSdan if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
129610f5a50eSdan || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
129710f5a50eSdan ){
129810f5a50eSdan goto finished;
129910f5a50eSdan }
130010f5a50eSdan
1301cd28508eSdrh /* Verify that the version number on the WAL format is one that
1302cd28508eSdrh ** are able to understand */
130310f5a50eSdan version = sqlite3Get4byte(&aBuf[4]);
130410f5a50eSdan if( version!=WAL_MAX_VERSION ){
130510f5a50eSdan rc = SQLITE_CANTOPEN_BKPT;
130610f5a50eSdan goto finished;
130710f5a50eSdan }
130810f5a50eSdan
1309c438efd6Sdrh /* Malloc a buffer to read frames into. */
1310584c754dSdrh szFrame = szPage + WAL_FRAME_HDRSIZE;
1311d3e38b7cSdan aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ);
1312c438efd6Sdrh if( !aFrame ){
1313fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT;
131473b64e4dSdrh goto recovery_error;
1315c438efd6Sdrh }
13167ed91f23Sdrh aData = &aFrame[WAL_FRAME_HDRSIZE];
1317d3e38b7cSdan aPrivate = (u32*)&aData[szPage];
1318c438efd6Sdrh
1319c438efd6Sdrh /* Read all frames from the log file. */
1320d3e38b7cSdan iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
13218deae5adSdrh for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
1322d3e38b7cSdan u32 *aShare;
13238deae5adSdrh u32 iFrame; /* Index of last frame read */
13248deae5adSdrh u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
13258deae5adSdrh u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
13268deae5adSdrh u32 nHdr, nHdr32;
1327d3e38b7cSdan rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
1328eaad533eSdrh assert( aShare!=0 || rc!=SQLITE_OK );
1329eaad533eSdrh if( aShare==0 ) break;
1330d3e38b7cSdan pWal->apWiData[iPg] = aPrivate;
1331d3e38b7cSdan
1332d3e38b7cSdan for(iFrame=iFirst; iFrame<=iLast; iFrame++){
1333d3e38b7cSdan i64 iOffset = walFrameOffset(iFrame, szPage);
1334c438efd6Sdrh u32 pgno; /* Database page number for frame */
1335c438efd6Sdrh u32 nTruncate; /* dbsize field from frame header */
1336c438efd6Sdrh
1337c438efd6Sdrh /* Read and decode the next log frame. */
1338584c754dSdrh rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
1339c438efd6Sdrh if( rc!=SQLITE_OK ) break;
13407e263728Sdrh isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
1341f694aa64Sdrh if( !isValid ) break;
1342fe6163d7Sdrh rc = walIndexAppend(pWal, iFrame, pgno);
1343f31230afSdrh if( NEVER(rc!=SQLITE_OK) ) break;
1344c438efd6Sdrh
1345c438efd6Sdrh /* If nTruncate is non-zero, this is a commit record. */
1346c438efd6Sdrh if( nTruncate ){
134771d89919Sdan pWal->hdr.mxFrame = iFrame;
134871d89919Sdan pWal->hdr.nPage = nTruncate;
13491df2db7fSshaneh pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
13509b78f791Sdrh testcase( szPage<=32768 );
13519b78f791Sdrh testcase( szPage>=65536 );
135271d89919Sdan aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
135371d89919Sdan aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
1354c438efd6Sdrh }
1355c438efd6Sdrh }
1356d3e38b7cSdan pWal->apWiData[iPg] = aShare;
1357f31230afSdrh nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
1358f31230afSdrh nHdr32 = nHdr / sizeof(u32);
1359e592c18cSdrh #ifndef SQLITE_SAFER_WALINDEX_RECOVERY
1360e592c18cSdrh /* Memcpy() should work fine here, on all reasonable implementations.
1361e592c18cSdrh ** Technically, memcpy() might change the destination to some
1362e592c18cSdrh ** intermediate value before setting to the final value, and that might
1363e592c18cSdrh ** cause a concurrent reader to malfunction. Memcpy() is allowed to
1364e592c18cSdrh ** do that, according to the spec, but no memcpy() implementation that
1365e592c18cSdrh ** we know of actually does that, which is why we say that memcpy()
1366e592c18cSdrh ** is safe for this. Memcpy() is certainly a lot faster.
1367e592c18cSdrh */
1368d3e38b7cSdan memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
1369e592c18cSdrh #else
1370e592c18cSdrh /* In the event that some platform is found for which memcpy()
1371e592c18cSdrh ** changes the destination to some intermediate value before
1372e592c18cSdrh ** setting the final value, this alternative copy routine is
1373e592c18cSdrh ** provided.
1374e592c18cSdrh */
1375e592c18cSdrh {
1376e592c18cSdrh int i;
1377e592c18cSdrh for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
1378e592c18cSdrh if( aShare[i]!=aPrivate[i] ){
1379e592c18cSdrh /* Atomic memory operations are not required here because if
1380e592c18cSdrh ** the value needs to be changed, that means it is not being
1381e592c18cSdrh ** accessed concurrently. */
1382e592c18cSdrh aShare[i] = aPrivate[i];
1383e592c18cSdrh }
1384e592c18cSdrh }
1385e592c18cSdrh }
1386e592c18cSdrh #endif
1387d3e38b7cSdan if( iFrame<=iLast ) break;
1388d3e38b7cSdan }
1389c438efd6Sdrh
1390c438efd6Sdrh sqlite3_free(aFrame);
1391c438efd6Sdrh }
1392c438efd6Sdrh
1393c438efd6Sdrh finished:
1394576bc329Sdan if( rc==SQLITE_OK ){
1395db7f647eSdrh volatile WalCkptInfo *pInfo;
1396db7f647eSdrh int i;
139771d89919Sdan pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
139871d89919Sdan pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
13997e263728Sdrh walIndexWriteHdr(pWal);
14003dee6da9Sdan
1401db7f647eSdrh /* Reset the checkpoint-header. This is safe because this thread is
1402d3e38b7cSdan ** currently holding locks that exclude all other writers and
1403d3e38b7cSdan ** checkpointers. Then set the values of read-mark slots 1 through N.
14043dee6da9Sdan */
1405db7f647eSdrh pInfo = walCkptInfo(pWal);
1406db7f647eSdrh pInfo->nBackfill = 0;
14073bf83ccdSdan pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
1408db7f647eSdrh pInfo->aReadMark[0] = 0;
1409d3e38b7cSdan for(i=1; i<WAL_NREADER; i++){
1410d3e38b7cSdan rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
1411d3e38b7cSdan if( rc==SQLITE_OK ){
1412d3e38b7cSdan if( i==1 && pWal->hdr.mxFrame ){
1413d3e38b7cSdan pInfo->aReadMark[i] = pWal->hdr.mxFrame;
1414d3e38b7cSdan }else{
1415d3e38b7cSdan pInfo->aReadMark[i] = READMARK_NOT_USED;
1416d3e38b7cSdan }
1417d3e38b7cSdan walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
14188caebb26Sdrh }else if( rc!=SQLITE_BUSY ){
14198caebb26Sdrh goto recovery_error;
1420d3e38b7cSdan }
1421d3e38b7cSdan }
1422eb8763d7Sdan
1423eb8763d7Sdan /* If more than one frame was recovered from the log file, report an
1424eb8763d7Sdan ** event via sqlite3_log(). This is to help with identifying performance
1425eb8763d7Sdan ** problems caused by applications routinely shutting down without
1426eb8763d7Sdan ** checkpointing the log file.
1427eb8763d7Sdan */
1428eb8763d7Sdan if( pWal->hdr.nPage ){
1429d040e764Sdrh sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
1430d040e764Sdrh "recovered %d frames from WAL file %s",
14310943f0bdSdan pWal->hdr.mxFrame, pWal->zWalName
1432eb8763d7Sdan );
1433eb8763d7Sdan }
1434576bc329Sdan }
143573b64e4dSdrh
143673b64e4dSdrh recovery_error:
1437c74c3334Sdrh WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
1438dea5ce36Sdan walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
1439c438efd6Sdrh return rc;
1440c438efd6Sdrh }
1441c438efd6Sdrh
1442c438efd6Sdrh /*
14431018e90bSdan ** Close an open wal-index.
1444a8e654ebSdrh */
walIndexClose(Wal * pWal,int isDelete)14451018e90bSdan static void walIndexClose(Wal *pWal, int isDelete){
144685bc6df2Sdrh if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
14478c408004Sdan int i;
14488c408004Sdan for(i=0; i<pWal->nWiData; i++){
14498c408004Sdan sqlite3_free((void *)pWal->apWiData[i]);
14508c408004Sdan pWal->apWiData[i] = 0;
14518c408004Sdan }
145211caf4f4Sdan }
145311caf4f4Sdan if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
1454e11fedc5Sdrh sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
1455a8e654ebSdrh }
14568c408004Sdan }
1457a8e654ebSdrh
1458a8e654ebSdrh /*
14593e875ef3Sdan ** Open a connection to the WAL file zWalName. The database file must
14603e875ef3Sdan ** already be opened on connection pDbFd. The buffer that zWalName points
14613e875ef3Sdan ** to must remain valid for the lifetime of the returned Wal* handle.
1462c438efd6Sdrh **
1463c438efd6Sdrh ** A SHARED lock should be held on the database file when this function
1464c438efd6Sdrh ** is called. The purpose of this SHARED lock is to prevent any other
1465181e091fSdrh ** client from unlinking the WAL or wal-index file. If another process
1466c438efd6Sdrh ** were to do this just after this client opened one of these files, the
1467c438efd6Sdrh ** system would be badly broken.
1468ef378025Sdan **
1469ef378025Sdan ** If the log file is successfully opened, SQLITE_OK is returned and
1470ef378025Sdan ** *ppWal is set to point to a new WAL handle. If an error occurs,
1471ef378025Sdan ** an SQLite error code is returned and *ppWal is left unmodified.
1472c438efd6Sdrh */
sqlite3WalOpen(sqlite3_vfs * pVfs,sqlite3_file * pDbFd,const char * zWalName,int bNoShm,i64 mxWalSize,Wal ** ppWal)1473c438efd6Sdrh int sqlite3WalOpen(
14747ed91f23Sdrh sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
1475d9e5c4f6Sdrh sqlite3_file *pDbFd, /* The open database file */
14763e875ef3Sdan const char *zWalName, /* Name of the WAL file */
14778c408004Sdan int bNoShm, /* True to run in heap-memory mode */
147885a83755Sdrh i64 mxWalSize, /* Truncate WAL to this size on reset */
14797ed91f23Sdrh Wal **ppWal /* OUT: Allocated Wal handle */
1480c438efd6Sdrh ){
1481ef378025Sdan int rc; /* Return Code */
14827ed91f23Sdrh Wal *pRet; /* Object to allocate and return */
1483c438efd6Sdrh int flags; /* Flags passed to OsOpen() */
1484c438efd6Sdrh
14853e875ef3Sdan assert( zWalName && zWalName[0] );
1486d9e5c4f6Sdrh assert( pDbFd );
1487c438efd6Sdrh
1488fd4c7862Sdrh /* Verify the values of various constants. Any changes to the values
1489fd4c7862Sdrh ** of these constants would result in an incompatible on-disk format
1490fd4c7862Sdrh ** for the -shm file. Any change that causes one of these asserts to
1491fd4c7862Sdrh ** fail is a backward compatibility problem, even if the change otherwise
1492fd4c7862Sdrh ** works.
1493fd4c7862Sdrh **
1494fd4c7862Sdrh ** This table also serves as a helpful cross-reference when trying to
1495fd4c7862Sdrh ** interpret hex dumps of the -shm file.
1496fd4c7862Sdrh */
1497fd4c7862Sdrh assert( 48 == sizeof(WalIndexHdr) );
1498fd4c7862Sdrh assert( 40 == sizeof(WalCkptInfo) );
1499fd4c7862Sdrh assert( 120 == WALINDEX_LOCK_OFFSET );
1500fd4c7862Sdrh assert( 136 == WALINDEX_HDR_SIZE );
1501fd4c7862Sdrh assert( 4096 == HASHTABLE_NPAGE );
1502fd4c7862Sdrh assert( 4062 == HASHTABLE_NPAGE_ONE );
1503fd4c7862Sdrh assert( 8192 == HASHTABLE_NSLOT );
1504fd4c7862Sdrh assert( 383 == HASHTABLE_HASH_1 );
1505fd4c7862Sdrh assert( 32768 == WALINDEX_PGSZ );
1506fd4c7862Sdrh assert( 8 == SQLITE_SHM_NLOCK );
1507fd4c7862Sdrh assert( 5 == WAL_NREADER );
1508944d85dfSdrh assert( 24 == WAL_FRAME_HDRSIZE );
1509944d85dfSdrh assert( 32 == WAL_HDRSIZE );
1510fd4c7862Sdrh assert( 120 == WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK );
1511fd4c7862Sdrh assert( 121 == WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK );
1512fd4c7862Sdrh assert( 122 == WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK );
1513fd4c7862Sdrh assert( 123 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) );
1514fd4c7862Sdrh assert( 124 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) );
1515fd4c7862Sdrh assert( 125 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) );
1516fd4c7862Sdrh assert( 126 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) );
1517fd4c7862Sdrh assert( 127 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) );
1518fd4c7862Sdrh
15191b78eaf0Sdrh /* In the amalgamation, the os_unix.c and os_win.c source files come before
15201b78eaf0Sdrh ** this source file. Verify that the #defines of the locking byte offsets
15211b78eaf0Sdrh ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
1522998147ecSdrh ** For that matter, if the lock offset ever changes from its initial design
1523998147ecSdrh ** value of 120, we need to know that so there is an assert() to check it.
15241b78eaf0Sdrh */
15251b78eaf0Sdrh #ifdef WIN_SHM_BASE
15261b78eaf0Sdrh assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
15271b78eaf0Sdrh #endif
15281b78eaf0Sdrh #ifdef UNIX_SHM_BASE
15291b78eaf0Sdrh assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
15301b78eaf0Sdrh #endif
15311b78eaf0Sdrh
15321b78eaf0Sdrh
15337ed91f23Sdrh /* Allocate an instance of struct Wal to return. */
15347ed91f23Sdrh *ppWal = 0;
15353e875ef3Sdan pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
153676ed3bc0Sdan if( !pRet ){
1537fad3039cSmistachkin return SQLITE_NOMEM_BKPT;
153876ed3bc0Sdan }
153976ed3bc0Sdan
1540c438efd6Sdrh pRet->pVfs = pVfs;
1541d9e5c4f6Sdrh pRet->pWalFd = (sqlite3_file *)&pRet[1];
1542d9e5c4f6Sdrh pRet->pDbFd = pDbFd;
154373b64e4dSdrh pRet->readLock = -1;
154485a83755Sdrh pRet->mxWalSize = mxWalSize;
15453e875ef3Sdan pRet->zWalName = zWalName;
1546d992b150Sdrh pRet->syncHeader = 1;
1547374f4a04Sdrh pRet->padToSectorBoundary = 1;
15488c408004Sdan pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
1549c438efd6Sdrh
15507ed91f23Sdrh /* Open file handle on the write-ahead log file. */
1551ddb0ac4bSdan flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
15523e875ef3Sdan rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
155350833e32Sdan if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
155466dfec8bSdrh pRet->readOnly = WAL_RDONLY;
155550833e32Sdan }
1556c438efd6Sdrh
1557c438efd6Sdrh if( rc!=SQLITE_OK ){
15581018e90bSdan walIndexClose(pRet, 0);
1559d9e5c4f6Sdrh sqlite3OsClose(pRet->pWalFd);
1560c438efd6Sdrh sqlite3_free(pRet);
1561ef378025Sdan }else{
1562dd973548Sdan int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
1563d992b150Sdrh if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
1564cb15f35fSdrh if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
1565cb15f35fSdrh pRet->padToSectorBoundary = 0;
1566cb15f35fSdrh }
15677ed91f23Sdrh *ppWal = pRet;
1568c74c3334Sdrh WALTRACE(("WAL%d: opened\n", pRet));
1569ef378025Sdan }
1570c438efd6Sdrh return rc;
1571c438efd6Sdrh }
1572c438efd6Sdrh
1573a2a42013Sdrh /*
157485a83755Sdrh ** Change the size to which the WAL file is trucated on each reset.
157585a83755Sdrh */
sqlite3WalLimit(Wal * pWal,i64 iLimit)157685a83755Sdrh void sqlite3WalLimit(Wal *pWal, i64 iLimit){
157785a83755Sdrh if( pWal ) pWal->mxWalSize = iLimit;
157885a83755Sdrh }
157985a83755Sdrh
158085a83755Sdrh /*
1581a2a42013Sdrh ** Find the smallest page number out of all pages held in the WAL that
1582a2a42013Sdrh ** has not been returned by any prior invocation of this method on the
1583a2a42013Sdrh ** same WalIterator object. Write into *piFrame the frame index where
1584a2a42013Sdrh ** that page was last written into the WAL. Write into *piPage the page
1585a2a42013Sdrh ** number.
1586a2a42013Sdrh **
1587a2a42013Sdrh ** Return 0 on success. If there are no pages in the WAL with a page
1588a2a42013Sdrh ** number larger than *piPage, then return 1.
1589a2a42013Sdrh */
walIteratorNext(WalIterator * p,u32 * piPage,u32 * piFrame)15907ed91f23Sdrh static int walIteratorNext(
15917ed91f23Sdrh WalIterator *p, /* Iterator */
1592a2a42013Sdrh u32 *piPage, /* OUT: The page number of the next page */
1593a2a42013Sdrh u32 *piFrame /* OUT: Wal frame index of next page */
1594c438efd6Sdrh ){
1595a2a42013Sdrh u32 iMin; /* Result pgno must be greater than iMin */
1596a2a42013Sdrh u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
1597a2a42013Sdrh int i; /* For looping through segments */
1598c438efd6Sdrh
1599a2a42013Sdrh iMin = p->iPrior;
1600a2a42013Sdrh assert( iMin<0xffffffff );
1601c438efd6Sdrh for(i=p->nSegment-1; i>=0; i--){
16027ed91f23Sdrh struct WalSegment *pSegment = &p->aSegment[i];
160313a3cb82Sdan while( pSegment->iNext<pSegment->nEntry ){
1604a2a42013Sdrh u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
1605c438efd6Sdrh if( iPg>iMin ){
1606c438efd6Sdrh if( iPg<iRet ){
1607c438efd6Sdrh iRet = iPg;
160813a3cb82Sdan *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
1609c438efd6Sdrh }
1610c438efd6Sdrh break;
1611c438efd6Sdrh }
1612c438efd6Sdrh pSegment->iNext++;
1613c438efd6Sdrh }
1614c438efd6Sdrh }
1615c438efd6Sdrh
1616a2a42013Sdrh *piPage = p->iPrior = iRet;
1617c438efd6Sdrh return (iRet==0xFFFFFFFF);
1618c438efd6Sdrh }
1619c438efd6Sdrh
1620f544b4c4Sdan /*
1621f544b4c4Sdan ** This function merges two sorted lists into a single sorted list.
1622d9c9b78eSdrh **
1623d9c9b78eSdrh ** aLeft[] and aRight[] are arrays of indices. The sort key is
1624d9c9b78eSdrh ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
1625d9c9b78eSdrh ** is guaranteed for all J<K:
1626d9c9b78eSdrh **
1627d9c9b78eSdrh ** aContent[aLeft[J]] < aContent[aLeft[K]]
1628d9c9b78eSdrh ** aContent[aRight[J]] < aContent[aRight[K]]
1629d9c9b78eSdrh **
1630d9c9b78eSdrh ** This routine overwrites aRight[] with a new (probably longer) sequence
1631d9c9b78eSdrh ** of indices such that the aRight[] contains every index that appears in
1632d9c9b78eSdrh ** either aLeft[] or the old aRight[] and such that the second condition
1633d9c9b78eSdrh ** above is still met.
1634d9c9b78eSdrh **
1635d9c9b78eSdrh ** The aContent[aLeft[X]] values will be unique for all X. And the
1636d9c9b78eSdrh ** aContent[aRight[X]] values will be unique too. But there might be
1637d9c9b78eSdrh ** one or more combinations of X and Y such that
1638d9c9b78eSdrh **
1639d9c9b78eSdrh ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
1640d9c9b78eSdrh **
1641d9c9b78eSdrh ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
1642f544b4c4Sdan */
walMerge(const u32 * aContent,ht_slot * aLeft,int nLeft,ht_slot ** paRight,int * pnRight,ht_slot * aTmp)1643f544b4c4Sdan static void walMerge(
1644d9c9b78eSdrh const u32 *aContent, /* Pages in wal - keys for the sort */
1645f544b4c4Sdan ht_slot *aLeft, /* IN: Left hand input list */
1646f544b4c4Sdan int nLeft, /* IN: Elements in array *paLeft */
1647f544b4c4Sdan ht_slot **paRight, /* IN/OUT: Right hand input list */
1648f544b4c4Sdan int *pnRight, /* IN/OUT: Elements in *paRight */
1649f544b4c4Sdan ht_slot *aTmp /* Temporary buffer */
1650a2a42013Sdrh ){
1651a2a42013Sdrh int iLeft = 0; /* Current index in aLeft */
1652f544b4c4Sdan int iRight = 0; /* Current index in aRight */
1653a2a42013Sdrh int iOut = 0; /* Current index in output buffer */
1654f544b4c4Sdan int nRight = *pnRight;
1655f544b4c4Sdan ht_slot *aRight = *paRight;
1656a2a42013Sdrh
1657f544b4c4Sdan assert( nLeft>0 && nRight>0 );
1658a2a42013Sdrh while( iRight<nRight || iLeft<nLeft ){
1659067f3165Sdan ht_slot logpage;
1660a2a42013Sdrh Pgno dbpage;
1661a2a42013Sdrh
1662a2a42013Sdrh if( (iLeft<nLeft)
1663a2a42013Sdrh && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
1664a2a42013Sdrh ){
1665a2a42013Sdrh logpage = aLeft[iLeft++];
1666a2a42013Sdrh }else{
1667a2a42013Sdrh logpage = aRight[iRight++];
1668a2a42013Sdrh }
1669a2a42013Sdrh dbpage = aContent[logpage];
1670a2a42013Sdrh
1671f544b4c4Sdan aTmp[iOut++] = logpage;
1672a2a42013Sdrh if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
1673a2a42013Sdrh
1674a2a42013Sdrh assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
1675a2a42013Sdrh assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
1676a2a42013Sdrh }
1677f544b4c4Sdan
1678f544b4c4Sdan *paRight = aLeft;
1679f544b4c4Sdan *pnRight = iOut;
1680f544b4c4Sdan memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
1681a2a42013Sdrh }
1682a2a42013Sdrh
1683f544b4c4Sdan /*
1684d9c9b78eSdrh ** Sort the elements in list aList using aContent[] as the sort key.
1685d9c9b78eSdrh ** Remove elements with duplicate keys, preferring to keep the
1686d9c9b78eSdrh ** larger aList[] values.
1687d9c9b78eSdrh **
1688d9c9b78eSdrh ** The aList[] entries are indices into aContent[]. The values in
1689d9c9b78eSdrh ** aList[] are to be sorted so that for all J<K:
1690d9c9b78eSdrh **
1691d9c9b78eSdrh ** aContent[aList[J]] < aContent[aList[K]]
1692d9c9b78eSdrh **
1693d9c9b78eSdrh ** For any X and Y such that
1694d9c9b78eSdrh **
1695d9c9b78eSdrh ** aContent[aList[X]] == aContent[aList[Y]]
1696d9c9b78eSdrh **
1697d9c9b78eSdrh ** Keep the larger of the two values aList[X] and aList[Y] and discard
1698d9c9b78eSdrh ** the smaller.
1699f544b4c4Sdan */
walMergesort(const u32 * aContent,ht_slot * aBuffer,ht_slot * aList,int * pnList)1700f544b4c4Sdan static void walMergesort(
1701d9c9b78eSdrh const u32 *aContent, /* Pages in wal */
1702f544b4c4Sdan ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
1703f544b4c4Sdan ht_slot *aList, /* IN/OUT: List to sort */
1704f544b4c4Sdan int *pnList /* IN/OUT: Number of elements in aList[] */
1705f544b4c4Sdan ){
1706f544b4c4Sdan struct Sublist {
1707f544b4c4Sdan int nList; /* Number of elements in aList */
1708f544b4c4Sdan ht_slot *aList; /* Pointer to sub-list content */
1709f544b4c4Sdan };
1710f544b4c4Sdan
1711f544b4c4Sdan const int nList = *pnList; /* Size of input list */
1712ff82894fSdrh int nMerge = 0; /* Number of elements in list aMerge */
1713ff82894fSdrh ht_slot *aMerge = 0; /* List to be merged */
1714f544b4c4Sdan int iList; /* Index into input list */
1715f4fa0b80Sdrh u32 iSub = 0; /* Index into aSub array */
1716f544b4c4Sdan struct Sublist aSub[13]; /* Array of sub-lists */
1717f544b4c4Sdan
1718f544b4c4Sdan memset(aSub, 0, sizeof(aSub));
1719f544b4c4Sdan assert( nList<=HASHTABLE_NPAGE && nList>0 );
1720f544b4c4Sdan assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
1721f544b4c4Sdan
1722f544b4c4Sdan for(iList=0; iList<nList; iList++){
1723f544b4c4Sdan nMerge = 1;
1724f544b4c4Sdan aMerge = &aList[iList];
1725f544b4c4Sdan for(iSub=0; iList & (1<<iSub); iSub++){
1726f4fa0b80Sdrh struct Sublist *p;
1727f4fa0b80Sdrh assert( iSub<ArraySize(aSub) );
1728f4fa0b80Sdrh p = &aSub[iSub];
1729f544b4c4Sdan assert( p->aList && p->nList<=(1<<iSub) );
1730bdf1e243Sdan assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
1731f544b4c4Sdan walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
1732f544b4c4Sdan }
1733f544b4c4Sdan aSub[iSub].aList = aMerge;
1734f544b4c4Sdan aSub[iSub].nList = nMerge;
1735f544b4c4Sdan }
1736f544b4c4Sdan
1737f544b4c4Sdan for(iSub++; iSub<ArraySize(aSub); iSub++){
1738f544b4c4Sdan if( nList & (1<<iSub) ){
1739f4fa0b80Sdrh struct Sublist *p;
1740f4fa0b80Sdrh assert( iSub<ArraySize(aSub) );
1741f4fa0b80Sdrh p = &aSub[iSub];
1742bdf1e243Sdan assert( p->nList<=(1<<iSub) );
1743bdf1e243Sdan assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
1744f544b4c4Sdan walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
1745f544b4c4Sdan }
1746f544b4c4Sdan }
1747f544b4c4Sdan assert( aMerge==aList );
1748f544b4c4Sdan *pnList = nMerge;
1749f544b4c4Sdan
1750a2a42013Sdrh #ifdef SQLITE_DEBUG
1751a2a42013Sdrh {
1752a2a42013Sdrh int i;
1753a2a42013Sdrh for(i=1; i<*pnList; i++){
1754a2a42013Sdrh assert( aContent[aList[i]] > aContent[aList[i-1]] );
1755a2a42013Sdrh }
1756a2a42013Sdrh }
1757a2a42013Sdrh #endif
1758a2a42013Sdrh }
1759a2a42013Sdrh
1760a2a42013Sdrh /*
17615d656852Sdan ** Free an iterator allocated by walIteratorInit().
17625d656852Sdan */
walIteratorFree(WalIterator * p)17635d656852Sdan static void walIteratorFree(WalIterator *p){
1764cbd55b03Sdrh sqlite3_free(p);
17655d656852Sdan }
17665d656852Sdan
17675d656852Sdan /*
1768bdf1e243Sdan ** Construct a WalInterator object that can be used to loop over all
1769302ce475Sdan ** pages in the WAL following frame nBackfill in ascending order. Frames
1770302ce475Sdan ** nBackfill or earlier may be included - excluding them is an optimization
1771302ce475Sdan ** only. The caller must hold the checkpoint lock.
1772a2a42013Sdrh **
1773a2a42013Sdrh ** On success, make *pp point to the newly allocated WalInterator object
1774bdf1e243Sdan ** return SQLITE_OK. Otherwise, return an error code. If this routine
1775bdf1e243Sdan ** returns an error, the value of *pp is undefined.
1776a2a42013Sdrh **
1777a2a42013Sdrh ** The calling routine should invoke walIteratorFree() to destroy the
1778bdf1e243Sdan ** WalIterator object when it has finished with it.
1779a2a42013Sdrh */
walIteratorInit(Wal * pWal,u32 nBackfill,WalIterator ** pp)1780302ce475Sdan static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
17817ed91f23Sdrh WalIterator *p; /* Return value */
1782c438efd6Sdrh int nSegment; /* Number of segments to merge */
1783c438efd6Sdrh u32 iLast; /* Last frame in log */
1784f6ad201aSdrh sqlite3_int64 nByte; /* Number of bytes to allocate */
1785c438efd6Sdrh int i; /* Iterator variable */
1786067f3165Sdan ht_slot *aTmp; /* Temp space used by merge-sort */
1787bdf1e243Sdan int rc = SQLITE_OK; /* Return Code */
1788a2a42013Sdrh
1789bdf1e243Sdan /* This routine only runs while holding the checkpoint lock. And
1790bdf1e243Sdan ** it only runs if there is actually content in the log (mxFrame>0).
1791a2a42013Sdrh */
1792bdf1e243Sdan assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
179313a3cb82Sdan iLast = pWal->hdr.mxFrame;
1794a2a42013Sdrh
1795bdf1e243Sdan /* Allocate space for the WalIterator object. */
179613a3cb82Sdan nSegment = walFramePage(iLast) + 1;
179713a3cb82Sdan nByte = sizeof(WalIterator)
179852d6fc0eSdan + (nSegment-1)*sizeof(struct WalSegment)
179952d6fc0eSdan + iLast*sizeof(ht_slot);
1800f3cdcdccSdrh p = (WalIterator *)sqlite3_malloc64(nByte);
18018f6097c2Sdan if( !p ){
1802fad3039cSmistachkin return SQLITE_NOMEM_BKPT;
1803a2a42013Sdrh }
1804c438efd6Sdrh memset(p, 0, nByte);
1805a2a42013Sdrh p->nSegment = nSegment;
1806bdf1e243Sdan
1807bdf1e243Sdan /* Allocate temporary space used by the merge-sort routine. This block
1808bdf1e243Sdan ** of memory will be freed before this function returns.
1809bdf1e243Sdan */
1810f3cdcdccSdrh aTmp = (ht_slot *)sqlite3_malloc64(
181152d6fc0eSdan sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
181252d6fc0eSdan );
1813bdf1e243Sdan if( !aTmp ){
1814fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT;
1815bdf1e243Sdan }
1816bdf1e243Sdan
1817302ce475Sdan for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
18184ece2f26Sdrh WalHashLoc sLoc;
181913a3cb82Sdan
18204ece2f26Sdrh rc = walHashGet(pWal, i, &sLoc);
1821bdf1e243Sdan if( rc==SQLITE_OK ){
182252d6fc0eSdan int j; /* Counter variable */
182352d6fc0eSdan int nEntry; /* Number of entries in this segment */
182452d6fc0eSdan ht_slot *aIndex; /* Sorted index for this segment */
182552d6fc0eSdan
1826519426aaSdrh if( (i+1)==nSegment ){
18274ece2f26Sdrh nEntry = (int)(iLast - sLoc.iZero);
1828519426aaSdrh }else{
18294ece2f26Sdrh nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
1830519426aaSdrh }
18314ece2f26Sdrh aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
18324ece2f26Sdrh sLoc.iZero++;
183313a3cb82Sdan
183413a3cb82Sdan for(j=0; j<nEntry; j++){
18355eba1f60Sshaneh aIndex[j] = (ht_slot)j;
1836c438efd6Sdrh }
18374ece2f26Sdrh walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
18384ece2f26Sdrh p->aSegment[i].iZero = sLoc.iZero;
183913a3cb82Sdan p->aSegment[i].nEntry = nEntry;
1840bdf1e243Sdan p->aSegment[i].aIndex = aIndex;
18414ece2f26Sdrh p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
1842c438efd6Sdrh }
1843bdf1e243Sdan }
1844cbd55b03Sdrh sqlite3_free(aTmp);
1845c438efd6Sdrh
1846bdf1e243Sdan if( rc!=SQLITE_OK ){
1847bdf1e243Sdan walIteratorFree(p);
184849cc2f3bSdrh p = 0;
1849bdf1e243Sdan }
18508f6097c2Sdan *pp = p;
1851bdf1e243Sdan return rc;
1852c438efd6Sdrh }
1853c438efd6Sdrh
18547bb8b8a4Sdan #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
18557bb8b8a4Sdan /*
18567bb8b8a4Sdan ** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
18577bb8b8a4Sdan ** they are supported by the VFS, and (b) the database handle is configured
18587bb8b8a4Sdan ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
18597bb8b8a4Sdan ** or 0 otherwise.
18607bb8b8a4Sdan */
walEnableBlocking(Wal * pWal)18617bb8b8a4Sdan static int walEnableBlocking(Wal *pWal){
18627bb8b8a4Sdan int res = 0;
18637bb8b8a4Sdan if( pWal->db ){
18647bb8b8a4Sdan int tmout = pWal->db->busyTimeout;
18657bb8b8a4Sdan if( tmout ){
18667bb8b8a4Sdan int rc;
18677bb8b8a4Sdan rc = sqlite3OsFileControl(
18687bb8b8a4Sdan pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
18697bb8b8a4Sdan );
18707bb8b8a4Sdan res = (rc==SQLITE_OK);
18717bb8b8a4Sdan }
18727bb8b8a4Sdan }
18737bb8b8a4Sdan return res;
18747bb8b8a4Sdan }
18757bb8b8a4Sdan
18767bb8b8a4Sdan /*
18777bb8b8a4Sdan ** Disable blocking locks.
18787bb8b8a4Sdan */
walDisableBlocking(Wal * pWal)18797bb8b8a4Sdan static void walDisableBlocking(Wal *pWal){
18807bb8b8a4Sdan int tmout = 0;
18817bb8b8a4Sdan sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
18827bb8b8a4Sdan }
18837bb8b8a4Sdan
18847bb8b8a4Sdan /*
18857bb8b8a4Sdan ** If parameter bLock is true, attempt to enable blocking locks, take
18867bb8b8a4Sdan ** the WRITER lock, and then disable blocking locks. If blocking locks
18877bb8b8a4Sdan ** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
18887bb8b8a4Sdan ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
18897bb8b8a4Sdan ** an error if blocking locks can not be enabled.
18907bb8b8a4Sdan **
18917bb8b8a4Sdan ** If the bLock parameter is false and the WRITER lock is held, release it.
18927bb8b8a4Sdan */
sqlite3WalWriteLock(Wal * pWal,int bLock)18937bb8b8a4Sdan int sqlite3WalWriteLock(Wal *pWal, int bLock){
18947bb8b8a4Sdan int rc = SQLITE_OK;
18957bb8b8a4Sdan assert( pWal->readLock<0 || bLock==0 );
18967bb8b8a4Sdan if( bLock ){
18977bb8b8a4Sdan assert( pWal->db );
18987bb8b8a4Sdan if( walEnableBlocking(pWal) ){
18997bb8b8a4Sdan rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
19007bb8b8a4Sdan if( rc==SQLITE_OK ){
19017bb8b8a4Sdan pWal->writeLock = 1;
19027bb8b8a4Sdan }
19037bb8b8a4Sdan walDisableBlocking(pWal);
19047bb8b8a4Sdan }
19057bb8b8a4Sdan }else if( pWal->writeLock ){
19067bb8b8a4Sdan walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
19077bb8b8a4Sdan pWal->writeLock = 0;
19087bb8b8a4Sdan }
19097bb8b8a4Sdan return rc;
19107bb8b8a4Sdan }
19117bb8b8a4Sdan
19127bb8b8a4Sdan /*
19137bb8b8a4Sdan ** Set the database handle used to determine if blocking locks are required.
19147bb8b8a4Sdan */
sqlite3WalDb(Wal * pWal,sqlite3 * db)19157bb8b8a4Sdan void sqlite3WalDb(Wal *pWal, sqlite3 *db){
19167bb8b8a4Sdan pWal->db = db;
19177bb8b8a4Sdan }
19187bb8b8a4Sdan
19197bb8b8a4Sdan /*
19207bb8b8a4Sdan ** Take an exclusive WRITE lock. Blocking if so configured.
19217bb8b8a4Sdan */
walLockWriter(Wal * pWal)19227bb8b8a4Sdan static int walLockWriter(Wal *pWal){
19237bb8b8a4Sdan int rc;
19247bb8b8a4Sdan walEnableBlocking(pWal);
19257bb8b8a4Sdan rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
19267bb8b8a4Sdan walDisableBlocking(pWal);
19277bb8b8a4Sdan return rc;
19287bb8b8a4Sdan }
19297bb8b8a4Sdan #else
19307bb8b8a4Sdan # define walEnableBlocking(x) 0
19317bb8b8a4Sdan # define walDisableBlocking(x)
19327bb8b8a4Sdan # define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)
19337bb8b8a4Sdan # define sqlite3WalDb(pWal, db)
19347bb8b8a4Sdan #endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
19357bb8b8a4Sdan
19367bb8b8a4Sdan
1937c438efd6Sdrh /*
1938a58f26f9Sdan ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
1939a58f26f9Sdan ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
1940a58f26f9Sdan ** busy-handler function. Invoke it and retry the lock until either the
1941a58f26f9Sdan ** lock is successfully obtained or the busy-handler returns 0.
1942a58f26f9Sdan */
walBusyLock(Wal * pWal,int (* xBusy)(void *),void * pBusyArg,int lockIdx,int n)1943a58f26f9Sdan static int walBusyLock(
1944a58f26f9Sdan Wal *pWal, /* WAL connection */
1945a58f26f9Sdan int (*xBusy)(void*), /* Function to call when busy */
1946a58f26f9Sdan void *pBusyArg, /* Context argument for xBusyHandler */
1947a58f26f9Sdan int lockIdx, /* Offset of first byte to lock */
1948a58f26f9Sdan int n /* Number of bytes to lock */
1949a58f26f9Sdan ){
1950a58f26f9Sdan int rc;
1951a58f26f9Sdan do {
1952ab372773Sdrh rc = walLockExclusive(pWal, lockIdx, n);
1953a58f26f9Sdan }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
19547bb8b8a4Sdan #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
19557bb8b8a4Sdan if( rc==SQLITE_BUSY_TIMEOUT ){
19567bb8b8a4Sdan walDisableBlocking(pWal);
19577bb8b8a4Sdan rc = SQLITE_BUSY;
19587bb8b8a4Sdan }
19597bb8b8a4Sdan #endif
1960a58f26f9Sdan return rc;
1961a58f26f9Sdan }
1962a58f26f9Sdan
1963a58f26f9Sdan /*
1964f2b8dd58Sdan ** The cache of the wal-index header must be valid to call this function.
1965f2b8dd58Sdan ** Return the page-size in bytes used by the database.
1966f2b8dd58Sdan */
walPagesize(Wal * pWal)1967f2b8dd58Sdan static int walPagesize(Wal *pWal){
1968f2b8dd58Sdan return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
1969f2b8dd58Sdan }
1970f2b8dd58Sdan
1971f2b8dd58Sdan /*
1972f26a1549Sdan ** The following is guaranteed when this function is called:
1973f26a1549Sdan **
1974f26a1549Sdan ** a) the WRITER lock is held,
1975f26a1549Sdan ** b) the entire log file has been checkpointed, and
1976f26a1549Sdan ** c) any existing readers are reading exclusively from the database
1977f26a1549Sdan ** file - there are no readers that may attempt to read a frame from
1978f26a1549Sdan ** the log file.
1979f26a1549Sdan **
1980f26a1549Sdan ** This function updates the shared-memory structures so that the next
1981f26a1549Sdan ** client to write to the database (which may be this one) does so by
1982f26a1549Sdan ** writing frames into the start of the log file.
19830fe8c1b9Sdan **
19840fe8c1b9Sdan ** The value of parameter salt1 is used as the aSalt[1] value in the
19850fe8c1b9Sdan ** new wal-index header. It should be passed a pseudo-random value (i.e.
19860fe8c1b9Sdan ** one obtained from sqlite3_randomness()).
1987f26a1549Sdan */
walRestartHdr(Wal * pWal,u32 salt1)19880fe8c1b9Sdan static void walRestartHdr(Wal *pWal, u32 salt1){
1989f26a1549Sdan volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
1990f26a1549Sdan int i; /* Loop counter */
1991f26a1549Sdan u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
1992f26a1549Sdan pWal->nCkpt++;
1993f26a1549Sdan pWal->hdr.mxFrame = 0;
1994f26a1549Sdan sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
19950fe8c1b9Sdan memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
1996f26a1549Sdan walIndexWriteHdr(pWal);
19978b4f231cSdan AtomicStore(&pInfo->nBackfill, 0);
1998998147ecSdrh pInfo->nBackfillAttempted = 0;
1999f26a1549Sdan pInfo->aReadMark[1] = 0;
2000f26a1549Sdan for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
2001f26a1549Sdan assert( pInfo->aReadMark[0]==0 );
2002f26a1549Sdan }
2003f26a1549Sdan
2004f26a1549Sdan /*
200573b64e4dSdrh ** Copy as much content as we can from the WAL back into the database file
200673b64e4dSdrh ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
200773b64e4dSdrh **
200873b64e4dSdrh ** The amount of information copies from WAL to database might be limited
200973b64e4dSdrh ** by active readers. This routine will never overwrite a database page
201073b64e4dSdrh ** that a concurrent reader might be using.
201173b64e4dSdrh **
201273b64e4dSdrh ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
201373b64e4dSdrh ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
201473b64e4dSdrh ** checkpoints are always run by a background thread or background
201573b64e4dSdrh ** process, foreground threads will never block on a lengthy fsync call.
201673b64e4dSdrh **
201773b64e4dSdrh ** Fsync is called on the WAL before writing content out of the WAL and
201873b64e4dSdrh ** into the database. This ensures that if the new content is persistent
201973b64e4dSdrh ** in the WAL and can be recovered following a power-loss or hard reset.
202073b64e4dSdrh **
202173b64e4dSdrh ** Fsync is also called on the database file if (and only if) the entire
202273b64e4dSdrh ** WAL content is copied into the database file. This second fsync makes
202373b64e4dSdrh ** it safe to delete the WAL since the new content will persist in the
202473b64e4dSdrh ** database file.
202573b64e4dSdrh **
202673b64e4dSdrh ** This routine uses and updates the nBackfill field of the wal-index header.
202760ec914cSpeter.d.reid ** This is the only routine that will increase the value of nBackfill.
202873b64e4dSdrh ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
202973b64e4dSdrh ** its value.)
203073b64e4dSdrh **
203173b64e4dSdrh ** The caller must be holding sufficient locks to ensure that no other
203273b64e4dSdrh ** checkpoint is running (in any other thread or process) at the same
203373b64e4dSdrh ** time.
2034c438efd6Sdrh */
walCheckpoint(Wal * pWal,sqlite3 * db,int eMode,int (* xBusy)(void *),void * pBusyArg,int sync_flags,u8 * zBuf)20357ed91f23Sdrh static int walCheckpoint(
20367ed91f23Sdrh Wal *pWal, /* Wal connection */
20377fb89906Sdan sqlite3 *db, /* Check for interrupts on this handle */
2038cdc1f049Sdan int eMode, /* One of PASSIVE, FULL or RESTART */
2039dd90d7eeSdrh int (*xBusy)(void*), /* Function to call when busy */
2040a58f26f9Sdan void *pBusyArg, /* Context argument for xBusyHandler */
2041c438efd6Sdrh int sync_flags, /* Flags for OsSync() (or 0) */
20429c5e3680Sdan u8 *zBuf /* Temporary buffer to use */
2043c438efd6Sdrh ){
2044976b0033Sdan int rc = SQLITE_OK; /* Return code */
2045b2eced5dSdrh int szPage; /* Database page-size */
20467ed91f23Sdrh WalIterator *pIter = 0; /* Wal iterator context */
2047c438efd6Sdrh u32 iDbpage = 0; /* Next database page to write */
20487ed91f23Sdrh u32 iFrame = 0; /* Wal frame containing data for iDbpage */
204973b64e4dSdrh u32 mxSafeFrame; /* Max frame that can be backfilled */
2050502019c8Sdan u32 mxPage; /* Max database page to write */
205173b64e4dSdrh int i; /* Loop counter */
205273b64e4dSdrh volatile WalCkptInfo *pInfo; /* The checkpoint status information */
2053c438efd6Sdrh
2054f2b8dd58Sdan szPage = walPagesize(pWal);
20559b78f791Sdrh testcase( szPage<=32768 );
20569b78f791Sdrh testcase( szPage>=65536 );
20577d208445Sdrh pInfo = walCkptInfo(pWal);
2058976b0033Sdan if( pInfo->nBackfill<pWal->hdr.mxFrame ){
2059f544b4c4Sdan
2060dd90d7eeSdrh /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
2061dd90d7eeSdrh ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
2062dd90d7eeSdrh assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
2063b6e099a9Sdan
206473b64e4dSdrh /* Compute in mxSafeFrame the index of the last frame of the WAL that is
206573b64e4dSdrh ** safe to write into the database. Frames beyond mxSafeFrame might
206673b64e4dSdrh ** overwrite database pages that are in use by active readers and thus
206773b64e4dSdrh ** cannot be backfilled from the WAL.
206873b64e4dSdrh */
2069d54ff60bSdan mxSafeFrame = pWal->hdr.mxFrame;
2070502019c8Sdan mxPage = pWal->hdr.nPage;
207173b64e4dSdrh for(i=1; i<WAL_NREADER; i++){
2072f16cf653Sdrh u32 y = AtomicLoad(pInfo->aReadMark+i);
2073f2b8dd58Sdan if( mxSafeFrame>y ){
207483f42d1bSdan assert( y<=pWal->hdr.mxFrame );
2075f2b8dd58Sdan rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
207683f42d1bSdan if( rc==SQLITE_OK ){
2077f16cf653Sdrh u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
2078f16cf653Sdrh AtomicStore(pInfo->aReadMark+i, iMark);
207973b64e4dSdrh walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
20802d37e1cfSdrh }else if( rc==SQLITE_BUSY ){
2081db7f647eSdrh mxSafeFrame = y;
2082f2b8dd58Sdan xBusy = 0;
20832d37e1cfSdrh }else{
208483f42d1bSdan goto walcheckpoint_out;
208573b64e4dSdrh }
208673b64e4dSdrh }
208773b64e4dSdrh }
208873b64e4dSdrh
2089f0cb61d6Sdan /* Allocate the iterator */
2090f0cb61d6Sdan if( pInfo->nBackfill<mxSafeFrame ){
2091f0cb61d6Sdan rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
2092f0cb61d6Sdan assert( rc==SQLITE_OK || pIter==0 );
2093f0cb61d6Sdan }
2094f0cb61d6Sdan
2095f0cb61d6Sdan if( pIter
2096a58f26f9Sdan && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
209773b64e4dSdrh ){
209873b64e4dSdrh u32 nBackfill = pInfo->nBackfill;
209973b64e4dSdrh
21003bf83ccdSdan pInfo->nBackfillAttempted = mxSafeFrame;
21013bf83ccdSdan
210273b64e4dSdrh /* Sync the WAL to disk */
2103daaae7b9Sdrh rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
2104c438efd6Sdrh
2105f23da966Sdan /* If the database may grow as a result of this checkpoint, hint
2106f23da966Sdan ** about the eventual size of the db file to the VFS layer.
2107f23da966Sdan */
2108007820d6Sdan if( rc==SQLITE_OK ){
2109007820d6Sdan i64 nReq = ((i64)mxPage * szPage);
21106389a7b0Smistachkin i64 nSize; /* Current size of database file */
2111fcf31b28Sdrh sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
2112f23da966Sdan rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
2113f23da966Sdan if( rc==SQLITE_OK && nSize<nReq ){
211491faeec8Sdan if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
211588819d58Sdan /* If the size of the final database is larger than the current
211691faeec8Sdan ** database plus the amount of data in the wal file, plus the
211791faeec8Sdan ** maximum size of the pending-byte page (65536 bytes), then
211888819d58Sdan ** must be corruption somewhere. */
211988819d58Sdan rc = SQLITE_CORRUPT_BKPT;
2120799443b1Sdrh }else{
2121799443b1Sdrh sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
212288819d58Sdan }
212388819d58Sdan }
2124502019c8Sdan
2125799443b1Sdrh }
2126799443b1Sdrh
2127976b0033Sdan /* Iterate through the contents of the WAL, copying data to the db file */
212873b64e4dSdrh while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
21293e8e7ecbSdrh i64 iOffset;
213013a3cb82Sdan assert( walFramePgno(pWal, iFrame)==iDbpage );
2131892edb69Sdan if( AtomicLoad(&db->u1.isInterrupted) ){
21327fb89906Sdan rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
21337fb89906Sdan break;
21347fb89906Sdan }
2135976b0033Sdan if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
2136976b0033Sdan continue;
2137976b0033Sdan }
21383e8e7ecbSdrh iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
213909b5dbc5Sdrh /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
21403e8e7ecbSdrh rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
21413e8e7ecbSdrh if( rc!=SQLITE_OK ) break;
21423e8e7ecbSdrh iOffset = (iDbpage-1)*(i64)szPage;
21433e8e7ecbSdrh testcase( IS_BIG_INT(iOffset) );
2144f23da966Sdan rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
21453e8e7ecbSdrh if( rc!=SQLITE_OK ) break;
2146c438efd6Sdrh }
2147fcf31b28Sdrh sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
2148c438efd6Sdrh
214973b64e4dSdrh /* If work was actually accomplished... */
2150d764c7deSdan if( rc==SQLITE_OK ){
21514280eb30Sdan if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
21523e8e7ecbSdrh i64 szDb = pWal->hdr.nPage*(i64)szPage;
21533e8e7ecbSdrh testcase( IS_BIG_INT(szDb) );
21543e8e7ecbSdrh rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
2155daaae7b9Sdrh if( rc==SQLITE_OK ){
2156daaae7b9Sdrh rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
2157c438efd6Sdrh }
215873b64e4dSdrh }
2159d764c7deSdan if( rc==SQLITE_OK ){
21608b4f231cSdan AtomicStore(&pInfo->nBackfill, mxSafeFrame);
2161d764c7deSdan }
216273b64e4dSdrh }
2163c438efd6Sdrh
216473b64e4dSdrh /* Release the reader lock held while backfilling */
216573b64e4dSdrh walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
2166a58f26f9Sdan }
2167a58f26f9Sdan
2168a58f26f9Sdan if( rc==SQLITE_BUSY ){
216934116eafSdrh /* Reset the return code so as not to report a checkpoint failure
2170a58f26f9Sdan ** just because there are active readers. */
217134116eafSdrh rc = SQLITE_OK;
217273b64e4dSdrh }
2173976b0033Sdan }
217473b64e4dSdrh
2175f26a1549Sdan /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
2176f26a1549Sdan ** entire wal file has been copied into the database file, then block
2177f26a1549Sdan ** until all readers have finished using the wal file. This ensures that
2178f26a1549Sdan ** the next process to write to the database restarts the wal file.
2179f2b8dd58Sdan */
2180f2b8dd58Sdan if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
2181cdc1f049Sdan assert( pWal->writeLock );
2182f2b8dd58Sdan if( pInfo->nBackfill<pWal->hdr.mxFrame ){
2183f2b8dd58Sdan rc = SQLITE_BUSY;
2184f26a1549Sdan }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
21850fe8c1b9Sdan u32 salt1;
21860fe8c1b9Sdan sqlite3_randomness(4, &salt1);
2187976b0033Sdan assert( pInfo->nBackfill==pWal->hdr.mxFrame );
2188cdc1f049Sdan rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
2189cdc1f049Sdan if( rc==SQLITE_OK ){
2190f26a1549Sdan if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
2191a25165faSdrh /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
2192a25165faSdrh ** SQLITE_CHECKPOINT_RESTART with the addition that it also
2193a25165faSdrh ** truncates the log file to zero bytes just prior to a
2194a25165faSdrh ** successful return.
2195f26a1549Sdan **
2196f26a1549Sdan ** In theory, it might be safe to do this without updating the
2197f26a1549Sdan ** wal-index header in shared memory, as all subsequent reader or
2198f26a1549Sdan ** writer clients should see that the entire log file has been
2199f26a1549Sdan ** checkpointed and behave accordingly. This seems unsafe though,
2200f26a1549Sdan ** as it would leave the system in a state where the contents of
2201f26a1549Sdan ** the wal-index header do not match the contents of the
2202f26a1549Sdan ** file-system. To avoid this, update the wal-index header to
2203f26a1549Sdan ** indicate that the log file contains zero valid frames. */
22040fe8c1b9Sdan walRestartHdr(pWal, salt1);
2205f26a1549Sdan rc = sqlite3OsTruncate(pWal->pWalFd, 0);
2206f26a1549Sdan }
2207cdc1f049Sdan walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
2208cdc1f049Sdan }
2209cdc1f049Sdan }
2210f2b8dd58Sdan }
2211cdc1f049Sdan
221283f42d1bSdan walcheckpoint_out:
22137ed91f23Sdrh walIteratorFree(pIter);
2214c438efd6Sdrh return rc;
2215c438efd6Sdrh }
2216c438efd6Sdrh
2217c438efd6Sdrh /*
2218f60b7f36Sdan ** If the WAL file is currently larger than nMax bytes in size, truncate
2219f60b7f36Sdan ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
22208dd4afadSdrh */
walLimitSize(Wal * pWal,i64 nMax)2221f60b7f36Sdan static void walLimitSize(Wal *pWal, i64 nMax){
22228dd4afadSdrh i64 sz;
22238dd4afadSdrh int rx;
22248dd4afadSdrh sqlite3BeginBenignMalloc();
22258dd4afadSdrh rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
2226f60b7f36Sdan if( rx==SQLITE_OK && (sz > nMax ) ){
2227f60b7f36Sdan rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
22288dd4afadSdrh }
22298dd4afadSdrh sqlite3EndBenignMalloc();
22308dd4afadSdrh if( rx ){
22318dd4afadSdrh sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
22328dd4afadSdrh }
22338dd4afadSdrh }
22348dd4afadSdrh
22358dd4afadSdrh /*
2236c438efd6Sdrh ** Close a connection to a log file.
2237c438efd6Sdrh */
sqlite3WalClose(Wal * pWal,sqlite3 * db,int sync_flags,int nBuf,u8 * zBuf)2238c438efd6Sdrh int sqlite3WalClose(
22397ed91f23Sdrh Wal *pWal, /* Wal to close */
22407fb89906Sdan sqlite3 *db, /* For interrupt flag */
2241c438efd6Sdrh int sync_flags, /* Flags to pass to OsSync() (or 0) */
2242b6e099a9Sdan int nBuf,
2243b6e099a9Sdan u8 *zBuf /* Buffer of at least nBuf bytes */
2244c438efd6Sdrh ){
2245c438efd6Sdrh int rc = SQLITE_OK;
22467ed91f23Sdrh if( pWal ){
224730c8629eSdan int isDelete = 0; /* True to unlink wal and wal-index files */
224830c8629eSdan
224930c8629eSdan /* If an EXCLUSIVE lock can be obtained on the database file (using the
225030c8629eSdan ** ordinary, rollback-mode locking methods, this guarantees that the
225130c8629eSdan ** connection associated with this log file is the only connection to
225230c8629eSdan ** the database. In this case checkpoint the database and unlink both
225330c8629eSdan ** the wal and wal-index files.
225430c8629eSdan **
225530c8629eSdan ** The EXCLUSIVE lock is not released before returning.
225630c8629eSdan */
22574a5bad57Sdan if( zBuf!=0
2258298af023Sdan && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
2259298af023Sdan ){
22608c408004Sdan if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
22618c408004Sdan pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
22628c408004Sdan }
22637fb89906Sdan rc = sqlite3WalCheckpoint(pWal, db,
22647fb89906Sdan SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
2265cdc1f049Sdan );
2266eed42505Sdrh if( rc==SQLITE_OK ){
2267eed42505Sdrh int bPersist = -1;
2268c02372ceSdrh sqlite3OsFileControlHint(
22696f2f19a1Sdan pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
22706f2f19a1Sdan );
2271eed42505Sdrh if( bPersist!=1 ){
2272eed42505Sdrh /* Try to delete the WAL file if the checkpoint completed and
2273eed42505Sdrh ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
2274eed42505Sdrh ** mode (!bPersist) */
227530c8629eSdan isDelete = 1;
2276f60b7f36Sdan }else if( pWal->mxWalSize>=0 ){
2277eed42505Sdrh /* Try to truncate the WAL file to zero bytes if the checkpoint
2278eed42505Sdrh ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
2279eed42505Sdrh ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
2280eed42505Sdrh ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
2281eed42505Sdrh ** to zero bytes as truncating to the journal_size_limit might
2282eed42505Sdrh ** leave a corrupt WAL file on disk. */
2283eed42505Sdrh walLimitSize(pWal, 0);
2284eed42505Sdrh }
228530c8629eSdan }
228630c8629eSdan }
228730c8629eSdan
22881018e90bSdan walIndexClose(pWal, isDelete);
2289d9e5c4f6Sdrh sqlite3OsClose(pWal->pWalFd);
229030c8629eSdan if( isDelete ){
229192c45cf0Sdrh sqlite3BeginBenignMalloc();
2292d9e5c4f6Sdrh sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
229392c45cf0Sdrh sqlite3EndBenignMalloc();
229430c8629eSdan }
2295c74c3334Sdrh WALTRACE(("WAL%p: closed\n", pWal));
22968a300f80Sshaneh sqlite3_free((void *)pWal->apWiData);
22977ed91f23Sdrh sqlite3_free(pWal);
2298c438efd6Sdrh }
2299c438efd6Sdrh return rc;
2300c438efd6Sdrh }
2301c438efd6Sdrh
2302c438efd6Sdrh /*
2303a2a42013Sdrh ** Try to read the wal-index header. Return 0 on success and 1 if
2304a2a42013Sdrh ** there is a problem.
2305a2a42013Sdrh **
2306a2a42013Sdrh ** The wal-index is in shared memory. Another thread or process might
2307a2a42013Sdrh ** be writing the header at the same time this procedure is trying to
2308a2a42013Sdrh ** read it, which might result in inconsistency. A dirty read is detected
230973b64e4dSdrh ** by verifying that both copies of the header are the same and also by
231073b64e4dSdrh ** a checksum on the header.
2311a2a42013Sdrh **
2312a2a42013Sdrh ** If and only if the read is consistent and the header is different from
2313a2a42013Sdrh ** pWal->hdr, then pWal->hdr is updated to the content of the new header
2314a2a42013Sdrh ** and *pChanged is set to 1.
2315c438efd6Sdrh **
231684670502Sdan ** If the checksum cannot be verified return non-zero. If the header
231784670502Sdan ** is read successfully and the checksum verified, return zero.
2318c438efd6Sdrh */
walIndexTryHdr(Wal * pWal,int * pChanged)23195a8cd2e4Sdrh static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
2320286a2884Sdrh u32 aCksum[2]; /* Checksum on the header content */
2321f0b20f88Sdrh WalIndexHdr h1, h2; /* Two copies of the header content */
23224280eb30Sdan WalIndexHdr volatile *aHdr; /* Header in shared memory */
2323c438efd6Sdrh
23244280eb30Sdan /* The first page of the wal-index must be mapped at this point. */
23254280eb30Sdan assert( pWal->nWiData>0 && pWal->apWiData[0] );
232679e6c78cSdrh
23276cef0cf7Sdrh /* Read the header. This might happen concurrently with a write to the
232873b64e4dSdrh ** same area of shared memory on a different CPU in a SMP,
232973b64e4dSdrh ** meaning it is possible that an inconsistent snapshot is read
233084670502Sdan ** from the file. If this happens, return non-zero.
2331f0b20f88Sdrh **
2332f16cf653Sdrh ** tag-20200519-1:
2333f0b20f88Sdrh ** There are two copies of the header at the beginning of the wal-index.
2334f0b20f88Sdrh ** When reading, read [0] first then [1]. Writes are in the reverse order.
2335f0b20f88Sdrh ** Memory barriers are used to prevent the compiler or the hardware from
2336f16cf653Sdrh ** reordering the reads and writes. TSAN and similar tools can sometimes
2337f16cf653Sdrh ** give false-positive warnings about these accesses because the tools do not
2338f16cf653Sdrh ** account for the double-read and the memory barrier. The use of mutexes
2339f16cf653Sdrh ** here would be problematic as the memory being accessed is potentially
2340f16cf653Sdrh ** shared among multiple processes and not all mutex implementions work
2341f16cf653Sdrh ** reliably in that environment.
2342c438efd6Sdrh */
23434280eb30Sdan aHdr = walIndexHdr(pWal);
2344f16cf653Sdrh memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
23458c408004Sdan walShmBarrier(pWal);
23464280eb30Sdan memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
2347286a2884Sdrh
2348f0b20f88Sdrh if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
2349f0b20f88Sdrh return 1; /* Dirty read */
2350286a2884Sdrh }
23514b82c387Sdrh if( h1.isInit==0 ){
2352f0b20f88Sdrh return 1; /* Malformed header - probably all zeros */
2353f0b20f88Sdrh }
2354b8fd6c2fSdan walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
2355f0b20f88Sdrh if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
2356f0b20f88Sdrh return 1; /* Checksum does not match */
2357c438efd6Sdrh }
2358c438efd6Sdrh
2359f0b20f88Sdrh if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
2360c438efd6Sdrh *pChanged = 1;
2361f0b20f88Sdrh memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
23629b78f791Sdrh pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
23639b78f791Sdrh testcase( pWal->szPage<=32768 );
23649b78f791Sdrh testcase( pWal->szPage>=65536 );
2365c438efd6Sdrh }
236684670502Sdan
236784670502Sdan /* The header was successfully read. Return zero. */
236884670502Sdan return 0;
2369c438efd6Sdrh }
2370c438efd6Sdrh
2371c438efd6Sdrh /*
237208ecefc5Sdan ** This is the value that walTryBeginRead returns when it needs to
237308ecefc5Sdan ** be retried.
237408ecefc5Sdan */
237508ecefc5Sdan #define WAL_RETRY (-1)
237608ecefc5Sdan
237708ecefc5Sdan /*
2378a2a42013Sdrh ** Read the wal-index header from the wal-index and into pWal->hdr.
2379a927e94eSdrh ** If the wal-header appears to be corrupt, try to reconstruct the
2380a927e94eSdrh ** wal-index from the WAL before returning.
2381a2a42013Sdrh **
2382a2a42013Sdrh ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
238360ec914cSpeter.d.reid ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
2384a2a42013Sdrh ** to 0.
2385a2a42013Sdrh **
23867ed91f23Sdrh ** If the wal-index header is successfully read, return SQLITE_OK.
2387c438efd6Sdrh ** Otherwise an SQLite error code.
2388c438efd6Sdrh */
walIndexReadHdr(Wal * pWal,int * pChanged)23897ed91f23Sdrh static int walIndexReadHdr(Wal *pWal, int *pChanged){
239084670502Sdan int rc; /* Return code */
239173b64e4dSdrh int badHdr; /* True if a header read failed */
2392a927e94eSdrh volatile u32 *page0; /* Chunk of wal-index containing header */
2393c438efd6Sdrh
23944280eb30Sdan /* Ensure that page 0 of the wal-index (the page that contains the
23954280eb30Sdan ** wal-index header) is mapped. Return early if an error occurs here.
23964280eb30Sdan */
2397a861469aSdan assert( pChanged );
23984280eb30Sdan rc = walIndexPage(pWal, 0, &page0);
239985bc6df2Sdrh if( rc!=SQLITE_OK ){
240085bc6df2Sdrh assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
24017e45e3a5Sdrh if( rc==SQLITE_READONLY_CANTINIT ){
240285bc6df2Sdrh /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
240385bc6df2Sdrh ** was openable but is not writable, and this thread is unable to
240485bc6df2Sdrh ** confirm that another write-capable connection has the shared-memory
240585bc6df2Sdrh ** open, and hence the content of the shared-memory is unreliable,
240685bc6df2Sdrh ** since the shared-memory might be inconsistent with the WAL file
240785bc6df2Sdrh ** and there is no writer on hand to fix it. */
2408c05a063cSdrh assert( page0==0 );
2409c05a063cSdrh assert( pWal->writeLock==0 );
2410c05a063cSdrh assert( pWal->readOnly & WAL_SHM_RDONLY );
241185bc6df2Sdrh pWal->bShmUnreliable = 1;
241211caf4f4Sdan pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
241311caf4f4Sdan *pChanged = 1;
241485bc6df2Sdrh }else{
241585bc6df2Sdrh return rc; /* Any other non-OK return is just an error */
241685bc6df2Sdrh }
2417c05a063cSdrh }else{
2418c05a063cSdrh /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
2419c05a063cSdrh ** is zero, which prevents the SHM from growing */
2420c05a063cSdrh testcase( page0!=0 );
2421c05a063cSdrh }
2422c05a063cSdrh assert( page0!=0 || pWal->writeLock==0 );
24237ed91f23Sdrh
24244280eb30Sdan /* If the first page of the wal-index has been mapped, try to read the
24254280eb30Sdan ** wal-index header immediately, without holding any lock. This usually
24264280eb30Sdan ** works, but may fail if the wal-index header is corrupt or currently
2427a927e94eSdrh ** being modified by another thread or process.
2428c438efd6Sdrh */
24294280eb30Sdan badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
2430c438efd6Sdrh
243173b64e4dSdrh /* If the first attempt failed, it might have been due to a race
243266dfec8bSdrh ** with a writer. So get a WRITE lock and try again.
2433c438efd6Sdrh */
24344edc6bf3Sdan if( badHdr ){
243585bc6df2Sdrh if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
24364edc6bf3Sdan if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
24374edc6bf3Sdan walUnlockShared(pWal, WAL_WRITE_LOCK);
24384edc6bf3Sdan rc = SQLITE_READONLY_RECOVERY;
24394edc6bf3Sdan }
2440d0e6d133Sdan }else{
2441d0e6d133Sdan int bWriteLock = pWal->writeLock;
2442861fb1e9Sdan if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){
244373b64e4dSdrh pWal->writeLock = 1;
24444280eb30Sdan if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
244573b64e4dSdrh badHdr = walIndexTryHdr(pWal, pChanged);
244673b64e4dSdrh if( badHdr ){
244773b64e4dSdrh /* If the wal-index header is still malformed even while holding
244873b64e4dSdrh ** a WRITE lock, it can only mean that the header is corrupted and
244973b64e4dSdrh ** needs to be reconstructed. So run recovery to do exactly that.
245073b64e4dSdrh */
24517ed91f23Sdrh rc = walIndexRecover(pWal);
24523dee6da9Sdan *pChanged = 1;
2453c438efd6Sdrh }
2454c438efd6Sdrh }
2455d0e6d133Sdan if( bWriteLock==0 ){
24564280eb30Sdan pWal->writeLock = 0;
24574280eb30Sdan walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
2458bab7b91eSdrh }
24594edc6bf3Sdan }
2460d0e6d133Sdan }
2461d0e6d133Sdan }
2462bab7b91eSdrh
2463a927e94eSdrh /* If the header is read successfully, check the version number to make
2464a927e94eSdrh ** sure the wal-index was not constructed with some future format that
2465a927e94eSdrh ** this version of SQLite cannot understand.
2466a927e94eSdrh */
2467a927e94eSdrh if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
2468a927e94eSdrh rc = SQLITE_CANTOPEN_BKPT;
2469a927e94eSdrh }
247085bc6df2Sdrh if( pWal->bShmUnreliable ){
247111caf4f4Sdan if( rc!=SQLITE_OK ){
247211caf4f4Sdan walIndexClose(pWal, 0);
247385bc6df2Sdrh pWal->bShmUnreliable = 0;
247408ecefc5Sdan assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
24758b17ac19Sdrh /* walIndexRecover() might have returned SHORT_READ if a concurrent
24768b17ac19Sdrh ** writer truncated the WAL out from under it. If that happens, it
24778b17ac19Sdrh ** indicates that a writer has fixed the SHM file for us, so retry */
247808ecefc5Sdan if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
247911caf4f4Sdan }
248011caf4f4Sdan pWal->exclusiveMode = WAL_NORMAL_MODE;
248111caf4f4Sdan }
2482a927e94eSdrh
2483c438efd6Sdrh return rc;
2484c438efd6Sdrh }
2485c438efd6Sdrh
2486c438efd6Sdrh /*
248785bc6df2Sdrh ** Open a transaction in a connection where the shared-memory is read-only
248885bc6df2Sdrh ** and where we cannot verify that there is a separate write-capable connection
248985bc6df2Sdrh ** on hand to keep the shared-memory up-to-date with the WAL file.
249085bc6df2Sdrh **
249185bc6df2Sdrh ** This can happen, for example, when the shared-memory is implemented by
249285bc6df2Sdrh ** memory-mapping a *-shm file, where a prior writer has shut down and
249385bc6df2Sdrh ** left the *-shm file on disk, and now the present connection is trying
249485bc6df2Sdrh ** to use that database but lacks write permission on the *-shm file.
249585bc6df2Sdrh ** Other scenarios are also possible, depending on the VFS implementation.
249685bc6df2Sdrh **
249785bc6df2Sdrh ** Precondition:
249885bc6df2Sdrh **
249985bc6df2Sdrh ** The *-wal file has been read and an appropriate wal-index has been
250085bc6df2Sdrh ** constructed in pWal->apWiData[] using heap memory instead of shared
250185bc6df2Sdrh ** memory.
250211caf4f4Sdan **
250311caf4f4Sdan ** If this function returns SQLITE_OK, then the read transaction has
250411caf4f4Sdan ** been successfully opened. In this case output variable (*pChanged)
250511caf4f4Sdan ** is set to true before returning if the caller should discard the
250611caf4f4Sdan ** contents of the page cache before proceeding. Or, if it returns
250711caf4f4Sdan ** WAL_RETRY, then the heap memory wal-index has been discarded and
250811caf4f4Sdan ** the caller should retry opening the read transaction from the
250911caf4f4Sdan ** beginning (including attempting to map the *-shm file).
251011caf4f4Sdan **
251111caf4f4Sdan ** If an error occurs, an SQLite error code is returned.
251211caf4f4Sdan */
walBeginShmUnreliable(Wal * pWal,int * pChanged)251385bc6df2Sdrh static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
251411caf4f4Sdan i64 szWal; /* Size of wal file on disk in bytes */
251511caf4f4Sdan i64 iOffset; /* Current offset when reading wal file */
251611caf4f4Sdan u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
251711caf4f4Sdan u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
251811caf4f4Sdan int szFrame; /* Number of bytes in buffer aFrame[] */
251911caf4f4Sdan u8 *aData; /* Pointer to data part of aFrame buffer */
252011caf4f4Sdan volatile void *pDummy; /* Dummy argument for xShmMap */
252111caf4f4Sdan int rc; /* Return code */
252211caf4f4Sdan u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
252311caf4f4Sdan
252485bc6df2Sdrh assert( pWal->bShmUnreliable );
252511caf4f4Sdan assert( pWal->readOnly & WAL_SHM_RDONLY );
252611caf4f4Sdan assert( pWal->nWiData>0 && pWal->apWiData[0] );
252711caf4f4Sdan
252811caf4f4Sdan /* Take WAL_READ_LOCK(0). This has the effect of preventing any
252985bc6df2Sdrh ** writers from running a checkpoint, but does not stop them
253011caf4f4Sdan ** from running recovery. */
253111caf4f4Sdan rc = walLockShared(pWal, WAL_READ_LOCK(0));
253211caf4f4Sdan if( rc!=SQLITE_OK ){
2533ab548384Sdan if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
253485bc6df2Sdrh goto begin_unreliable_shm_out;
253511caf4f4Sdan }
253611caf4f4Sdan pWal->readLock = 0;
253711caf4f4Sdan
253885bc6df2Sdrh /* Check to see if a separate writer has attached to the shared-memory area,
253985bc6df2Sdrh ** thus making the shared-memory "reliable" again. Do this by invoking
254085bc6df2Sdrh ** the xShmMap() routine of the VFS and looking to see if the return
254185bc6df2Sdrh ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
254211caf4f4Sdan **
254385bc6df2Sdrh ** If the shared-memory is now "reliable" return WAL_RETRY, which will
254485bc6df2Sdrh ** cause the heap-memory WAL-index to be discarded and the actual
254585bc6df2Sdrh ** shared memory to be used in its place.
2546870655bbSdrh **
2547870655bbSdrh ** This step is important because, even though this connection is holding
2548870655bbSdrh ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
2549870655bbSdrh ** have already checkpointed the WAL file and, while the current
2550870655bbSdrh ** is active, wrap the WAL and start overwriting frames that this
2551870655bbSdrh ** process wants to use.
2552870655bbSdrh **
2553870655bbSdrh ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
2554870655bbSdrh ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
2555870655bbSdrh ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
2556870655bbSdrh ** even if some external agent does a "chmod" to make the shared-memory
2557870655bbSdrh ** writable by us, until sqlite3OsShmUnmap() has been called.
2558870655bbSdrh ** This is a requirement on the VFS implementation.
255985bc6df2Sdrh */
256011caf4f4Sdan rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
25619214c1efSdrh assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
25627e45e3a5Sdrh if( rc!=SQLITE_READONLY_CANTINIT ){
256311caf4f4Sdan rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
256485bc6df2Sdrh goto begin_unreliable_shm_out;
256511caf4f4Sdan }
256611caf4f4Sdan
2567870655bbSdrh /* We reach this point only if the real shared-memory is still unreliable.
256885bc6df2Sdrh ** Assume the in-memory WAL-index substitute is correct and load it
256985bc6df2Sdrh ** into pWal->hdr.
257085bc6df2Sdrh */
257111caf4f4Sdan memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
257285bc6df2Sdrh
2573870655bbSdrh /* Make sure some writer hasn't come in and changed the WAL file out
2574870655bbSdrh ** from under us, then disconnected, while we were not looking.
257585bc6df2Sdrh */
257611caf4f4Sdan rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
2577ab548384Sdan if( rc!=SQLITE_OK ){
257885bc6df2Sdrh goto begin_unreliable_shm_out;
2579ab548384Sdan }
2580ab548384Sdan if( szWal<WAL_HDRSIZE ){
258111caf4f4Sdan /* If the wal file is too small to contain a wal-header and the
258211caf4f4Sdan ** wal-index header has mxFrame==0, then it must be safe to proceed
258311caf4f4Sdan ** reading the database file only. However, the page cache cannot
258411caf4f4Sdan ** be trusted, as a read/write connection may have connected, written
258511caf4f4Sdan ** the db, run a checkpoint, truncated the wal file and disconnected
258611caf4f4Sdan ** since this client's last read transaction. */
258711caf4f4Sdan *pChanged = 1;
2588ab548384Sdan rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
258985bc6df2Sdrh goto begin_unreliable_shm_out;
259011caf4f4Sdan }
259111caf4f4Sdan
259211caf4f4Sdan /* Check the salt keys at the start of the wal file still match. */
259311caf4f4Sdan rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
259411caf4f4Sdan if( rc!=SQLITE_OK ){
259585bc6df2Sdrh goto begin_unreliable_shm_out;
259611caf4f4Sdan }
259711caf4f4Sdan if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
2598870655bbSdrh /* Some writer has wrapped the WAL file while we were not looking.
2599870655bbSdrh ** Return WAL_RETRY which will cause the in-memory WAL-index to be
2600870655bbSdrh ** rebuilt. */
260111caf4f4Sdan rc = WAL_RETRY;
260285bc6df2Sdrh goto begin_unreliable_shm_out;
260311caf4f4Sdan }
260411caf4f4Sdan
260511caf4f4Sdan /* Allocate a buffer to read frames into */
2606f208abddSdrh assert( (pWal->szPage & (pWal->szPage-1))==0 );
2607f208abddSdrh assert( pWal->szPage>=512 && pWal->szPage<=65536 );
2608f208abddSdrh szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
260911caf4f4Sdan aFrame = (u8 *)sqlite3_malloc64(szFrame);
261011caf4f4Sdan if( aFrame==0 ){
261111caf4f4Sdan rc = SQLITE_NOMEM_BKPT;
261285bc6df2Sdrh goto begin_unreliable_shm_out;
261311caf4f4Sdan }
261411caf4f4Sdan aData = &aFrame[WAL_FRAME_HDRSIZE];
261511caf4f4Sdan
2616cbd33219Sdan /* Check to see if a complete transaction has been appended to the
2617cbd33219Sdan ** wal file since the heap-memory wal-index was created. If so, the
2618cbd33219Sdan ** heap-memory wal-index is discarded and WAL_RETRY returned to
2619cbd33219Sdan ** the caller. */
262011caf4f4Sdan aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
262111caf4f4Sdan aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
2622f208abddSdrh for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
262311caf4f4Sdan iOffset+szFrame<=szWal;
262411caf4f4Sdan iOffset+=szFrame
262511caf4f4Sdan ){
262611caf4f4Sdan u32 pgno; /* Database page number for frame */
262711caf4f4Sdan u32 nTruncate; /* dbsize field from frame header */
262811caf4f4Sdan
262911caf4f4Sdan /* Read and decode the next log frame. */
263011caf4f4Sdan rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
2631ab548384Sdan if( rc!=SQLITE_OK ) break;
263211caf4f4Sdan if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
263311caf4f4Sdan
2634cbd33219Sdan /* If nTruncate is non-zero, then a complete transaction has been
2635cbd33219Sdan ** appended to this wal file. Set rc to WAL_RETRY and break out of
2636cbd33219Sdan ** the loop. */
263711caf4f4Sdan if( nTruncate ){
263811caf4f4Sdan rc = WAL_RETRY;
263911caf4f4Sdan break;
264011caf4f4Sdan }
264111caf4f4Sdan }
264211caf4f4Sdan pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
264311caf4f4Sdan pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
264411caf4f4Sdan
264585bc6df2Sdrh begin_unreliable_shm_out:
264611caf4f4Sdan sqlite3_free(aFrame);
264711caf4f4Sdan if( rc!=SQLITE_OK ){
264811caf4f4Sdan int i;
264911caf4f4Sdan for(i=0; i<pWal->nWiData; i++){
265011caf4f4Sdan sqlite3_free((void*)pWal->apWiData[i]);
265111caf4f4Sdan pWal->apWiData[i] = 0;
265211caf4f4Sdan }
265385bc6df2Sdrh pWal->bShmUnreliable = 0;
265411caf4f4Sdan sqlite3WalEndReadTransaction(pWal);
265511caf4f4Sdan *pChanged = 1;
265611caf4f4Sdan }
265711caf4f4Sdan return rc;
265811caf4f4Sdan }
265911caf4f4Sdan
266011caf4f4Sdan /*
266173b64e4dSdrh ** Attempt to start a read transaction. This might fail due to a race or
266273b64e4dSdrh ** other transient condition. When that happens, it returns WAL_RETRY to
266373b64e4dSdrh ** indicate to the caller that it is safe to retry immediately.
266473b64e4dSdrh **
2665a927e94eSdrh ** On success return SQLITE_OK. On a permanent failure (such an
266673b64e4dSdrh ** I/O error or an SQLITE_BUSY because another process is running
266773b64e4dSdrh ** recovery) return a positive error code.
266873b64e4dSdrh **
2669a927e94eSdrh ** The useWal parameter is true to force the use of the WAL and disable
2670a927e94eSdrh ** the case where the WAL is bypassed because it has been completely
2671a927e94eSdrh ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
2672a927e94eSdrh ** to make a copy of the wal-index header into pWal->hdr. If the
2673a927e94eSdrh ** wal-index header has changed, *pChanged is set to 1 (as an indication
2674183f0aa6Sdrh ** to the caller that the local page cache is obsolete and needs to be
2675a927e94eSdrh ** flushed.) When useWal==1, the wal-index header is assumed to already
2676a927e94eSdrh ** be loaded and the pChanged parameter is unused.
2677a927e94eSdrh **
2678a927e94eSdrh ** The caller must set the cnt parameter to the number of prior calls to
2679a927e94eSdrh ** this routine during the current read attempt that returned WAL_RETRY.
2680a927e94eSdrh ** This routine will start taking more aggressive measures to clear the
2681a927e94eSdrh ** race conditions after multiple WAL_RETRY returns, and after an excessive
2682a927e94eSdrh ** number of errors will ultimately return SQLITE_PROTOCOL. The
2683a927e94eSdrh ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
2684a927e94eSdrh ** and is not honoring the locking protocol. There is a vanishingly small
2685a927e94eSdrh ** chance that SQLITE_PROTOCOL could be returned because of a run of really
2686a927e94eSdrh ** bad luck when there is lots of contention for the wal-index, but that
2687a927e94eSdrh ** possibility is so small that it can be safely neglected, we believe.
2688a927e94eSdrh **
268973b64e4dSdrh ** On success, this routine obtains a read lock on
269073b64e4dSdrh ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
269173b64e4dSdrh ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
269273b64e4dSdrh ** that means the Wal does not hold any read lock. The reader must not
269373b64e4dSdrh ** access any database page that is modified by a WAL frame up to and
269473b64e4dSdrh ** including frame number aReadMark[pWal->readLock]. The reader will
269573b64e4dSdrh ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
269673b64e4dSdrh ** Or if pWal->readLock==0, then the reader will ignore the WAL
269773b64e4dSdrh ** completely and get all content directly from the database file.
2698a927e94eSdrh ** If the useWal parameter is 1 then the WAL will never be ignored and
2699a927e94eSdrh ** this routine will always set pWal->readLock>0 on success.
270073b64e4dSdrh ** When the read transaction is completed, the caller must release the
270173b64e4dSdrh ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
270273b64e4dSdrh **
270373b64e4dSdrh ** This routine uses the nBackfill and aReadMark[] fields of the header
270473b64e4dSdrh ** to select a particular WAL_READ_LOCK() that strives to let the
270573b64e4dSdrh ** checkpoint process do as much work as possible. This routine might
270673b64e4dSdrh ** update values of the aReadMark[] array in the header, but if it does
270773b64e4dSdrh ** so it takes care to hold an exclusive lock on the corresponding
270873b64e4dSdrh ** WAL_READ_LOCK() while changing values.
270973b64e4dSdrh */
walTryBeginRead(Wal * pWal,int * pChanged,int useWal,int cnt)2710aab4c02eSdrh static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
271173b64e4dSdrh volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
271273b64e4dSdrh u32 mxReadMark; /* Largest aReadMark[] value */
271373b64e4dSdrh int mxI; /* Index of largest aReadMark[] value */
271473b64e4dSdrh int i; /* Loop counter */
271513a3cb82Sdan int rc = SQLITE_OK; /* Return code */
2716c49e960dSdrh u32 mxFrame; /* Wal frame to lock to */
2717c438efd6Sdrh
271861e4acecSdrh assert( pWal->readLock<0 ); /* Not currently locked */
2719c438efd6Sdrh
27202e9b0923Sdrh /* useWal may only be set for read/write connections */
27212e9b0923Sdrh assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
27222e9b0923Sdrh
2723658d76c9Sdrh /* Take steps to avoid spinning forever if there is a protocol error.
2724658d76c9Sdrh **
2725658d76c9Sdrh ** Circumstances that cause a RETRY should only last for the briefest
2726658d76c9Sdrh ** instances of time. No I/O or other system calls are done while the
2727658d76c9Sdrh ** locks are held, so the locks should not be held for very long. But
2728658d76c9Sdrh ** if we are unlucky, another process that is holding a lock might get
2729658d76c9Sdrh ** paged out or take a page-fault that is time-consuming to resolve,
2730658d76c9Sdrh ** during the few nanoseconds that it is holding the lock. In that case,
2731658d76c9Sdrh ** it might take longer than normal for the lock to free.
2732658d76c9Sdrh **
2733658d76c9Sdrh ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
2734658d76c9Sdrh ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
2735658d76c9Sdrh ** is more of a scheduler yield than an actual delay. But on the 10th
2736658d76c9Sdrh ** an subsequent retries, the delays start becoming longer and longer,
27375b6e3b97Sdrh ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
27385b6e3b97Sdrh ** The total delay time before giving up is less than 10 seconds.
2739658d76c9Sdrh */
2740aab4c02eSdrh if( cnt>5 ){
2741658d76c9Sdrh int nDelay = 1; /* Pause time in microseconds */
274203c6967fSdrh if( cnt>100 ){
274303c6967fSdrh VVA_ONLY( pWal->lockError = 1; )
274403c6967fSdrh return SQLITE_PROTOCOL;
274503c6967fSdrh }
27465b6e3b97Sdrh if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
2747658d76c9Sdrh sqlite3OsSleep(pWal->pVfs, nDelay);
2748aab4c02eSdrh }
2749aab4c02eSdrh
275073b64e4dSdrh if( !useWal ){
275111caf4f4Sdan assert( rc==SQLITE_OK );
275285bc6df2Sdrh if( pWal->bShmUnreliable==0 ){
27537ed91f23Sdrh rc = walIndexReadHdr(pWal, pChanged);
275411caf4f4Sdan }
275573b64e4dSdrh if( rc==SQLITE_BUSY ){
275673b64e4dSdrh /* If there is not a recovery running in another thread or process
275773b64e4dSdrh ** then convert BUSY errors to WAL_RETRY. If recovery is known to
275873b64e4dSdrh ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
275973b64e4dSdrh ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
276073b64e4dSdrh ** would be technically correct. But the race is benign since with
276173b64e4dSdrh ** WAL_RETRY this routine will be called again and will probably be
276273b64e4dSdrh ** right on the second iteration.
276373b64e4dSdrh */
27647d4514a4Sdan if( pWal->apWiData[0]==0 ){
27657d4514a4Sdan /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
27667d4514a4Sdan ** We assume this is a transient condition, so return WAL_RETRY. The
27677d4514a4Sdan ** xShmMap() implementation used by the default unix and win32 VFS
27687d4514a4Sdan ** modules may return SQLITE_BUSY due to a race condition in the
27697d4514a4Sdan ** code that determines whether or not the shared-memory region
27707d4514a4Sdan ** must be zeroed before the requested page is returned.
27717d4514a4Sdan */
27727d4514a4Sdan rc = WAL_RETRY;
27737d4514a4Sdan }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
277473b64e4dSdrh walUnlockShared(pWal, WAL_RECOVER_LOCK);
277573b64e4dSdrh rc = WAL_RETRY;
277673b64e4dSdrh }else if( rc==SQLITE_BUSY ){
277773b64e4dSdrh rc = SQLITE_BUSY_RECOVERY;
277873b64e4dSdrh }
277973b64e4dSdrh }
2780c438efd6Sdrh if( rc!=SQLITE_OK ){
278173b64e4dSdrh return rc;
278273b64e4dSdrh }
278385bc6df2Sdrh else if( pWal->bShmUnreliable ){
278485bc6df2Sdrh return walBeginShmUnreliable(pWal, pChanged);
278511caf4f4Sdan }
2786a927e94eSdrh }
278773b64e4dSdrh
278892c02da3Sdan assert( pWal->nWiData>0 );
27892e9b0923Sdrh assert( pWal->apWiData[0]!=0 );
27902e9b0923Sdrh pInfo = walCkptInfo(pWal);
27918b4f231cSdan if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
2792fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
279321f2bafdSdan && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
2794fc1acf33Sdan #endif
2795fc1acf33Sdan ){
279673b64e4dSdrh /* The WAL has been completely backfilled (or it is empty).
279773b64e4dSdrh ** and can be safely ignored.
279873b64e4dSdrh */
279973b64e4dSdrh rc = walLockShared(pWal, WAL_READ_LOCK(0));
28008c408004Sdan walShmBarrier(pWal);
280173b64e4dSdrh if( rc==SQLITE_OK ){
28022e9b0923Sdrh if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
2803493cc590Sdan /* It is not safe to allow the reader to continue here if frames
2804493cc590Sdan ** may have been appended to the log before READ_LOCK(0) was obtained.
2805493cc590Sdan ** When holding READ_LOCK(0), the reader ignores the entire log file,
2806493cc590Sdan ** which implies that the database file contains a trustworthy
280760ec914cSpeter.d.reid ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
2808493cc590Sdan ** happening, this is usually correct.
2809493cc590Sdan **
2810493cc590Sdan ** However, if frames have been appended to the log (or if the log
2811493cc590Sdan ** is wrapped and written for that matter) before the READ_LOCK(0)
2812493cc590Sdan ** is obtained, that is not necessarily true. A checkpointer may
2813493cc590Sdan ** have started to backfill the appended frames but crashed before
2814493cc590Sdan ** it finished. Leaving a corrupt image in the database file.
2815493cc590Sdan */
281673b64e4dSdrh walUnlockShared(pWal, WAL_READ_LOCK(0));
281773b64e4dSdrh return WAL_RETRY;
281873b64e4dSdrh }
281973b64e4dSdrh pWal->readLock = 0;
282073b64e4dSdrh return SQLITE_OK;
282173b64e4dSdrh }else if( rc!=SQLITE_BUSY ){
282273b64e4dSdrh return rc;
2823c438efd6Sdrh }
2824c438efd6Sdrh }
2825ba51590bSdan
282673b64e4dSdrh /* If we get this far, it means that the reader will want to use
282773b64e4dSdrh ** the WAL to get at content from recent commits. The job now is
282873b64e4dSdrh ** to select one of the aReadMark[] entries that is closest to
282973b64e4dSdrh ** but not exceeding pWal->hdr.mxFrame and lock that entry.
283073b64e4dSdrh */
283173b64e4dSdrh mxReadMark = 0;
283273b64e4dSdrh mxI = 0;
2833fc1acf33Sdan mxFrame = pWal->hdr.mxFrame;
2834fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
2835818b11aeSdan if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
2836818b11aeSdan mxFrame = pWal->pSnapshot->mxFrame;
2837818b11aeSdan }
2838fc1acf33Sdan #endif
283973b64e4dSdrh for(i=1; i<WAL_NREADER; i++){
2840876c7ea3Sdrh u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
2841fc1acf33Sdan if( mxReadMark<=thisMark && thisMark<=mxFrame ){
2842db7f647eSdrh assert( thisMark!=READMARK_NOT_USED );
284373b64e4dSdrh mxReadMark = thisMark;
284473b64e4dSdrh mxI = i;
284573b64e4dSdrh }
284673b64e4dSdrh }
284766dfec8bSdrh if( (pWal->readOnly & WAL_SHM_RDONLY)==0
2848fc1acf33Sdan && (mxReadMark<mxFrame || mxI==0)
284966dfec8bSdrh ){
2850d54ff60bSdan for(i=1; i<WAL_NREADER; i++){
2851ab372773Sdrh rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
285273b64e4dSdrh if( rc==SQLITE_OK ){
28533e42b991Sdan AtomicStore(pInfo->aReadMark+i,mxFrame);
28543e42b991Sdan mxReadMark = mxFrame;
285573b64e4dSdrh mxI = i;
285673b64e4dSdrh walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
285773b64e4dSdrh break;
285838933f2cSdrh }else if( rc!=SQLITE_BUSY ){
285938933f2cSdrh return rc;
286073b64e4dSdrh }
286173b64e4dSdrh }
286273b64e4dSdrh }
2863658d76c9Sdrh if( mxI==0 ){
28645bf39346Sdrh assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
28657e45e3a5Sdrh return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
2866658d76c9Sdrh }
286773b64e4dSdrh
286873b64e4dSdrh rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
286973b64e4dSdrh if( rc ){
287073b64e4dSdrh return rc==SQLITE_BUSY ? WAL_RETRY : rc;
287173b64e4dSdrh }
2872eb8cb3a8Sdan /* Now that the read-lock has been obtained, check that neither the
2873eb8cb3a8Sdan ** value in the aReadMark[] array or the contents of the wal-index
2874eb8cb3a8Sdan ** header have changed.
2875eb8cb3a8Sdan **
2876eb8cb3a8Sdan ** It is necessary to check that the wal-index header did not change
2877eb8cb3a8Sdan ** between the time it was read and when the shared-lock was obtained
2878eb8cb3a8Sdan ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
2879eb8cb3a8Sdan ** that the log file may have been wrapped by a writer, or that frames
2880eb8cb3a8Sdan ** that occur later in the log than pWal->hdr.mxFrame may have been
2881eb8cb3a8Sdan ** copied into the database by a checkpointer. If either of these things
2882eb8cb3a8Sdan ** happened, then reading the database with the current value of
2883eb8cb3a8Sdan ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
2884eb8cb3a8Sdan ** instead.
2885eb8cb3a8Sdan **
2886b8c7cfb8Sdan ** Before checking that the live wal-index header has not changed
2887b8c7cfb8Sdan ** since it was read, set Wal.minFrame to the first frame in the wal
2888b8c7cfb8Sdan ** file that has not yet been checkpointed. This client will not need
2889b8c7cfb8Sdan ** to read any frames earlier than minFrame from the wal file - they
2890b8c7cfb8Sdan ** can be safely read directly from the database file.
2891b8c7cfb8Sdan **
2892b8c7cfb8Sdan ** Because a ShmBarrier() call is made between taking the copy of
2893b8c7cfb8Sdan ** nBackfill and checking that the wal-header in shared-memory still
2894b8c7cfb8Sdan ** matches the one cached in pWal->hdr, it is guaranteed that the
2895b8c7cfb8Sdan ** checkpointer that set nBackfill was not working with a wal-index
2896b8c7cfb8Sdan ** header newer than that cached in pWal->hdr. If it were, that could
2897b8c7cfb8Sdan ** cause a problem. The checkpointer could omit to checkpoint
2898b8c7cfb8Sdan ** a version of page X that lies before pWal->minFrame (call that version
2899b8c7cfb8Sdan ** A) on the basis that there is a newer version (version B) of the same
2900b8c7cfb8Sdan ** page later in the wal file. But if version B happens to like past
2901b8c7cfb8Sdan ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
2902b8c7cfb8Sdan ** that it can read version A from the database file. However, since
2903b8c7cfb8Sdan ** we can guarantee that the checkpointer that set nBackfill could not
2904b8c7cfb8Sdan ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
2905eb8cb3a8Sdan */
2906876c7ea3Sdrh pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
29078c408004Sdan walShmBarrier(pWal);
2908876c7ea3Sdrh if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
29094280eb30Sdan || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
291073b64e4dSdrh ){
291173b64e4dSdrh walUnlockShared(pWal, WAL_READ_LOCK(mxI));
291273b64e4dSdrh return WAL_RETRY;
291373b64e4dSdrh }else{
2914db7f647eSdrh assert( mxReadMark<=pWal->hdr.mxFrame );
29155eba1f60Sshaneh pWal->readLock = (i16)mxI;
291673b64e4dSdrh }
291773b64e4dSdrh return rc;
291873b64e4dSdrh }
291973b64e4dSdrh
2920bc88711dSdrh #ifdef SQLITE_ENABLE_SNAPSHOT
292173b64e4dSdrh /*
292293f51132Sdan ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
292393f51132Sdan ** variable so that older snapshots can be accessed. To do this, loop
292493f51132Sdan ** through all wal frames from nBackfillAttempted to (nBackfill+1),
292593f51132Sdan ** comparing their content to the corresponding page with the database
292693f51132Sdan ** file, if any. Set nBackfillAttempted to the frame number of the
292793f51132Sdan ** first frame for which the wal file content matches the db file.
292893f51132Sdan **
292993f51132Sdan ** This is only really safe if the file-system is such that any page
293093f51132Sdan ** writes made by earlier checkpointers were atomic operations, which
293193f51132Sdan ** is not always true. It is also possible that nBackfillAttempted
293293f51132Sdan ** may be left set to a value larger than expected, if a wal frame
293393f51132Sdan ** contains content that duplicate of an earlier version of the same
293493f51132Sdan ** page.
293593f51132Sdan **
293693f51132Sdan ** SQLITE_OK is returned if successful, or an SQLite error code if an
293793f51132Sdan ** error occurs. It is not an error if nBackfillAttempted cannot be
293893f51132Sdan ** decreased at all.
29391158498dSdan */
sqlite3WalSnapshotRecover(Wal * pWal)29401158498dSdan int sqlite3WalSnapshotRecover(Wal *pWal){
29411158498dSdan int rc;
29421158498dSdan
294393f51132Sdan assert( pWal->readLock>=0 );
29441158498dSdan rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
29451158498dSdan if( rc==SQLITE_OK ){
29461158498dSdan volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
29471158498dSdan int szPage = (int)pWal->szPage;
29486a9e7f16Sdan i64 szDb; /* Size of db file in bytes */
29496a9e7f16Sdan
29506a9e7f16Sdan rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
29516a9e7f16Sdan if( rc==SQLITE_OK ){
29521158498dSdan void *pBuf1 = sqlite3_malloc(szPage);
29531158498dSdan void *pBuf2 = sqlite3_malloc(szPage);
29541158498dSdan if( pBuf1==0 || pBuf2==0 ){
29551158498dSdan rc = SQLITE_NOMEM;
29561158498dSdan }else{
29571158498dSdan u32 i = pInfo->nBackfillAttempted;
29588b4f231cSdan for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
29594ece2f26Sdrh WalHashLoc sLoc; /* Hash table location */
29601158498dSdan u32 pgno; /* Page number in db file */
29611158498dSdan i64 iDbOff; /* Offset of db file entry */
29621158498dSdan i64 iWalOff; /* Offset of wal file entry */
29631158498dSdan
29644ece2f26Sdrh rc = walHashGet(pWal, walFramePage(i), &sLoc);
29656a9e7f16Sdan if( rc!=SQLITE_OK ) break;
296671c3ea75Sdrh assert( i - sLoc.iZero - 1 >=0 );
296771c3ea75Sdrh pgno = sLoc.aPgno[i-sLoc.iZero-1];
29681158498dSdan iDbOff = (i64)(pgno-1) * szPage;
29696a9e7f16Sdan
29706a9e7f16Sdan if( iDbOff+szPage<=szDb ){
29711158498dSdan iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
29721158498dSdan rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
29731158498dSdan
29741158498dSdan if( rc==SQLITE_OK ){
29751158498dSdan rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
29761158498dSdan }
29771158498dSdan
29781158498dSdan if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
29791158498dSdan break;
29801158498dSdan }
29816a9e7f16Sdan }
29821158498dSdan
29831158498dSdan pInfo->nBackfillAttempted = i-1;
29841158498dSdan }
29851158498dSdan }
29861158498dSdan
29871158498dSdan sqlite3_free(pBuf1);
29881158498dSdan sqlite3_free(pBuf2);
29896a9e7f16Sdan }
29901158498dSdan walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
29911158498dSdan }
29921158498dSdan
29931158498dSdan return rc;
29941158498dSdan }
2995bc88711dSdrh #endif /* SQLITE_ENABLE_SNAPSHOT */
29961158498dSdan
29971158498dSdan /*
299873b64e4dSdrh ** Begin a read transaction on the database.
299973b64e4dSdrh **
300073b64e4dSdrh ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
300173b64e4dSdrh ** it takes a snapshot of the state of the WAL and wal-index for the current
300273b64e4dSdrh ** instant in time. The current thread will continue to use this snapshot.
300373b64e4dSdrh ** Other threads might append new content to the WAL and wal-index but
300473b64e4dSdrh ** that extra content is ignored by the current thread.
300573b64e4dSdrh **
300673b64e4dSdrh ** If the database contents have changes since the previous read
300773b64e4dSdrh ** transaction, then *pChanged is set to 1 before returning. The
30088741d0ddSdrh ** Pager layer will use this to know that its cache is stale and
300973b64e4dSdrh ** needs to be flushed.
301073b64e4dSdrh */
sqlite3WalBeginReadTransaction(Wal * pWal,int * pChanged)301166dfec8bSdrh int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
301273b64e4dSdrh int rc; /* Return code */
3013aab4c02eSdrh int cnt = 0; /* Number of TryBeginRead attempts */
301491960aa5Sdrh #ifdef SQLITE_ENABLE_SNAPSHOT
301591960aa5Sdrh int bChanged = 0;
301691960aa5Sdrh WalIndexHdr *pSnapshot = pWal->pSnapshot;
301791960aa5Sdrh #endif
30188714de97Sdan
3019d0e6d133Sdan assert( pWal->ckptLock==0 );
302073b64e4dSdrh
3021fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
30228714de97Sdan if( pSnapshot ){
30238714de97Sdan if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
30248714de97Sdan bChanged = 1;
30258714de97Sdan }
30268714de97Sdan
30278714de97Sdan /* It is possible that there is a checkpointer thread running
30288714de97Sdan ** concurrent with this code. If this is the case, it may be that the
30298714de97Sdan ** checkpointer has already determined that it will checkpoint
30308714de97Sdan ** snapshot X, where X is later in the wal file than pSnapshot, but
30318714de97Sdan ** has not yet set the pInfo->nBackfillAttempted variable to indicate
30328714de97Sdan ** its intent. To avoid the race condition this leads to, ensure that
30338714de97Sdan ** there is no checkpointer process by taking a shared CKPT lock
30348714de97Sdan ** before checking pInfo->nBackfillAttempted. */
3035fc87ab8cSdan (void)walEnableBlocking(pWal);
30368714de97Sdan rc = walLockShared(pWal, WAL_CKPT_LOCK);
303758021b23Sdan walDisableBlocking(pWal);
30388714de97Sdan
30398714de97Sdan if( rc!=SQLITE_OK ){
30408714de97Sdan return rc;
30418714de97Sdan }
3042d0e6d133Sdan pWal->ckptLock = 1;
30438714de97Sdan }
304497ccc1bdSdan #endif
304597ccc1bdSdan
304673b64e4dSdrh do{
3047aab4c02eSdrh rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
304873b64e4dSdrh }while( rc==WAL_RETRY );
3049ab1cc746Sdrh testcase( (rc&0xff)==SQLITE_BUSY );
3050ab1cc746Sdrh testcase( (rc&0xff)==SQLITE_IOERR );
3051ab1cc746Sdrh testcase( rc==SQLITE_PROTOCOL );
3052ab1cc746Sdrh testcase( rc==SQLITE_OK );
3053fc1acf33Sdan
3054fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
3055fc1acf33Sdan if( rc==SQLITE_OK ){
3056998147ecSdrh if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
305765127cd5Sdan /* At this point the client has a lock on an aReadMark[] slot holding
30583bf83ccdSdan ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
30593bf83ccdSdan ** is populated with the wal-index header corresponding to the head
30603bf83ccdSdan ** of the wal file. Verify that pSnapshot is still valid before
30613bf83ccdSdan ** continuing. Reasons why pSnapshot might no longer be valid:
306265127cd5Sdan **
3063998147ecSdrh ** (1) The WAL file has been reset since the snapshot was taken.
3064998147ecSdrh ** In this case, the salt will have changed.
306565127cd5Sdan **
3066998147ecSdrh ** (2) A checkpoint as been attempted that wrote frames past
3067998147ecSdrh ** pSnapshot->mxFrame into the database file. Note that the
3068998147ecSdrh ** checkpoint need not have completed for this to cause problems.
306965127cd5Sdan */
3070fc1acf33Sdan volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
307165127cd5Sdan
307271b62fa4Sdrh assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
3073fc1acf33Sdan assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
307465127cd5Sdan
30753bf83ccdSdan /* Check that the wal file has not been wrapped. Assuming that it has
3076a7aeb398Sdan ** not, also check that no checkpointer has attempted to checkpoint any
3077a7aeb398Sdan ** frames beyond pSnapshot->mxFrame. If either of these conditions are
30788d4b7a3fSdan ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
30793bf83ccdSdan ** with *pSnapshot and set *pChanged as appropriate for opening the
30803bf83ccdSdan ** snapshot. */
3081a7aeb398Sdan if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
3082998147ecSdrh && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
308365127cd5Sdan ){
30840f308f5dSdan assert( pWal->readLock>0 );
3085fc1acf33Sdan memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
3086fc1acf33Sdan *pChanged = bChanged;
3087fc1acf33Sdan }else{
30888d4b7a3fSdan rc = SQLITE_ERROR_SNAPSHOT;
3089fc1acf33Sdan }
309065127cd5Sdan
30918714de97Sdan /* A client using a non-current snapshot may not ignore any frames
30928714de97Sdan ** from the start of the wal file. This is because, for a system
30938714de97Sdan ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
30948714de97Sdan ** have omitted to checkpoint a frame earlier than minFrame in
30958714de97Sdan ** the file because there exists a frame after iSnapshot that
30968714de97Sdan ** is the same database page. */
3097f5778751Sdan pWal->minFrame = 1;
30983bf83ccdSdan
3099fc1acf33Sdan if( rc!=SQLITE_OK ){
3100fc1acf33Sdan sqlite3WalEndReadTransaction(pWal);
3101fc1acf33Sdan }
3102fc1acf33Sdan }
3103fc1acf33Sdan }
31048714de97Sdan
31058714de97Sdan /* Release the shared CKPT lock obtained above. */
3106d0e6d133Sdan if( pWal->ckptLock ){
3107d0e6d133Sdan assert( pSnapshot );
31088714de97Sdan walUnlockShared(pWal, WAL_CKPT_LOCK);
3109d0e6d133Sdan pWal->ckptLock = 0;
31108714de97Sdan }
3111fc1acf33Sdan #endif
3112c438efd6Sdrh return rc;
3113c438efd6Sdrh }
3114c438efd6Sdrh
3115c438efd6Sdrh /*
311673b64e4dSdrh ** Finish with a read transaction. All this does is release the
311773b64e4dSdrh ** read-lock.
3118c438efd6Sdrh */
sqlite3WalEndReadTransaction(Wal * pWal)311973b64e4dSdrh void sqlite3WalEndReadTransaction(Wal *pWal){
312058021b23Sdan sqlite3WalEndWriteTransaction(pWal);
3121bc9fc18eSdan if( pWal->readLock>=0 ){
312273b64e4dSdrh walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
312373b64e4dSdrh pWal->readLock = -1;
312473b64e4dSdrh }
3125c438efd6Sdrh }
3126c438efd6Sdrh
3127c438efd6Sdrh /*
312899bd1097Sdan ** Search the wal file for page pgno. If found, set *piRead to the frame that
312999bd1097Sdan ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
313099bd1097Sdan ** to zero.
313173b64e4dSdrh **
313299bd1097Sdan ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
313399bd1097Sdan ** error does occur, the final value of *piRead is undefined.
3134c438efd6Sdrh */
sqlite3WalFindFrame(Wal * pWal,Pgno pgno,u32 * piRead)313599bd1097Sdan int sqlite3WalFindFrame(
3136bb23aff3Sdan Wal *pWal, /* WAL handle */
3137bb23aff3Sdan Pgno pgno, /* Database page number to read data for */
313899bd1097Sdan u32 *piRead /* OUT: Frame number (or zero) */
3139b6e099a9Sdan ){
3140bb23aff3Sdan u32 iRead = 0; /* If !=0, WAL frame to return data from */
3141*fc7f8f81Sdrh u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
3142bb23aff3Sdan int iHash; /* Used to loop through N hash tables */
31436df003c7Sdan int iMinHash;
3144c438efd6Sdrh
3145aab4c02eSdrh /* This routine is only be called from within a read transaction. */
3146aab4c02eSdrh assert( pWal->readLock>=0 || pWal->lockError );
314773b64e4dSdrh
3148*fc7f8f81Sdrh /* If the "last page" field of the wal-index header snapshot is 0, then
3149*fc7f8f81Sdrh ** no data will be read from the wal under any circumstances. Return early
3150*fc7f8f81Sdrh ** in this case as an optimization. Likewise, if pWal->readLock==0,
3151*fc7f8f81Sdrh ** then the WAL is ignored by the reader so return early, as if the
3152*fc7f8f81Sdrh ** WAL were empty.
3153bb23aff3Sdan */
3154*fc7f8f81Sdrh if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
315599bd1097Sdan *piRead = 0;
3156bb23aff3Sdan return SQLITE_OK;
3157bb23aff3Sdan }
3158bb23aff3Sdan
3159bb23aff3Sdan /* Search the hash table or tables for an entry matching page number
3160bb23aff3Sdan ** pgno. Each iteration of the following for() loop searches one
3161bb23aff3Sdan ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
3162bb23aff3Sdan **
3163a927e94eSdrh ** This code might run concurrently to the code in walIndexAppend()
3164bb23aff3Sdan ** that adds entries to the wal-index (and possibly to this hash
31656e81096fSdrh ** table). This means the value just read from the hash
3166bb23aff3Sdan ** slot (aHash[iKey]) may have been added before or after the
3167bb23aff3Sdan ** current read transaction was opened. Values added after the
3168bb23aff3Sdan ** read transaction was opened may have been written incorrectly -
3169bb23aff3Sdan ** i.e. these slots may contain garbage data. However, we assume
3170bb23aff3Sdan ** that any slots written before the current read transaction was
3171bb23aff3Sdan ** opened remain unmodified.
3172bb23aff3Sdan **
3173bb23aff3Sdan ** For the reasons above, the if(...) condition featured in the inner
3174bb23aff3Sdan ** loop of the following block is more stringent that would be required
3175bb23aff3Sdan ** if we had exclusive access to the hash-table:
3176bb23aff3Sdan **
3177bb23aff3Sdan ** (aPgno[iFrame]==pgno):
3178bb23aff3Sdan ** This condition filters out normal hash-table collisions.
3179bb23aff3Sdan **
3180bb23aff3Sdan ** (iFrame<=iLast):
3181bb23aff3Sdan ** This condition filters out entries that were added to the hash
3182bb23aff3Sdan ** table after the current read-transaction had started.
3183c438efd6Sdrh */
3184b8c7cfb8Sdan iMinHash = walFramePage(pWal->minFrame);
31858d3e15eeSdrh for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
31864ece2f26Sdrh WalHashLoc sLoc; /* Hash table location */
3187bb23aff3Sdan int iKey; /* Hash slot index */
3188519426aaSdrh int nCollide; /* Number of hash collisions remaining */
3189519426aaSdrh int rc; /* Error code */
3190f16cf653Sdrh u32 iH;
3191bb23aff3Sdan
31924ece2f26Sdrh rc = walHashGet(pWal, iHash, &sLoc);
31934280eb30Sdan if( rc!=SQLITE_OK ){
31944280eb30Sdan return rc;
31954280eb30Sdan }
3196519426aaSdrh nCollide = HASHTABLE_NSLOT;
3197f16cf653Sdrh iKey = walHash(pgno);
3198f16cf653Sdrh while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
3199680f0fe3Sdrh u32 iFrame = iH + sLoc.iZero;
320071c3ea75Sdrh if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
3201622a53d5Sdrh assert( iFrame>iRead || CORRUPT_DB );
3202bb23aff3Sdan iRead = iFrame;
3203c438efd6Sdrh }
3204519426aaSdrh if( (nCollide--)==0 ){
3205519426aaSdrh return SQLITE_CORRUPT_BKPT;
3206519426aaSdrh }
3207f16cf653Sdrh iKey = walNextHash(iKey);
3208c438efd6Sdrh }
32098d3e15eeSdrh if( iRead ) break;
3210bb23aff3Sdan }
3211c438efd6Sdrh
3212bb23aff3Sdan #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
3213bb23aff3Sdan /* If expensive assert() statements are available, do a linear search
3214bb23aff3Sdan ** of the wal-index file content. Make sure the results agree with the
3215bb23aff3Sdan ** result obtained using the hash indexes above. */
3216bb23aff3Sdan {
3217bb23aff3Sdan u32 iRead2 = 0;
3218bb23aff3Sdan u32 iTest;
321985bc6df2Sdrh assert( pWal->bShmUnreliable || pWal->minFrame>0 );
32206c9d8f64Sdan for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
322113a3cb82Sdan if( walFramePgno(pWal, iTest)==pgno ){
3222bb23aff3Sdan iRead2 = iTest;
3223c438efd6Sdrh break;
3224c438efd6Sdrh }
3225c438efd6Sdrh }
3226bb23aff3Sdan assert( iRead==iRead2 );
3227c438efd6Sdrh }
3228bb23aff3Sdan #endif
3229cd11fb28Sdan
323099bd1097Sdan *piRead = iRead;
323199bd1097Sdan return SQLITE_OK;
323299bd1097Sdan }
323399bd1097Sdan
323499bd1097Sdan /*
323599bd1097Sdan ** Read the contents of frame iRead from the wal file into buffer pOut
323699bd1097Sdan ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
323799bd1097Sdan ** error code otherwise.
3238c438efd6Sdrh */
sqlite3WalReadFrame(Wal * pWal,u32 iRead,int nOut,u8 * pOut)323999bd1097Sdan int sqlite3WalReadFrame(
324099bd1097Sdan Wal *pWal, /* WAL handle */
324199bd1097Sdan u32 iRead, /* Frame to read */
324299bd1097Sdan int nOut, /* Size of buffer pOut in bytes */
324399bd1097Sdan u8 *pOut /* Buffer to write page data to */
324499bd1097Sdan ){
3245b2eced5dSdrh int sz;
3246b2eced5dSdrh i64 iOffset;
3247b2eced5dSdrh sz = pWal->hdr.szPage;
3248b07028f7Sdrh sz = (sz&0xfe00) + ((sz&0x0001)<<16);
32499b78f791Sdrh testcase( sz<=32768 );
32509b78f791Sdrh testcase( sz>=65536 );
3251b2eced5dSdrh iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
325209b5dbc5Sdrh /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
3253f602963dSdan return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
3254c438efd6Sdrh }
3255c438efd6Sdrh
3256c438efd6Sdrh /*
3257763afe62Sdan ** Return the size of the database in pages (or zero, if unknown).
3258c438efd6Sdrh */
sqlite3WalDbsize(Wal * pWal)3259763afe62Sdan Pgno sqlite3WalDbsize(Wal *pWal){
32607e9e70b1Sdrh if( pWal && ALWAYS(pWal->readLock>=0) ){
3261763afe62Sdan return pWal->hdr.nPage;
3262763afe62Sdan }
3263763afe62Sdan return 0;
3264c438efd6Sdrh }
3265c438efd6Sdrh
326630c8629eSdan
326773b64e4dSdrh /*
326873b64e4dSdrh ** This function starts a write transaction on the WAL.
326973b64e4dSdrh **
327073b64e4dSdrh ** A read transaction must have already been started by a prior call
327173b64e4dSdrh ** to sqlite3WalBeginReadTransaction().
327273b64e4dSdrh **
327373b64e4dSdrh ** If another thread or process has written into the database since
327473b64e4dSdrh ** the read transaction was started, then it is not possible for this
327573b64e4dSdrh ** thread to write as doing so would cause a fork. So this routine
327673b64e4dSdrh ** returns SQLITE_BUSY in that case and no write transaction is started.
327773b64e4dSdrh **
327873b64e4dSdrh ** There can only be a single writer active at a time.
327930c8629eSdan */
sqlite3WalBeginWriteTransaction(Wal * pWal)328073b64e4dSdrh int sqlite3WalBeginWriteTransaction(Wal *pWal){
328173b64e4dSdrh int rc;
328273b64e4dSdrh
328358021b23Sdan #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
328458021b23Sdan /* If the write-lock is already held, then it was obtained before the
328558021b23Sdan ** read-transaction was even opened, making this call a no-op.
328658021b23Sdan ** Return early. */
328758021b23Sdan if( pWal->writeLock ){
328858021b23Sdan assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
328958021b23Sdan return SQLITE_OK;
329058021b23Sdan }
329158021b23Sdan #endif
329258021b23Sdan
329373b64e4dSdrh /* Cannot start a write transaction without first holding a read
329473b64e4dSdrh ** transaction. */
329573b64e4dSdrh assert( pWal->readLock>=0 );
3296c9a9022bSdan assert( pWal->writeLock==0 && pWal->iReCksum==0 );
329773b64e4dSdrh
32981e5de5a1Sdan if( pWal->readOnly ){
32991e5de5a1Sdan return SQLITE_READONLY;
33001e5de5a1Sdan }
33011e5de5a1Sdan
330273b64e4dSdrh /* Only one writer allowed at a time. Get the write lock. Return
330373b64e4dSdrh ** SQLITE_BUSY if unable.
330473b64e4dSdrh */
3305ab372773Sdrh rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
330673b64e4dSdrh if( rc ){
330773b64e4dSdrh return rc;
330830c8629eSdan }
3309c99597caSdrh pWal->writeLock = 1;
331073b64e4dSdrh
331173b64e4dSdrh /* If another connection has written to the database file since the
331273b64e4dSdrh ** time the read transaction on this connection was started, then
331373b64e4dSdrh ** the write is disallowed.
331473b64e4dSdrh */
33154280eb30Sdan if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
331673b64e4dSdrh walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
3317c99597caSdrh pWal->writeLock = 0;
3318f73819afSdan rc = SQLITE_BUSY_SNAPSHOT;
331930c8629eSdan }
332073b64e4dSdrh
3321c438efd6Sdrh return rc;
3322c438efd6Sdrh }
3323c438efd6Sdrh
3324c438efd6Sdrh /*
332573b64e4dSdrh ** End a write transaction. The commit has already been done. This
332673b64e4dSdrh ** routine merely releases the lock.
332773b64e4dSdrh */
sqlite3WalEndWriteTransaction(Wal * pWal)332873b64e4dSdrh int sqlite3WalEndWriteTransaction(Wal *pWal){
3329da9fe0c3Sdan if( pWal->writeLock ){
333073b64e4dSdrh walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
3331d54ff60bSdan pWal->writeLock = 0;
3332c9a9022bSdan pWal->iReCksum = 0;
3333f60b7f36Sdan pWal->truncateOnCommit = 0;
3334da9fe0c3Sdan }
333573b64e4dSdrh return SQLITE_OK;
333673b64e4dSdrh }
333773b64e4dSdrh
333873b64e4dSdrh /*
3339c438efd6Sdrh ** If any data has been written (but not committed) to the log file, this
3340c438efd6Sdrh ** function moves the write-pointer back to the start of the transaction.
3341c438efd6Sdrh **
3342c438efd6Sdrh ** Additionally, the callback function is invoked for each frame written
334373b64e4dSdrh ** to the WAL since the start of the transaction. If the callback returns
3344c438efd6Sdrh ** other than SQLITE_OK, it is not invoked again and the error code is
3345c438efd6Sdrh ** returned to the caller.
3346c438efd6Sdrh **
3347c438efd6Sdrh ** Otherwise, if the callback function does not return an error, this
3348c438efd6Sdrh ** function returns SQLITE_OK.
3349c438efd6Sdrh */
sqlite3WalUndo(Wal * pWal,int (* xUndo)(void *,Pgno),void * pUndoCtx)33507ed91f23Sdrh int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
33515543759bSdan int rc = SQLITE_OK;
33527e9e70b1Sdrh if( ALWAYS(pWal->writeLock) ){
3353027a128aSdrh Pgno iMax = pWal->hdr.mxFrame;
3354c438efd6Sdrh Pgno iFrame;
3355c438efd6Sdrh
33565d656852Sdan /* Restore the clients cache of the wal-index header to the state it
33575d656852Sdan ** was in before the client began writing to the database.
33585d656852Sdan */
3359067f3165Sdan memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
33605d656852Sdan
33610626bd65Sdan for(iFrame=pWal->hdr.mxFrame+1;
3362664f85ddSdrh ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
33630626bd65Sdan iFrame++
33640626bd65Sdan ){
33650626bd65Sdan /* This call cannot fail. Unless the page for which the page number
33660626bd65Sdan ** is passed as the second argument is (a) in the cache and
33670626bd65Sdan ** (b) has an outstanding reference, then xUndo is either a no-op
33680626bd65Sdan ** (if (a) is false) or simply expels the page from the cache (if (b)
33690626bd65Sdan ** is false).
33700626bd65Sdan **
33710626bd65Sdan ** If the upper layer is doing a rollback, it is guaranteed that there
33720626bd65Sdan ** are no outstanding references to any page other than page 1. And
33730626bd65Sdan ** page 1 is never written to the log until the transaction is
33740626bd65Sdan ** committed. As a result, the call to xUndo may not fail.
33750626bd65Sdan */
337613a3cb82Sdan assert( walFramePgno(pWal, iFrame)!=1 );
337713a3cb82Sdan rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
3378c438efd6Sdrh }
33797eb05752Sdan if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
33806f150148Sdan }
3381c438efd6Sdrh return rc;
3382c438efd6Sdrh }
3383c438efd6Sdrh
338471d89919Sdan /*
338571d89919Sdan ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
338671d89919Sdan ** values. This function populates the array with values required to
338771d89919Sdan ** "rollback" the write position of the WAL handle back to the current
338871d89919Sdan ** point in the event of a savepoint rollback (via WalSavepointUndo()).
33897ed91f23Sdrh */
sqlite3WalSavepoint(Wal * pWal,u32 * aWalData)339071d89919Sdan void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
339173b64e4dSdrh assert( pWal->writeLock );
339271d89919Sdan aWalData[0] = pWal->hdr.mxFrame;
339371d89919Sdan aWalData[1] = pWal->hdr.aFrameCksum[0];
339471d89919Sdan aWalData[2] = pWal->hdr.aFrameCksum[1];
33956e6bd565Sdan aWalData[3] = pWal->nCkpt;
33964cd78b4dSdan }
33974cd78b4dSdan
339871d89919Sdan /*
339971d89919Sdan ** Move the write position of the WAL back to the point identified by
340071d89919Sdan ** the values in the aWalData[] array. aWalData must point to an array
340171d89919Sdan ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
340271d89919Sdan ** by a call to WalSavepoint().
34037ed91f23Sdrh */
sqlite3WalSavepointUndo(Wal * pWal,u32 * aWalData)340471d89919Sdan int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
34054cd78b4dSdan int rc = SQLITE_OK;
34064cd78b4dSdan
34076e6bd565Sdan assert( pWal->writeLock );
34086e6bd565Sdan assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
34096e6bd565Sdan
34106e6bd565Sdan if( aWalData[3]!=pWal->nCkpt ){
34116e6bd565Sdan /* This savepoint was opened immediately after the write-transaction
34126e6bd565Sdan ** was started. Right after that, the writer decided to wrap around
34136e6bd565Sdan ** to the start of the log. Update the savepoint values to match.
34146e6bd565Sdan */
34156e6bd565Sdan aWalData[0] = 0;
34166e6bd565Sdan aWalData[3] = pWal->nCkpt;
34176e6bd565Sdan }
34186e6bd565Sdan
341971d89919Sdan if( aWalData[0]<pWal->hdr.mxFrame ){
342071d89919Sdan pWal->hdr.mxFrame = aWalData[0];
342171d89919Sdan pWal->hdr.aFrameCksum[0] = aWalData[1];
342271d89919Sdan pWal->hdr.aFrameCksum[1] = aWalData[2];
34234fa95bfcSdrh walCleanupHash(pWal);
34246e6bd565Sdan }
34256e6bd565Sdan
34264cd78b4dSdan return rc;
34274cd78b4dSdan }
34284cd78b4dSdan
3429c438efd6Sdrh /*
34309971e710Sdan ** This function is called just before writing a set of frames to the log
34319971e710Sdan ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
34329971e710Sdan ** to the current log file, it is possible to overwrite the start of the
34339971e710Sdan ** existing log file with the new frames (i.e. "reset" the log). If so,
34349971e710Sdan ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
34359971e710Sdan ** unchanged.
34369971e710Sdan **
34379971e710Sdan ** SQLITE_OK is returned if no error is encountered (regardless of whether
34389971e710Sdan ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
34394533cd05Sdrh ** if an error occurs.
34409971e710Sdan */
walRestartLog(Wal * pWal)34419971e710Sdan static int walRestartLog(Wal *pWal){
34429971e710Sdan int rc = SQLITE_OK;
3443aab4c02eSdrh int cnt;
3444aab4c02eSdrh
344513a3cb82Sdan if( pWal->readLock==0 ){
34469971e710Sdan volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
34479971e710Sdan assert( pInfo->nBackfill==pWal->hdr.mxFrame );
34489971e710Sdan if( pInfo->nBackfill>0 ){
3449658d76c9Sdrh u32 salt1;
3450658d76c9Sdrh sqlite3_randomness(4, &salt1);
3451ab372773Sdrh rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
34529971e710Sdan if( rc==SQLITE_OK ){
34539971e710Sdan /* If all readers are using WAL_READ_LOCK(0) (in other words if no
34549971e710Sdan ** readers are currently using the WAL), then the transactions
34559971e710Sdan ** frames will overwrite the start of the existing log. Update the
34569971e710Sdan ** wal-index header to reflect this.
34579971e710Sdan **
34589971e710Sdan ** In theory it would be Ok to update the cache of the header only
34599971e710Sdan ** at this point. But updating the actual wal-index header is also
34609971e710Sdan ** safe and means there is no special case for sqlite3WalUndo()
3461f26a1549Sdan ** to handle if this transaction is rolled back. */
34620fe8c1b9Sdan walRestartHdr(pWal, salt1);
34639971e710Sdan walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
34644533cd05Sdrh }else if( rc!=SQLITE_BUSY ){
34654533cd05Sdrh return rc;
34669971e710Sdan }
34679971e710Sdan }
34689971e710Sdan walUnlockShared(pWal, WAL_READ_LOCK(0));
34699971e710Sdan pWal->readLock = -1;
3470aab4c02eSdrh cnt = 0;
34719971e710Sdan do{
34729971e710Sdan int notUsed;
3473aab4c02eSdrh rc = walTryBeginRead(pWal, ¬Used, 1, ++cnt);
34749971e710Sdan }while( rc==WAL_RETRY );
3475c90e0811Sdrh assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
3476ab1cc746Sdrh testcase( (rc&0xff)==SQLITE_IOERR );
3477ab1cc746Sdrh testcase( rc==SQLITE_PROTOCOL );
3478ab1cc746Sdrh testcase( rc==SQLITE_OK );
34799971e710Sdan }
34809971e710Sdan return rc;
34819971e710Sdan }
34829971e710Sdan
34839971e710Sdan /*
3484d992b150Sdrh ** Information about the current state of the WAL file and where
3485d992b150Sdrh ** the next fsync should occur - passed from sqlite3WalFrames() into
3486d992b150Sdrh ** walWriteToLog().
3487d992b150Sdrh */
3488d992b150Sdrh typedef struct WalWriter {
3489d992b150Sdrh Wal *pWal; /* The complete WAL information */
3490d992b150Sdrh sqlite3_file *pFd; /* The WAL file to which we write */
3491d992b150Sdrh sqlite3_int64 iSyncPoint; /* Fsync at this offset */
3492d992b150Sdrh int syncFlags; /* Flags for the fsync */
3493d992b150Sdrh int szPage; /* Size of one page */
3494d992b150Sdrh } WalWriter;
3495d992b150Sdrh
3496d992b150Sdrh /*
349788f975a7Sdrh ** Write iAmt bytes of content into the WAL file beginning at iOffset.
3498d992b150Sdrh ** Do a sync when crossing the p->iSyncPoint boundary.
349988f975a7Sdrh **
3500d992b150Sdrh ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
3501d992b150Sdrh ** first write the part before iSyncPoint, then sync, then write the
3502d992b150Sdrh ** rest.
350388f975a7Sdrh */
walWriteToLog(WalWriter * p,void * pContent,int iAmt,sqlite3_int64 iOffset)350488f975a7Sdrh static int walWriteToLog(
3505d992b150Sdrh WalWriter *p, /* WAL to write to */
350688f975a7Sdrh void *pContent, /* Content to be written */
350788f975a7Sdrh int iAmt, /* Number of bytes to write */
350888f975a7Sdrh sqlite3_int64 iOffset /* Start writing at this offset */
350988f975a7Sdrh ){
351088f975a7Sdrh int rc;
3511d992b150Sdrh if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
3512d992b150Sdrh int iFirstAmt = (int)(p->iSyncPoint - iOffset);
3513d992b150Sdrh rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
351488f975a7Sdrh if( rc ) return rc;
3515d992b150Sdrh iOffset += iFirstAmt;
3516d992b150Sdrh iAmt -= iFirstAmt;
351788f975a7Sdrh pContent = (void*)(iFirstAmt + (char*)pContent);
3518daaae7b9Sdrh assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
3519daaae7b9Sdrh rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
3520cc8d10a0Sdrh if( iAmt==0 || rc ) return rc;
352188f975a7Sdrh }
3522d992b150Sdrh rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
3523d992b150Sdrh return rc;
3524d992b150Sdrh }
3525d992b150Sdrh
3526d992b150Sdrh /*
3527d992b150Sdrh ** Write out a single frame of the WAL
3528d992b150Sdrh */
walWriteOneFrame(WalWriter * p,PgHdr * pPage,int nTruncate,sqlite3_int64 iOffset)3529d992b150Sdrh static int walWriteOneFrame(
3530d992b150Sdrh WalWriter *p, /* Where to write the frame */
3531d992b150Sdrh PgHdr *pPage, /* The page of the frame to be written */
3532d992b150Sdrh int nTruncate, /* The commit flag. Usually 0. >0 for commit */
3533d992b150Sdrh sqlite3_int64 iOffset /* Byte offset at which to write */
3534d992b150Sdrh ){
3535d992b150Sdrh int rc; /* Result code from subfunctions */
3536d992b150Sdrh void *pData; /* Data actually written */
3537d992b150Sdrh u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
3538d992b150Sdrh pData = pPage->pData;
3539d992b150Sdrh walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
3540d992b150Sdrh rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
3541d992b150Sdrh if( rc ) return rc;
3542d992b150Sdrh /* Write the page data */
3543d992b150Sdrh rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
354488f975a7Sdrh return rc;
354588f975a7Sdrh }
354688f975a7Sdrh
354788f975a7Sdrh /*
3548d6f7c979Sdan ** This function is called as part of committing a transaction within which
3549d6f7c979Sdan ** one or more frames have been overwritten. It updates the checksums for
3550c9a9022bSdan ** all frames written to the wal file by the current transaction starting
3551c9a9022bSdan ** with the earliest to have been overwritten.
3552d6f7c979Sdan **
3553d6f7c979Sdan ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
3554d6f7c979Sdan */
walRewriteChecksums(Wal * pWal,u32 iLast)3555c9a9022bSdan static int walRewriteChecksums(Wal *pWal, u32 iLast){
3556d6f7c979Sdan const int szPage = pWal->szPage;/* Database page size */
3557d6f7c979Sdan int rc = SQLITE_OK; /* Return code */
3558d6f7c979Sdan u8 *aBuf; /* Buffer to load data from wal file into */
3559d6f7c979Sdan u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
3560d6f7c979Sdan u32 iRead; /* Next frame to read from wal file */
3561c9a9022bSdan i64 iCksumOff;
3562d6f7c979Sdan
3563d6f7c979Sdan aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
3564fad3039cSmistachkin if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
3565d6f7c979Sdan
3566c9a9022bSdan /* Find the checksum values to use as input for the recalculating the
3567c9a9022bSdan ** first checksum. If the first frame is frame 1 (implying that the current
3568c9a9022bSdan ** transaction restarted the wal file), these values must be read from the
3569c9a9022bSdan ** wal-file header. Otherwise, read them from the frame header of the
3570c9a9022bSdan ** previous frame. */
3571c9a9022bSdan assert( pWal->iReCksum>0 );
3572c9a9022bSdan if( pWal->iReCksum==1 ){
3573c9a9022bSdan iCksumOff = 24;
3574c9a9022bSdan }else{
3575c9a9022bSdan iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
3576c9a9022bSdan }
3577c9a9022bSdan rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
3578d6f7c979Sdan pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
3579d6f7c979Sdan pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
3580d6f7c979Sdan
3581c9a9022bSdan iRead = pWal->iReCksum;
3582c9a9022bSdan pWal->iReCksum = 0;
3583c9a9022bSdan for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
3584d6f7c979Sdan i64 iOff = walFrameOffset(iRead, szPage);
3585d6f7c979Sdan rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
3586d6f7c979Sdan if( rc==SQLITE_OK ){
3587d6f7c979Sdan u32 iPgno, nDbSize;
3588d6f7c979Sdan iPgno = sqlite3Get4byte(aBuf);
3589d6f7c979Sdan nDbSize = sqlite3Get4byte(&aBuf[4]);
3590d6f7c979Sdan
3591d6f7c979Sdan walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
3592d6f7c979Sdan rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
3593d6f7c979Sdan }
3594d6f7c979Sdan }
3595d6f7c979Sdan
3596d6f7c979Sdan sqlite3_free(aBuf);
3597d6f7c979Sdan return rc;
3598d6f7c979Sdan }
3599d6f7c979Sdan
3600d6f7c979Sdan /*
36014cd78b4dSdan ** Write a set of frames to the log. The caller must hold the write-lock
36029971e710Sdan ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
3603c438efd6Sdrh */
sqlite3WalFrames(Wal * pWal,int szPage,PgHdr * pList,Pgno nTruncate,int isCommit,int sync_flags)3604c438efd6Sdrh int sqlite3WalFrames(
36057ed91f23Sdrh Wal *pWal, /* Wal handle to write to */
36066e81096fSdrh int szPage, /* Database page-size in bytes */
3607c438efd6Sdrh PgHdr *pList, /* List of dirty pages to write */
3608c438efd6Sdrh Pgno nTruncate, /* Database size after this commit */
3609c438efd6Sdrh int isCommit, /* True if this is a commit */
3610c438efd6Sdrh int sync_flags /* Flags to pass to OsSync() (or 0) */
3611c438efd6Sdrh ){
3612c438efd6Sdrh int rc; /* Used to catch return codes */
3613c438efd6Sdrh u32 iFrame; /* Next frame address */
3614c438efd6Sdrh PgHdr *p; /* Iterator to run through pList with. */
3615e874d9edSdrh PgHdr *pLast = 0; /* Last frame in list */
3616d992b150Sdrh int nExtra = 0; /* Number of extra copies of last page */
3617d992b150Sdrh int szFrame; /* The size of a single frame */
3618d992b150Sdrh i64 iOffset; /* Next byte to write in WAL file */
3619d992b150Sdrh WalWriter w; /* The writer */
3620d6f7c979Sdan u32 iFirst = 0; /* First frame that may be overwritten */
3621d6f7c979Sdan WalIndexHdr *pLive; /* Pointer to shared header */
3622c438efd6Sdrh
3623c438efd6Sdrh assert( pList );
362473b64e4dSdrh assert( pWal->writeLock );
3625c438efd6Sdrh
36264120994fSdrh /* If this frame set completes a transaction, then nTruncate>0. If
36274120994fSdrh ** nTruncate==0 then this frame set does not complete the transaction. */
36284120994fSdrh assert( (isCommit!=0)==(nTruncate!=0) );
36294120994fSdrh
3630c74c3334Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
3631c74c3334Sdrh { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
3632c74c3334Sdrh WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
3633c74c3334Sdrh pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
3634c74c3334Sdrh }
3635c74c3334Sdrh #endif
3636c74c3334Sdrh
3637d6f7c979Sdan pLive = (WalIndexHdr*)walIndexHdr(pWal);
3638b7c2f86bSdrh if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
3639d6f7c979Sdan iFirst = pLive->mxFrame+1;
3640d6f7c979Sdan }
3641d6f7c979Sdan
36429971e710Sdan /* See if it is possible to write these frames into the start of the
36439971e710Sdan ** log file, instead of appending to it at pWal->hdr.mxFrame.
36449971e710Sdan */
36459971e710Sdan if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
36469971e710Sdan return rc;
36479971e710Sdan }
36489971e710Sdan
3649a2a42013Sdrh /* If this is the first frame written into the log, write the WAL
3650a2a42013Sdrh ** header to the start of the WAL file. See comments at the top of
3651a2a42013Sdrh ** this source file for a description of the WAL header format.
3652c438efd6Sdrh */
3653027a128aSdrh iFrame = pWal->hdr.mxFrame;
3654c438efd6Sdrh if( iFrame==0 ){
365510f5a50eSdan u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
365610f5a50eSdan u32 aCksum[2]; /* Checksum for wal-header */
365710f5a50eSdan
3658b8fd6c2fSdan sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
365910f5a50eSdan sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
366023ea97b6Sdrh sqlite3Put4byte(&aWalHdr[8], szPage);
366123ea97b6Sdrh sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
3662d2980310Sdrh if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
36637e263728Sdrh memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
366410f5a50eSdan walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
366510f5a50eSdan sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
366610f5a50eSdan sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
366710f5a50eSdan
3668b2eced5dSdrh pWal->szPage = szPage;
366910f5a50eSdan pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
367010f5a50eSdan pWal->hdr.aFrameCksum[0] = aCksum[0];
367110f5a50eSdan pWal->hdr.aFrameCksum[1] = aCksum[1];
3672f60b7f36Sdan pWal->truncateOnCommit = 1;
367310f5a50eSdan
367423ea97b6Sdrh rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
3675c74c3334Sdrh WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
3676c438efd6Sdrh if( rc!=SQLITE_OK ){
3677c438efd6Sdrh return rc;
3678c438efd6Sdrh }
3679d992b150Sdrh
3680d992b150Sdrh /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
3681d992b150Sdrh ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
3682d992b150Sdrh ** an out-of-order write following a WAL restart could result in
3683d992b150Sdrh ** database corruption. See the ticket:
3684d992b150Sdrh **
36859c6e07d2Sdrh ** https://sqlite.org/src/info/ff5be73dee
3686d992b150Sdrh */
3687daaae7b9Sdrh if( pWal->syncHeader ){
3688daaae7b9Sdrh rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
3689d992b150Sdrh if( rc ) return rc;
3690d992b150Sdrh }
3691c438efd6Sdrh }
3692bd2aaf9aSshaneh assert( (int)pWal->szPage==szPage );
3693c438efd6Sdrh
3694d992b150Sdrh /* Setup information needed to write frames into the WAL */
3695d992b150Sdrh w.pWal = pWal;
3696d992b150Sdrh w.pFd = pWal->pWalFd;
3697d992b150Sdrh w.iSyncPoint = 0;
3698d992b150Sdrh w.syncFlags = sync_flags;
3699d992b150Sdrh w.szPage = szPage;
3700d992b150Sdrh iOffset = walFrameOffset(iFrame+1, szPage);
3701d992b150Sdrh szFrame = szPage + WAL_FRAME_HDRSIZE;
370288f975a7Sdrh
3703d992b150Sdrh /* Write all frames into the log file exactly once */
3704c438efd6Sdrh for(p=pList; p; p=p->pDirty){
3705d992b150Sdrh int nDbSize; /* 0 normally. Positive == commit flag */
3706d6f7c979Sdan
3707d6f7c979Sdan /* Check if this page has already been written into the wal file by
3708d6f7c979Sdan ** the current transaction. If so, overwrite the existing frame and
3709d6f7c979Sdan ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
3710d6f7c979Sdan ** checksums must be recomputed when the transaction is committed. */
3711d6f7c979Sdan if( iFirst && (p->pDirty || isCommit==0) ){
3712d6f7c979Sdan u32 iWrite = 0;
37138997087aSdrh VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
37148997087aSdrh assert( rc==SQLITE_OK || iWrite==0 );
3715d6f7c979Sdan if( iWrite>=iFirst ){
3716d6f7c979Sdan i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
37178e0cea1aSdrh void *pData;
3718c9a9022bSdan if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
3719c9a9022bSdan pWal->iReCksum = iWrite;
3720c9a9022bSdan }
37218e0cea1aSdrh pData = p->pData;
37228e0cea1aSdrh rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
3723d6f7c979Sdan if( rc ) return rc;
3724d6f7c979Sdan p->flags &= ~PGHDR_WAL_APPEND;
3725d6f7c979Sdan continue;
3726d6f7c979Sdan }
3727d6f7c979Sdan }
3728d6f7c979Sdan
3729d992b150Sdrh iFrame++;
3730d992b150Sdrh assert( iOffset==walFrameOffset(iFrame, szPage) );
3731d992b150Sdrh nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
3732d992b150Sdrh rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
3733d992b150Sdrh if( rc ) return rc;
3734c438efd6Sdrh pLast = p;
3735d992b150Sdrh iOffset += szFrame;
3736d6f7c979Sdan p->flags |= PGHDR_WAL_APPEND;
3737d6f7c979Sdan }
3738d6f7c979Sdan
3739d6f7c979Sdan /* Recalculate checksums within the wal file if required. */
3740c9a9022bSdan if( isCommit && pWal->iReCksum ){
3741c9a9022bSdan rc = walRewriteChecksums(pWal, iFrame);
3742d6f7c979Sdan if( rc ) return rc;
3743c438efd6Sdrh }
3744c438efd6Sdrh
3745d992b150Sdrh /* If this is the end of a transaction, then we might need to pad
3746d992b150Sdrh ** the transaction and/or sync the WAL file.
3747d992b150Sdrh **
3748d992b150Sdrh ** Padding and syncing only occur if this set of frames complete a
3749d992b150Sdrh ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
375060ec914cSpeter.d.reid ** or synchronous==OFF, then no padding or syncing are needed.
3751d992b150Sdrh **
3752cb15f35fSdrh ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
3753cb15f35fSdrh ** needed and only the sync is done. If padding is needed, then the
3754cb15f35fSdrh ** final frame is repeated (with its commit mark) until the next sector
3755d992b150Sdrh ** boundary is crossed. Only the part of the WAL prior to the last
3756d992b150Sdrh ** sector boundary is synced; the part of the last frame that extends
3757d992b150Sdrh ** past the sector boundary is written after the sync.
3758d992b150Sdrh */
3759daaae7b9Sdrh if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
3760fe912510Sdan int bSync = 1;
3761374f4a04Sdrh if( pWal->padToSectorBoundary ){
3762c9a53269Sdan int sectorSize = sqlite3SectorSize(pWal->pWalFd);
3763d992b150Sdrh w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
3764fe912510Sdan bSync = (w.iSyncPoint==iOffset);
3765fe912510Sdan testcase( bSync );
3766d992b150Sdrh while( iOffset<w.iSyncPoint ){
3767d992b150Sdrh rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
3768d992b150Sdrh if( rc ) return rc;
3769d992b150Sdrh iOffset += szFrame;
3770d992b150Sdrh nExtra++;
377155f66b34Sdrh assert( pLast!=0 );
3772c438efd6Sdrh }
3773fe912510Sdan }
3774fe912510Sdan if( bSync ){
3775fe912510Sdan assert( rc==SQLITE_OK );
3776daaae7b9Sdrh rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
3777c438efd6Sdrh }
37784e5e108eSdrh }
3779c438efd6Sdrh
3780d992b150Sdrh /* If this frame set completes the first transaction in the WAL and
3781d992b150Sdrh ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
3782d992b150Sdrh ** journal size limit, if possible.
3783d992b150Sdrh */
3784f60b7f36Sdan if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
3785f60b7f36Sdan i64 sz = pWal->mxWalSize;
3786d992b150Sdrh if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
3787d992b150Sdrh sz = walFrameOffset(iFrame+nExtra+1, szPage);
3788f60b7f36Sdan }
3789f60b7f36Sdan walLimitSize(pWal, sz);
3790f60b7f36Sdan pWal->truncateOnCommit = 0;
3791f60b7f36Sdan }
3792f60b7f36Sdan
3793e730fec8Sdrh /* Append data to the wal-index. It is not necessary to lock the
3794a2a42013Sdrh ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
3795c438efd6Sdrh ** guarantees that there are no other writers, and no data that may
3796c438efd6Sdrh ** be in use by existing readers is being overwritten.
3797c438efd6Sdrh */
3798027a128aSdrh iFrame = pWal->hdr.mxFrame;
3799c7991bdfSdan for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
3800d6f7c979Sdan if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
3801c438efd6Sdrh iFrame++;
3802c7991bdfSdan rc = walIndexAppend(pWal, iFrame, p->pgno);
3803c438efd6Sdrh }
380455f66b34Sdrh assert( pLast!=0 || nExtra==0 );
380520e226d9Sdrh while( rc==SQLITE_OK && nExtra>0 ){
3806c438efd6Sdrh iFrame++;
3807d992b150Sdrh nExtra--;
3808c7991bdfSdan rc = walIndexAppend(pWal, iFrame, pLast->pgno);
3809c438efd6Sdrh }
3810c438efd6Sdrh
3811c7991bdfSdan if( rc==SQLITE_OK ){
3812c438efd6Sdrh /* Update the private copy of the header. */
38131df2db7fSshaneh pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
38149b78f791Sdrh testcase( szPage<=32768 );
38159b78f791Sdrh testcase( szPage>=65536 );
3816027a128aSdrh pWal->hdr.mxFrame = iFrame;
3817c438efd6Sdrh if( isCommit ){
38187ed91f23Sdrh pWal->hdr.iChange++;
38197ed91f23Sdrh pWal->hdr.nPage = nTruncate;
3820c438efd6Sdrh }
38217ed91f23Sdrh /* If this is a commit, update the wal-index header too. */
38227ed91f23Sdrh if( isCommit ){
38237e263728Sdrh walIndexWriteHdr(pWal);
38247ed91f23Sdrh pWal->iCallback = iFrame;
3825c438efd6Sdrh }
3826c7991bdfSdan }
3827c438efd6Sdrh
3828c74c3334Sdrh WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
3829c438efd6Sdrh return rc;
3830c438efd6Sdrh }
3831c438efd6Sdrh
3832c438efd6Sdrh /*
383373b64e4dSdrh ** This routine is called to implement sqlite3_wal_checkpoint() and
383473b64e4dSdrh ** related interfaces.
3835c438efd6Sdrh **
383673b64e4dSdrh ** Obtain a CHECKPOINT lock and then backfill as much information as
383773b64e4dSdrh ** we can from WAL into the database.
3838a58f26f9Sdan **
3839a58f26f9Sdan ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
3840a58f26f9Sdan ** callback. In this case this function runs a blocking checkpoint.
3841c438efd6Sdrh */
sqlite3WalCheckpoint(Wal * pWal,sqlite3 * db,int eMode,int (* xBusy)(void *),void * pBusyArg,int sync_flags,int nBuf,u8 * zBuf,int * pnLog,int * pnCkpt)3842c438efd6Sdrh int sqlite3WalCheckpoint(
38437ed91f23Sdrh Wal *pWal, /* Wal connection */
38447fb89906Sdan sqlite3 *db, /* Check this handle's interrupt flag */
3845dd90d7eeSdrh int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
3846a58f26f9Sdan int (*xBusy)(void*), /* Function to call when busy */
3847a58f26f9Sdan void *pBusyArg, /* Context argument for xBusyHandler */
3848c438efd6Sdrh int sync_flags, /* Flags to sync db file with (or 0) */
3849b6e099a9Sdan int nBuf, /* Size of temporary buffer */
3850cdc1f049Sdan u8 *zBuf, /* Temporary buffer to use */
3851cdc1f049Sdan int *pnLog, /* OUT: Number of frames in WAL */
3852cdc1f049Sdan int *pnCkpt /* OUT: Number of backfilled frames in WAL */
3853c438efd6Sdrh ){
3854c438efd6Sdrh int rc; /* Return code */
385531c03907Sdan int isChanged = 0; /* True if a new wal-index header is loaded */
3856f2b8dd58Sdan int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
3857dd90d7eeSdrh int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
3858c438efd6Sdrh
3859d54ff60bSdan assert( pWal->ckptLock==0 );
3860a58f26f9Sdan assert( pWal->writeLock==0 );
3861c438efd6Sdrh
3862dd90d7eeSdrh /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
3863dd90d7eeSdrh ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
3864dd90d7eeSdrh assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
3865dd90d7eeSdrh
386666dfec8bSdrh if( pWal->readOnly ) return SQLITE_READONLY;
3867c74c3334Sdrh WALTRACE(("WAL%p: checkpoint begins\n", pWal));
3868dd90d7eeSdrh
386958021b23Sdan /* Enable blocking locks, if possible. If blocking locks are successfully
387058021b23Sdan ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
3871861fb1e9Sdan sqlite3WalDb(pWal, db);
3872783e159eSdrh (void)walEnableBlocking(pWal);
38738714de97Sdan
3874dd90d7eeSdrh /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
38758714de97Sdan ** "checkpoint" lock on the database file.
38768714de97Sdan ** EVIDENCE-OF: R-10421-19736 If any other process is running a
3877dd90d7eeSdrh ** checkpoint operation at the same time, the lock cannot be obtained and
3878dd90d7eeSdrh ** SQLITE_BUSY is returned.
3879dd90d7eeSdrh ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
3880dd90d7eeSdrh ** it will not be invoked in this case.
3881dd90d7eeSdrh */
38828714de97Sdan rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
3883dd90d7eeSdrh testcase( rc==SQLITE_BUSY );
38848714de97Sdan testcase( rc!=SQLITE_OK && xBusy2!=0 );
38858714de97Sdan if( rc==SQLITE_OK ){
3886d54ff60bSdan pWal->ckptLock = 1;
3887c438efd6Sdrh
3888dd90d7eeSdrh /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
3889dd90d7eeSdrh ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
3890dd90d7eeSdrh ** file.
3891f2b8dd58Sdan **
3892dd90d7eeSdrh ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
3893dd90d7eeSdrh ** immediately, and a busy-handler is configured, it is invoked and the
3894dd90d7eeSdrh ** writer lock retried until either the busy-handler returns 0 or the
3895dd90d7eeSdrh ** lock is successfully obtained.
3896a58f26f9Sdan */
3897cdc1f049Sdan if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
38988714de97Sdan rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
3899c438efd6Sdrh if( rc==SQLITE_OK ){
3900f2b8dd58Sdan pWal->writeLock = 1;
3901f2b8dd58Sdan }else if( rc==SQLITE_BUSY ){
3902f2b8dd58Sdan eMode2 = SQLITE_CHECKPOINT_PASSIVE;
3903dd90d7eeSdrh xBusy2 = 0;
3904f2b8dd58Sdan rc = SQLITE_OK;
3905c438efd6Sdrh }
3906a58f26f9Sdan }
39078714de97Sdan }
39088714de97Sdan
3909a58f26f9Sdan
3910f2b8dd58Sdan /* Read the wal-index header. */
39117ed91f23Sdrh if( rc==SQLITE_OK ){
3912d0e6d133Sdan walDisableBlocking(pWal);
3913a58f26f9Sdan rc = walIndexReadHdr(pWal, &isChanged);
3914fc87ab8cSdan (void)walEnableBlocking(pWal);
3915f55a4cf8Sdan if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
3916f55a4cf8Sdan sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
3917f55a4cf8Sdan }
3918a58f26f9Sdan }
3919f2b8dd58Sdan
3920f2b8dd58Sdan /* Copy data from the log to the database file. */
39219c5e3680Sdan if( rc==SQLITE_OK ){
3922d6f7c979Sdan
39239c5e3680Sdan if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
3924f2b8dd58Sdan rc = SQLITE_CORRUPT_BKPT;
3925f2b8dd58Sdan }else{
39267fb89906Sdan rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
39279c5e3680Sdan }
39289c5e3680Sdan
39299c5e3680Sdan /* If no error occurred, set the output variables. */
39309c5e3680Sdan if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
3931cdc1f049Sdan if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
39329c5e3680Sdan if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
3933c438efd6Sdrh }
3934f2b8dd58Sdan }
3935f2b8dd58Sdan
393631c03907Sdan if( isChanged ){
393731c03907Sdan /* If a new wal-index header was loaded before the checkpoint was
3938a2a42013Sdrh ** performed, then the pager-cache associated with pWal is now
393931c03907Sdan ** out of date. So zero the cached wal-index header to ensure that
394031c03907Sdan ** next time the pager opens a snapshot on this database it knows that
394131c03907Sdan ** the cache needs to be reset.
394231c03907Sdan */
394331c03907Sdan memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
394431c03907Sdan }
3945c438efd6Sdrh
394658021b23Sdan walDisableBlocking(pWal);
3947861fb1e9Sdan sqlite3WalDb(pWal, 0);
39488714de97Sdan
3949c438efd6Sdrh /* Release the locks. */
3950a58f26f9Sdan sqlite3WalEndWriteTransaction(pWal);
39518714de97Sdan if( pWal->ckptLock ){
395273b64e4dSdrh walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
3953d54ff60bSdan pWal->ckptLock = 0;
39548714de97Sdan }
3955c74c3334Sdrh WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
39567bb8b8a4Sdan #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
39577bb8b8a4Sdan if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
39587bb8b8a4Sdan #endif
3959f2b8dd58Sdan return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
3960c438efd6Sdrh }
3961c438efd6Sdrh
39627ed91f23Sdrh /* Return the value to pass to a sqlite3_wal_hook callback, the
39637ed91f23Sdrh ** number of frames in the WAL at the point of the last commit since
39647ed91f23Sdrh ** sqlite3WalCallback() was called. If no commits have occurred since
39657ed91f23Sdrh ** the last call, then return 0.
39667ed91f23Sdrh */
sqlite3WalCallback(Wal * pWal)39677ed91f23Sdrh int sqlite3WalCallback(Wal *pWal){
3968c438efd6Sdrh u32 ret = 0;
39697ed91f23Sdrh if( pWal ){
39707ed91f23Sdrh ret = pWal->iCallback;
39717ed91f23Sdrh pWal->iCallback = 0;
3972c438efd6Sdrh }
3973c438efd6Sdrh return (int)ret;
3974c438efd6Sdrh }
39755543759bSdan
39765543759bSdan /*
397761e4acecSdrh ** This function is called to change the WAL subsystem into or out
397861e4acecSdrh ** of locking_mode=EXCLUSIVE.
39795543759bSdan **
398061e4acecSdrh ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
398161e4acecSdrh ** into locking_mode=NORMAL. This means that we must acquire a lock
398261e4acecSdrh ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
398361e4acecSdrh ** or if the acquisition of the lock fails, then return 0. If the
398461e4acecSdrh ** transition out of exclusive-mode is successful, return 1. This
398561e4acecSdrh ** operation must occur while the pager is still holding the exclusive
398661e4acecSdrh ** lock on the main database file.
39875543759bSdan **
398861e4acecSdrh ** If op is one, then change from locking_mode=NORMAL into
398961e4acecSdrh ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
399061e4acecSdrh ** be released. Return 1 if the transition is made and 0 if the
399161e4acecSdrh ** WAL is already in exclusive-locking mode - meaning that this
399261e4acecSdrh ** routine is a no-op. The pager must already hold the exclusive lock
399361e4acecSdrh ** on the main database file before invoking this operation.
399461e4acecSdrh **
399561e4acecSdrh ** If op is negative, then do a dry-run of the op==1 case but do
399661e4acecSdrh ** not actually change anything. The pager uses this to see if it
399761e4acecSdrh ** should acquire the database exclusive lock prior to invoking
399861e4acecSdrh ** the op==1 case.
39995543759bSdan */
sqlite3WalExclusiveMode(Wal * pWal,int op)40005543759bSdan int sqlite3WalExclusiveMode(Wal *pWal, int op){
400161e4acecSdrh int rc;
4002aab4c02eSdrh assert( pWal->writeLock==0 );
40038c408004Sdan assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
40043cac5dc9Sdan
40053cac5dc9Sdan /* pWal->readLock is usually set, but might be -1 if there was a
40063cac5dc9Sdan ** prior error while attempting to acquire are read-lock. This cannot
40073cac5dc9Sdan ** happen if the connection is actually in exclusive mode (as no xShmLock
40083cac5dc9Sdan ** locks are taken in this case). Nor should the pager attempt to
40093cac5dc9Sdan ** upgrade to exclusive-mode following such an error.
40103cac5dc9Sdan */
4011aab4c02eSdrh assert( pWal->readLock>=0 || pWal->lockError );
40123cac5dc9Sdan assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
40133cac5dc9Sdan
401461e4acecSdrh if( op==0 ){
4015c05a063cSdrh if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
4016c05a063cSdrh pWal->exclusiveMode = WAL_NORMAL_MODE;
40173cac5dc9Sdan if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
4018c05a063cSdrh pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
40195543759bSdan }
4020c05a063cSdrh rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
402161e4acecSdrh }else{
4022aab4c02eSdrh /* Already in locking_mode=NORMAL */
402361e4acecSdrh rc = 0;
402461e4acecSdrh }
402561e4acecSdrh }else if( op>0 ){
4026c05a063cSdrh assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
4027aab4c02eSdrh assert( pWal->readLock>=0 );
402861e4acecSdrh walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
4029c05a063cSdrh pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
403061e4acecSdrh rc = 1;
403161e4acecSdrh }else{
4032c05a063cSdrh rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
403361e4acecSdrh }
403461e4acecSdrh return rc;
40355543759bSdan }
40365543759bSdan
40378c408004Sdan /*
40388c408004Sdan ** Return true if the argument is non-NULL and the WAL module is using
40398c408004Sdan ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
40408c408004Sdan ** WAL module is using shared-memory, return false.
40418c408004Sdan */
sqlite3WalHeapMemory(Wal * pWal)40428c408004Sdan int sqlite3WalHeapMemory(Wal *pWal){
40438c408004Sdan return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
40448c408004Sdan }
40458c408004Sdan
4046fc1acf33Sdan #ifdef SQLITE_ENABLE_SNAPSHOT
4047e230a899Sdrh /* Create a snapshot object. The content of a snapshot is opaque to
4048e230a899Sdrh ** every other subsystem, so the WAL module can put whatever it needs
4049e230a899Sdrh ** in the object.
4050e230a899Sdrh */
sqlite3WalSnapshotGet(Wal * pWal,sqlite3_snapshot ** ppSnapshot)4051fc1acf33Sdan int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
4052fc1acf33Sdan int rc = SQLITE_OK;
4053fc1acf33Sdan WalIndexHdr *pRet;
4054ba6eb876Sdrh static const u32 aZero[4] = { 0, 0, 0, 0 };
4055fc1acf33Sdan
4056fc1acf33Sdan assert( pWal->readLock>=0 && pWal->writeLock==0 );
4057fc1acf33Sdan
4058ba6eb876Sdrh if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
4059ba6eb876Sdrh *ppSnapshot = 0;
4060ba6eb876Sdrh return SQLITE_ERROR;
4061ba6eb876Sdrh }
4062fc1acf33Sdan pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
4063fc1acf33Sdan if( pRet==0 ){
4064fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT;
4065fc1acf33Sdan }else{
4066fc1acf33Sdan memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
4067fc1acf33Sdan *ppSnapshot = (sqlite3_snapshot*)pRet;
4068fc1acf33Sdan }
4069fc1acf33Sdan
4070fc1acf33Sdan return rc;
4071fc1acf33Sdan }
4072fc1acf33Sdan
4073e230a899Sdrh /* Try to open on pSnapshot when the next read-transaction starts
4074e230a899Sdrh */
sqlite3WalSnapshotOpen(Wal * pWal,sqlite3_snapshot * pSnapshot)40758714de97Sdan void sqlite3WalSnapshotOpen(
40768714de97Sdan Wal *pWal,
40778714de97Sdan sqlite3_snapshot *pSnapshot
40788714de97Sdan ){
4079fc1acf33Sdan pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
4080fc1acf33Sdan }
4081ad2d5bafSdan
4082ad2d5bafSdan /*
4083ad2d5bafSdan ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
4084ad2d5bafSdan ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
4085ad2d5bafSdan */
sqlite3_snapshot_cmp(sqlite3_snapshot * p1,sqlite3_snapshot * p2)4086ad2d5bafSdan int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
4087ad2d5bafSdan WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
4088ad2d5bafSdan WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
4089ad2d5bafSdan
4090ad2d5bafSdan /* aSalt[0] is a copy of the value stored in the wal file header. It
4091ad2d5bafSdan ** is incremented each time the wal file is restarted. */
4092ad2d5bafSdan if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
4093ad2d5bafSdan if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
4094ad2d5bafSdan if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
4095ad2d5bafSdan if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
4096ad2d5bafSdan return 0;
4097ad2d5bafSdan }
4098fa3d4c19Sdan
4099fa3d4c19Sdan /*
4100fa3d4c19Sdan ** The caller currently has a read transaction open on the database.
4101fa3d4c19Sdan ** This function takes a SHARED lock on the CHECKPOINTER slot and then
4102fa3d4c19Sdan ** checks if the snapshot passed as the second argument is still
4103fa3d4c19Sdan ** available. If so, SQLITE_OK is returned.
4104fa3d4c19Sdan **
4105fa3d4c19Sdan ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
4106fa3d4c19Sdan ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
4107fa3d4c19Sdan ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
4108fa3d4c19Sdan ** lock is released before returning.
4109fa3d4c19Sdan */
sqlite3WalSnapshotCheck(Wal * pWal,sqlite3_snapshot * pSnapshot)4110fa3d4c19Sdan int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
4111fa3d4c19Sdan int rc;
4112fa3d4c19Sdan rc = walLockShared(pWal, WAL_CKPT_LOCK);
4113fa3d4c19Sdan if( rc==SQLITE_OK ){
4114fa3d4c19Sdan WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
4115fa3d4c19Sdan if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
4116fa3d4c19Sdan || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
4117fa3d4c19Sdan ){
41188d4b7a3fSdan rc = SQLITE_ERROR_SNAPSHOT;
4119fa3d4c19Sdan walUnlockShared(pWal, WAL_CKPT_LOCK);
4120fa3d4c19Sdan }
4121fa3d4c19Sdan }
4122fa3d4c19Sdan return rc;
4123fa3d4c19Sdan }
4124fa3d4c19Sdan
4125fa3d4c19Sdan /*
4126fa3d4c19Sdan ** Release a lock obtained by an earlier successful call to
4127fa3d4c19Sdan ** sqlite3WalSnapshotCheck().
4128fa3d4c19Sdan */
sqlite3WalSnapshotUnlock(Wal * pWal)4129fa3d4c19Sdan void sqlite3WalSnapshotUnlock(Wal *pWal){
4130fa3d4c19Sdan assert( pWal );
4131fa3d4c19Sdan walUnlockShared(pWal, WAL_CKPT_LOCK);
4132fa3d4c19Sdan }
4133fa3d4c19Sdan
4134fa3d4c19Sdan
4135fc1acf33Sdan #endif /* SQLITE_ENABLE_SNAPSHOT */
4136fc1acf33Sdan
413770708600Sdrh #ifdef SQLITE_ENABLE_ZIPVFS
4138b3bdc72dSdan /*
4139b3bdc72dSdan ** If the argument is not NULL, it points to a Wal object that holds a
4140b3bdc72dSdan ** read-lock. This function returns the database page-size if it is known,
4141b3bdc72dSdan ** or zero if it is not (or if pWal is NULL).
4142b3bdc72dSdan */
sqlite3WalFramesize(Wal * pWal)4143b3bdc72dSdan int sqlite3WalFramesize(Wal *pWal){
4144b3bdc72dSdan assert( pWal==0 || pWal->readLock>=0 );
4145b3bdc72dSdan return (pWal ? pWal->szPage : 0);
4146b3bdc72dSdan }
414770708600Sdrh #endif
4148b3bdc72dSdan
414921d61853Sdrh /* Return the sqlite3_file object for the WAL file
415021d61853Sdrh */
sqlite3WalFile(Wal * pWal)415121d61853Sdrh sqlite3_file *sqlite3WalFile(Wal *pWal){
415221d61853Sdrh return pWal->pWalFd;
415321d61853Sdrh }
415421d61853Sdrh
41555cf53537Sdan #endif /* #ifndef SQLITE_OMIT_WAL */
4156