The read-only CHECK-constraint optimization of [34ddf02d3d21151b] inhibits the
[sqlite.git] / src / wal.c
blobfd2eabfd963c6b07ace6d9a6fde8824a26e36d4e
1 /*
2 ** 2010 February 1
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
13 ** This file contains the implementation of a write-ahead log (WAL) used in
14 ** "journal_mode=WAL" mode.
16 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
18 ** A WAL file consists of a header followed by zero or more "frames".
19 ** Each frame records the revised content of a single page from the
20 ** database file. All changes to the database are recorded by writing
21 ** frames into the WAL. Transactions commit when a frame is written that
22 ** contains a commit marker. A single WAL can and usually does record
23 ** multiple transactions. Periodically, the content of the WAL is
24 ** transferred back into the database file in an operation called a
25 ** "checkpoint".
27 ** A single WAL file can be used multiple times. In other words, the
28 ** WAL can fill up with frames and then be checkpointed and then new
29 ** frames can overwrite the old ones. A WAL always grows from beginning
30 ** toward the end. Checksums and counters attached to each frame are
31 ** used to determine which frames within the WAL are valid and which
32 ** are leftovers from prior checkpoints.
34 ** The WAL header is 32 bytes in size and consists of the following eight
35 ** big-endian 32-bit unsigned integer values:
37 ** 0: Magic number. 0x377f0682 or 0x377f0683
38 ** 4: File format version. Currently 3007000
39 ** 8: Database page size. Example: 1024
40 ** 12: Checkpoint sequence number
41 ** 16: Salt-1, random integer incremented with each checkpoint
42 ** 20: Salt-2, a different random integer changing with each ckpt
43 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
44 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
46 ** Immediately following the wal-header are zero or more frames. Each
47 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48 ** of page data. The frame-header is six big-endian 32-bit unsigned
49 ** integer values, as follows:
51 ** 0: Page number.
52 ** 4: For commit records, the size of the database image in pages
53 ** after the commit. For all other records, zero.
54 ** 8: Salt-1 (copied from the header)
55 ** 12: Salt-2 (copied from the header)
56 ** 16: Checksum-1.
57 ** 20: Checksum-2.
59 ** A frame is considered valid if and only if the following conditions are
60 ** true:
62 ** (1) The salt-1 and salt-2 values in the frame-header match
63 ** salt values in the wal-header
65 ** (2) The checksum values in the final 8 bytes of the frame-header
66 ** exactly match the checksum computed consecutively on the
67 ** WAL header and the first 8 bytes and the content of all frames
68 ** up to and including the current frame.
70 ** The checksum is computed using 32-bit big-endian integers if the
71 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
72 ** is computed using little-endian if the magic number is 0x377f0682.
73 ** The checksum values are always stored in the frame header in a
74 ** big-endian format regardless of which byte order is used to compute
75 ** the checksum. The checksum is computed by interpreting the input as
76 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
77 ** algorithm used for the checksum is as follows:
79 ** for i from 0 to n-1 step 2:
80 ** s0 += x[i] + s1;
81 ** s1 += x[i+1] + s0;
82 ** endfor
84 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
85 ** in reverse order (the largest fibonacci weight occurs on the first element
86 ** of the sequence being summed.) The s1 value spans all 32-bit
87 ** terms of the sequence whereas s0 omits the final term.
89 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
90 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
91 ** The VFS.xSync operations serve as write barriers - all writes launched
92 ** before the xSync must complete before any write that launches after the
93 ** xSync begins.
95 ** After each checkpoint, the salt-1 value is incremented and the salt-2
96 ** value is randomized. This prevents old and new frames in the WAL from
97 ** being considered valid at the same time and being checkpointing together
98 ** following a crash.
100 ** READER ALGORITHM
102 ** To read a page from the database (call it page number P), a reader
103 ** first checks the WAL to see if it contains page P. If so, then the
104 ** last valid instance of page P that is a followed by a commit frame
105 ** or is a commit frame itself becomes the value read. If the WAL
106 ** contains no copies of page P that are valid and which are a commit
107 ** frame or are followed by a commit frame, then page P is read from
108 ** the database file.
110 ** To start a read transaction, the reader records the index of the last
111 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
112 ** for all subsequent read operations. New transactions can be appended
113 ** to the WAL, but as long as the reader uses its original mxFrame value
114 ** and ignores the newly appended content, it will see a consistent snapshot
115 ** of the database from a single point in time. This technique allows
116 ** multiple concurrent readers to view different versions of the database
117 ** content simultaneously.
119 ** The reader algorithm in the previous paragraphs works correctly, but
120 ** because frames for page P can appear anywhere within the WAL, the
121 ** reader has to scan the entire WAL looking for page P frames. If the
122 ** WAL is large (multiple megabytes is typical) that scan can be slow,
123 ** and read performance suffers. To overcome this problem, a separate
124 ** data structure called the wal-index is maintained to expedite the
125 ** search for frames of a particular page.
127 ** WAL-INDEX FORMAT
129 ** Conceptually, the wal-index is shared memory, though VFS implementations
130 ** might choose to implement the wal-index using a mmapped file. Because
131 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
132 ** on a network filesystem. All users of the database must be able to
133 ** share memory.
135 ** In the default unix and windows implementation, the wal-index is a mmapped
136 ** file whose name is the database name with a "-shm" suffix added. For that
137 ** reason, the wal-index is sometimes called the "shm" file.
139 ** The wal-index is transient. After a crash, the wal-index can (and should
140 ** be) reconstructed from the original WAL file. In fact, the VFS is required
141 ** to either truncate or zero the header of the wal-index when the last
142 ** connection to it closes. Because the wal-index is transient, it can
143 ** use an architecture-specific format; it does not have to be cross-platform.
144 ** Hence, unlike the database and WAL file formats which store all values
145 ** as big endian, the wal-index can store multi-byte values in the native
146 ** byte order of the host computer.
148 ** The purpose of the wal-index is to answer this question quickly: Given
149 ** a page number P and a maximum frame index M, return the index of the
150 ** last frame in the wal before frame M for page P in the WAL, or return
151 ** NULL if there are no frames for page P in the WAL prior to M.
153 ** The wal-index consists of a header region, followed by an one or
154 ** more index blocks.
156 ** The wal-index header contains the total number of frames within the WAL
157 ** in the mxFrame field.
159 ** Each index block except for the first contains information on
160 ** HASHTABLE_NPAGE frames. The first index block contains information on
161 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
162 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
163 ** first index block are the same size as all other index blocks in the
164 ** wal-index. The values are:
166 ** HASHTABLE_NPAGE 4096
167 ** HASHTABLE_NPAGE_ONE 4062
169 ** Each index block contains two sections, a page-mapping that contains the
170 ** database page number associated with each wal frame, and a hash-table
171 ** that allows readers to query an index block for a specific page number.
172 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
173 ** for the first index block) 32-bit page numbers. The first entry in the
174 ** first index-block contains the database page number corresponding to the
175 ** first frame in the WAL file. The first entry in the second index block
176 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
177 ** the log, and so on.
179 ** The last index block in a wal-index usually contains less than the full
180 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
181 ** depending on the contents of the WAL file. This does not change the
182 ** allocated size of the page-mapping array - the page-mapping array merely
183 ** contains unused entries.
185 ** Even without using the hash table, the last frame for page P
186 ** can be found by scanning the page-mapping sections of each index block
187 ** starting with the last index block and moving toward the first, and
188 ** within each index block, starting at the end and moving toward the
189 ** beginning. The first entry that equals P corresponds to the frame
190 ** holding the content for that page.
192 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
193 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
194 ** hash table for each page number in the mapping section, so the hash
195 ** table is never more than half full. The expected number of collisions
196 ** prior to finding a match is 1. Each entry of the hash table is an
197 ** 1-based index of an entry in the mapping section of the same
198 ** index block. Let K be the 1-based index of the largest entry in
199 ** the mapping section. (For index blocks other than the last, K will
200 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
201 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
202 ** contain a value of 0.
204 ** To look for page P in the hash table, first compute a hash iKey on
205 ** P as follows:
207 ** iKey = (P * 383) % HASHTABLE_NSLOT
209 ** Then start scanning entries of the hash table, starting with iKey
210 ** (wrapping around to the beginning when the end of the hash table is
211 ** reached) until an unused hash slot is found. Let the first unused slot
212 ** be at index iUnused. (iUnused might be less than iKey if there was
213 ** wrap-around.) Because the hash table is never more than half full,
214 ** the search is guaranteed to eventually hit an unused entry. Let
215 ** iMax be the value between iKey and iUnused, closest to iUnused,
216 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
217 ** no hash slot such that aHash[i]==p) then page P is not in the
218 ** current index block. Otherwise the iMax-th mapping entry of the
219 ** current index block corresponds to the last entry that references
220 ** page P.
222 ** A hash search begins with the last index block and moves toward the
223 ** first index block, looking for entries corresponding to page P. On
224 ** average, only two or three slots in each index block need to be
225 ** examined in order to either find the last entry for page P, or to
226 ** establish that no such entry exists in the block. Each index block
227 ** holds over 4000 entries. So two or three index blocks are sufficient
228 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
229 ** comparisons (on average) suffice to either locate a frame in the
230 ** WAL or to establish that the frame does not exist in the WAL. This
231 ** is much faster than scanning the entire 10MB WAL.
233 ** Note that entries are added in order of increasing K. Hence, one
234 ** reader might be using some value K0 and a second reader that started
235 ** at a later time (after additional transactions were added to the WAL
236 ** and to the wal-index) might be using a different value K1, where K1>K0.
237 ** Both readers can use the same hash table and mapping section to get
238 ** the correct result. There may be entries in the hash table with
239 ** K>K0 but to the first reader, those entries will appear to be unused
240 ** slots in the hash table and so the first reader will get an answer as
241 ** if no values greater than K0 had ever been inserted into the hash table
242 ** in the first place - which is what reader one wants. Meanwhile, the
243 ** second reader using K1 will see additional values that were inserted
244 ** later, which is exactly what reader two wants.
246 ** When a rollback occurs, the value of K is decreased. Hash table entries
247 ** that correspond to frames greater than the new K value are removed
248 ** from the hash table at this point.
250 #ifndef SQLITE_OMIT_WAL
252 #include "wal.h"
255 ** Trace output macros
257 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
258 int sqlite3WalTrace = 0;
259 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
260 #else
261 # define WALTRACE(X)
262 #endif
265 ** The maximum (and only) versions of the wal and wal-index formats
266 ** that may be interpreted by this version of SQLite.
268 ** If a client begins recovering a WAL file and finds that (a) the checksum
269 ** values in the wal-header are correct and (b) the version field is not
270 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
272 ** Similarly, if a client successfully reads a wal-index header (i.e. the
273 ** checksum test is successful) and finds that the version field is not
274 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
275 ** returns SQLITE_CANTOPEN.
277 #define WAL_MAX_VERSION 3007000
278 #define WALINDEX_MAX_VERSION 3007000
281 ** Index numbers for various locking bytes. WAL_NREADER is the number
282 ** of available reader locks and should be at least 3. The default
283 ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
285 ** Technically, the various VFSes are free to implement these locks however
286 ** they see fit. However, compatibility is encouraged so that VFSes can
287 ** interoperate. The standard implementation used on both unix and windows
288 ** is for the index number to indicate a byte offset into the
289 ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
290 ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
291 ** should be 120) is the location in the shm file for the first locking
292 ** byte.
294 #define WAL_WRITE_LOCK 0
295 #define WAL_ALL_BUT_WRITE 1
296 #define WAL_CKPT_LOCK 1
297 #define WAL_RECOVER_LOCK 2
298 #define WAL_READ_LOCK(I) (3+(I))
299 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
302 /* Object declarations */
303 typedef struct WalIndexHdr WalIndexHdr;
304 typedef struct WalIterator WalIterator;
305 typedef struct WalCkptInfo WalCkptInfo;
309 ** The following object holds a copy of the wal-index header content.
311 ** The actual header in the wal-index consists of two copies of this
312 ** object followed by one instance of the WalCkptInfo object.
313 ** For all versions of SQLite through 3.10.0 and probably beyond,
314 ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
315 ** the total header size is 136 bytes.
317 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
318 ** Or it can be 1 to represent a 65536-byte page. The latter case was
319 ** added in 3.7.1 when support for 64K pages was added.
321 struct WalIndexHdr {
322 u32 iVersion; /* Wal-index version */
323 u32 unused; /* Unused (padding) field */
324 u32 iChange; /* Counter incremented each transaction */
325 u8 isInit; /* 1 when initialized */
326 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
327 u16 szPage; /* Database page size in bytes. 1==64K */
328 u32 mxFrame; /* Index of last valid frame in the WAL */
329 u32 nPage; /* Size of database in pages */
330 u32 aFrameCksum[2]; /* Checksum of last frame in log */
331 u32 aSalt[2]; /* Two salt values copied from WAL header */
332 u32 aCksum[2]; /* Checksum over all prior fields */
336 ** A copy of the following object occurs in the wal-index immediately
337 ** following the second copy of the WalIndexHdr. This object stores
338 ** information used by checkpoint.
340 ** nBackfill is the number of frames in the WAL that have been written
341 ** back into the database. (We call the act of moving content from WAL to
342 ** database "backfilling".) The nBackfill number is never greater than
343 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
344 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
345 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
346 ** mxFrame back to zero when the WAL is reset.
348 ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
349 ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
350 ** the nBackfillAttempted is set before any backfilling is done and the
351 ** nBackfill is only set after all backfilling completes. So if a checkpoint
352 ** crashes, nBackfillAttempted might be larger than nBackfill. The
353 ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
355 ** The aLock[] field is a set of bytes used for locking. These bytes should
356 ** never be read or written.
358 ** There is one entry in aReadMark[] for each reader lock. If a reader
359 ** holds read-lock K, then the value in aReadMark[K] is no greater than
360 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
361 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
362 ** a special case; its value is never used and it exists as a place-holder
363 ** to avoid having to offset aReadMark[] indexes by one. Readers holding
364 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
365 ** directly from the database.
367 ** The value of aReadMark[K] may only be changed by a thread that
368 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
369 ** aReadMark[K] cannot changed while there is a reader is using that mark
370 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
372 ** The checkpointer may only transfer frames from WAL to database where
373 ** the frame numbers are less than or equal to every aReadMark[] that is
374 ** in use (that is, every aReadMark[j] for which there is a corresponding
375 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
376 ** largest value and will increase an unused aReadMark[] to mxFrame if there
377 ** is not already an aReadMark[] equal to mxFrame. The exception to the
378 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
379 ** in the WAL has been backfilled into the database) then new readers
380 ** will choose aReadMark[0] which has value 0 and hence such reader will
381 ** get all their all content directly from the database file and ignore
382 ** the WAL.
384 ** Writers normally append new frames to the end of the WAL. However,
385 ** if nBackfill equals mxFrame (meaning that all WAL content has been
386 ** written back into the database) and if no readers are using the WAL
387 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
388 ** the writer will first "reset" the WAL back to the beginning and start
389 ** writing new content beginning at frame 1.
391 ** We assume that 32-bit loads are atomic and so no locks are needed in
392 ** order to read from any aReadMark[] entries.
394 struct WalCkptInfo {
395 u32 nBackfill; /* Number of WAL frames backfilled into DB */
396 u32 aReadMark[WAL_NREADER]; /* Reader marks */
397 u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
398 u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
399 u32 notUsed0; /* Available for future enhancements */
401 #define READMARK_NOT_USED 0xffffffff
404 ** This is a schematic view of the complete 136-byte header of the
405 ** wal-index file (also known as the -shm file):
407 ** +-----------------------------+
408 ** 0: | iVersion | \
409 ** +-----------------------------+ |
410 ** 4: | (unused padding) | |
411 ** +-----------------------------+ |
412 ** 8: | iChange | |
413 ** +-------+-------+-------------+ |
414 ** 12: | bInit | bBig | szPage | |
415 ** +-------+-------+-------------+ |
416 ** 16: | mxFrame | | First copy of the
417 ** +-----------------------------+ | WalIndexHdr object
418 ** 20: | nPage | |
419 ** +-----------------------------+ |
420 ** 24: | aFrameCksum | |
421 ** | | |
422 ** +-----------------------------+ |
423 ** 32: | aSalt | |
424 ** | | |
425 ** +-----------------------------+ |
426 ** 40: | aCksum | |
427 ** | | /
428 ** +-----------------------------+
429 ** 48: | iVersion | \
430 ** +-----------------------------+ |
431 ** 52: | (unused padding) | |
432 ** +-----------------------------+ |
433 ** 56: | iChange | |
434 ** +-------+-------+-------------+ |
435 ** 60: | bInit | bBig | szPage | |
436 ** +-------+-------+-------------+ | Second copy of the
437 ** 64: | mxFrame | | WalIndexHdr
438 ** +-----------------------------+ |
439 ** 68: | nPage | |
440 ** +-----------------------------+ |
441 ** 72: | aFrameCksum | |
442 ** | | |
443 ** +-----------------------------+ |
444 ** 80: | aSalt | |
445 ** | | |
446 ** +-----------------------------+ |
447 ** 88: | aCksum | |
448 ** | | /
449 ** +-----------------------------+
450 ** 96: | nBackfill |
451 ** +-----------------------------+
452 ** 100: | 5 read marks |
453 ** | |
454 ** | |
455 ** | |
456 ** | |
457 ** +-------+-------+------+------+
458 ** 120: | Write | Ckpt | Rcvr | Rd0 | \
459 ** +-------+-------+------+------+ ) 8 lock bytes
460 ** | Read1 | Read2 | Rd3 | Rd4 | /
461 ** +-------+-------+------+------+
462 ** 128: | nBackfillAttempted |
463 ** +-----------------------------+
464 ** 132: | (unused padding) |
465 ** +-----------------------------+
468 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
469 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
470 ** only support mandatory file-locks, we do not read or write data
471 ** from the region of the file on which locks are applied.
473 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
474 #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
476 /* Size of header before each frame in wal */
477 #define WAL_FRAME_HDRSIZE 24
479 /* Size of write ahead log header, including checksum. */
480 #define WAL_HDRSIZE 32
482 /* WAL magic value. Either this value, or the same value with the least
483 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
484 ** big-endian format in the first 4 bytes of a WAL file.
486 ** If the LSB is set, then the checksums for each frame within the WAL
487 ** file are calculated by treating all data as an array of 32-bit
488 ** big-endian words. Otherwise, they are calculated by interpreting
489 ** all data as 32-bit little-endian words.
491 #define WAL_MAGIC 0x377f0682
494 ** Return the offset of frame iFrame in the write-ahead log file,
495 ** assuming a database page size of szPage bytes. The offset returned
496 ** is to the start of the write-ahead log frame-header.
498 #define walFrameOffset(iFrame, szPage) ( \
499 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
503 ** An open write-ahead log file is represented by an instance of the
504 ** following object.
506 struct Wal {
507 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
508 sqlite3_file *pDbFd; /* File handle for the database file */
509 sqlite3_file *pWalFd; /* File handle for WAL file */
510 u32 iCallback; /* Value to pass to log callback (or 0) */
511 i64 mxWalSize; /* Truncate WAL to this size upon reset */
512 int nWiData; /* Size of array apWiData */
513 int szFirstBlock; /* Size of first block written to WAL file */
514 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
515 u32 szPage; /* Database page size */
516 i16 readLock; /* Which read lock is being held. -1 for none */
517 u8 syncFlags; /* Flags to use to sync header writes */
518 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
519 u8 writeLock; /* True if in a write transaction */
520 u8 ckptLock; /* True if holding a checkpoint lock */
521 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
522 u8 truncateOnCommit; /* True to truncate WAL file on commit */
523 u8 syncHeader; /* Fsync the WAL header if true */
524 u8 padToSectorBoundary; /* Pad transactions out to the next sector */
525 u8 bShmUnreliable; /* SHM content is read-only and unreliable */
526 WalIndexHdr hdr; /* Wal-index header for current transaction */
527 u32 minFrame; /* Ignore wal frames before this one */
528 u32 iReCksum; /* On commit, recalculate checksums from here */
529 const char *zWalName; /* Name of WAL file */
530 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
531 #ifdef SQLITE_USE_SEH
532 u32 lockMask; /* Mask of locks held */
533 void *pFree; /* Pointer to sqlite3_free() if exception thrown */
534 u32 *pWiValue; /* Value to write into apWiData[iWiPg] */
535 int iWiPg; /* Write pWiValue into apWiData[iWiPg] */
536 int iSysErrno; /* System error code following exception */
537 #endif
538 #ifdef SQLITE_DEBUG
539 int nSehTry; /* Number of nested SEH_TRY{} blocks */
540 u8 lockError; /* True if a locking error has occurred */
541 #endif
542 #ifdef SQLITE_ENABLE_SNAPSHOT
543 WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
544 #endif
545 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
546 sqlite3 *db;
547 #endif
551 ** Candidate values for Wal.exclusiveMode.
553 #define WAL_NORMAL_MODE 0
554 #define WAL_EXCLUSIVE_MODE 1
555 #define WAL_HEAPMEMORY_MODE 2
558 ** Possible values for WAL.readOnly
560 #define WAL_RDWR 0 /* Normal read/write connection */
561 #define WAL_RDONLY 1 /* The WAL file is readonly */
562 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
565 ** Each page of the wal-index mapping contains a hash-table made up of
566 ** an array of HASHTABLE_NSLOT elements of the following type.
568 typedef u16 ht_slot;
571 ** This structure is used to implement an iterator that loops through
572 ** all frames in the WAL in database page order. Where two or more frames
573 ** correspond to the same database page, the iterator visits only the
574 ** frame most recently written to the WAL (in other words, the frame with
575 ** the largest index).
577 ** The internals of this structure are only accessed by:
579 ** walIteratorInit() - Create a new iterator,
580 ** walIteratorNext() - Step an iterator,
581 ** walIteratorFree() - Free an iterator.
583 ** This functionality is used by the checkpoint code (see walCheckpoint()).
585 struct WalIterator {
586 u32 iPrior; /* Last result returned from the iterator */
587 int nSegment; /* Number of entries in aSegment[] */
588 struct WalSegment {
589 int iNext; /* Next slot in aIndex[] not yet returned */
590 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
591 u32 *aPgno; /* Array of page numbers. */
592 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
593 int iZero; /* Frame number associated with aPgno[0] */
594 } aSegment[1]; /* One for every 32KB page in the wal-index */
598 ** Define the parameters of the hash tables in the wal-index file. There
599 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
600 ** wal-index.
602 ** Changing any of these constants will alter the wal-index format and
603 ** create incompatibilities.
605 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
606 #define HASHTABLE_HASH_1 383 /* Should be prime */
607 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
610 ** The block of page numbers associated with the first hash-table in a
611 ** wal-index is smaller than usual. This is so that there is a complete
612 ** hash-table on each aligned 32KB page of the wal-index.
614 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
616 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
617 #define WALINDEX_PGSZ ( \
618 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
622 ** Structured Exception Handling (SEH) is a Windows-specific technique
623 ** for catching exceptions raised while accessing memory-mapped files.
625 ** The -DSQLITE_USE_SEH compile-time option means to use SEH to catch and
626 ** deal with system-level errors that arise during WAL -shm file processing.
627 ** Without this compile-time option, any system-level faults that appear
628 ** while accessing the memory-mapped -shm file will cause a process-wide
629 ** signal to be deliver, which will more than likely cause the entire
630 ** process to exit.
632 #ifdef SQLITE_USE_SEH
633 #include <Windows.h>
635 /* Beginning of a block of code in which an exception might occur */
636 # define SEH_TRY __try { \
637 assert( walAssertLockmask(pWal) && pWal->nSehTry==0 ); \
638 VVA_ONLY(pWal->nSehTry++);
640 /* The end of a block of code in which an exception might occur */
641 # define SEH_EXCEPT(X) \
642 VVA_ONLY(pWal->nSehTry--); \
643 assert( pWal->nSehTry==0 ); \
644 } __except( sehExceptionFilter(pWal, GetExceptionCode(), GetExceptionInformation() ) ){ X }
646 /* Simulate a memory-mapping fault in the -shm file for testing purposes */
647 # define SEH_INJECT_FAULT sehInjectFault(pWal)
650 ** The second argument is the return value of GetExceptionCode() for the
651 ** current exception. Return EXCEPTION_EXECUTE_HANDLER if the exception code
652 ** indicates that the exception may have been caused by accessing the *-shm
653 ** file mapping. Or EXCEPTION_CONTINUE_SEARCH otherwise.
655 static int sehExceptionFilter(Wal *pWal, int eCode, EXCEPTION_POINTERS *p){
656 VVA_ONLY(pWal->nSehTry--);
657 if( eCode==EXCEPTION_IN_PAGE_ERROR ){
658 if( p && p->ExceptionRecord && p->ExceptionRecord->NumberParameters>=3 ){
659 /* From MSDN: For this type of exception, the first element of the
660 ** ExceptionInformation[] array is a read-write flag - 0 if the exception
661 ** was thrown while reading, 1 if while writing. The second element is
662 ** the virtual address being accessed. The "third array element specifies
663 ** the underlying NTSTATUS code that resulted in the exception". */
664 pWal->iSysErrno = (int)p->ExceptionRecord->ExceptionInformation[2];
666 return EXCEPTION_EXECUTE_HANDLER;
668 return EXCEPTION_CONTINUE_SEARCH;
672 ** If one is configured, invoke the xTestCallback callback with 650 as
673 ** the argument. If it returns true, throw the same exception that is
674 ** thrown by the system if the *-shm file mapping is accessed after it
675 ** has been invalidated.
677 static void sehInjectFault(Wal *pWal){
678 int res;
679 assert( pWal->nSehTry>0 );
681 res = sqlite3FaultSim(650);
682 if( res!=0 ){
683 ULONG_PTR aArg[3];
684 aArg[0] = 0;
685 aArg[1] = 0;
686 aArg[2] = (ULONG_PTR)res;
687 RaiseException(EXCEPTION_IN_PAGE_ERROR, 0, 3, (const ULONG_PTR*)aArg);
692 ** There are two ways to use this macro. To set a pointer to be freed
693 ** if an exception is thrown:
695 ** SEH_FREE_ON_ERROR(0, pPtr);
697 ** and to cancel the same:
699 ** SEH_FREE_ON_ERROR(pPtr, 0);
701 ** In the first case, there must not already be a pointer registered to
702 ** be freed. In the second case, pPtr must be the registered pointer.
704 #define SEH_FREE_ON_ERROR(X,Y) \
705 assert( (X==0 || Y==0) && pWal->pFree==X ); pWal->pFree = Y
708 ** There are two ways to use this macro. To arrange for pWal->apWiData[iPg]
709 ** to be set to pValue if an exception is thrown:
711 ** SEH_SET_ON_ERROR(iPg, pValue);
713 ** and to cancel the same:
715 ** SEH_SET_ON_ERROR(0, 0);
717 #define SEH_SET_ON_ERROR(X,Y) pWal->iWiPg = X; pWal->pWiValue = Y
719 #else
720 # define SEH_TRY VVA_ONLY(pWal->nSehTry++);
721 # define SEH_EXCEPT(X) VVA_ONLY(pWal->nSehTry--); assert( pWal->nSehTry==0 );
722 # define SEH_INJECT_FAULT assert( pWal->nSehTry>0 );
723 # define SEH_FREE_ON_ERROR(X,Y)
724 # define SEH_SET_ON_ERROR(X,Y)
725 #endif /* ifdef SQLITE_USE_SEH */
729 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
730 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
731 ** numbered from zero.
733 ** If the wal-index is currently smaller the iPage pages then the size
734 ** of the wal-index might be increased, but only if it is safe to do
735 ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
736 ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
738 ** Three possible result scenarios:
740 ** (1) rc==SQLITE_OK and *ppPage==Requested-Wal-Index-Page
741 ** (2) rc>=SQLITE_ERROR and *ppPage==NULL
742 ** (3) rc==SQLITE_OK and *ppPage==NULL // only if iPage==0
744 ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
746 static SQLITE_NOINLINE int walIndexPageRealloc(
747 Wal *pWal, /* The WAL context */
748 int iPage, /* The page we seek */
749 volatile u32 **ppPage /* Write the page pointer here */
751 int rc = SQLITE_OK;
753 /* Enlarge the pWal->apWiData[] array if required */
754 if( pWal->nWiData<=iPage ){
755 sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
756 volatile u32 **apNew;
757 apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
758 if( !apNew ){
759 *ppPage = 0;
760 return SQLITE_NOMEM_BKPT;
762 memset((void*)&apNew[pWal->nWiData], 0,
763 sizeof(u32*)*(iPage+1-pWal->nWiData));
764 pWal->apWiData = apNew;
765 pWal->nWiData = iPage+1;
768 /* Request a pointer to the required page from the VFS */
769 assert( pWal->apWiData[iPage]==0 );
770 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
771 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
772 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
773 }else{
774 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
775 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
777 assert( pWal->apWiData[iPage]!=0
778 || rc!=SQLITE_OK
779 || (pWal->writeLock==0 && iPage==0) );
780 testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
781 if( rc==SQLITE_OK ){
782 if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
783 }else if( (rc&0xff)==SQLITE_READONLY ){
784 pWal->readOnly |= WAL_SHM_RDONLY;
785 if( rc==SQLITE_READONLY ){
786 rc = SQLITE_OK;
791 *ppPage = pWal->apWiData[iPage];
792 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
793 return rc;
795 static int walIndexPage(
796 Wal *pWal, /* The WAL context */
797 int iPage, /* The page we seek */
798 volatile u32 **ppPage /* Write the page pointer here */
800 SEH_INJECT_FAULT;
801 if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
802 return walIndexPageRealloc(pWal, iPage, ppPage);
804 return SQLITE_OK;
808 ** Return a pointer to the WalCkptInfo structure in the wal-index.
810 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
811 assert( pWal->nWiData>0 && pWal->apWiData[0] );
812 SEH_INJECT_FAULT;
813 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
817 ** Return a pointer to the WalIndexHdr structure in the wal-index.
819 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
820 assert( pWal->nWiData>0 && pWal->apWiData[0] );
821 SEH_INJECT_FAULT;
822 return (volatile WalIndexHdr*)pWal->apWiData[0];
826 ** The argument to this macro must be of type u32. On a little-endian
827 ** architecture, it returns the u32 value that results from interpreting
828 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
829 ** returns the value that would be produced by interpreting the 4 bytes
830 ** of the input value as a little-endian integer.
832 #define BYTESWAP32(x) ( \
833 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
834 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
838 ** Generate or extend an 8 byte checksum based on the data in
839 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
840 ** initial values of 0 and 0 if aIn==NULL).
842 ** The checksum is written back into aOut[] before returning.
844 ** nByte must be a positive multiple of 8.
846 static void walChecksumBytes(
847 int nativeCksum, /* True for native byte-order, false for non-native */
848 u8 *a, /* Content to be checksummed */
849 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
850 const u32 *aIn, /* Initial checksum value input */
851 u32 *aOut /* OUT: Final checksum value output */
853 u32 s1, s2;
854 u32 *aData = (u32 *)a;
855 u32 *aEnd = (u32 *)&a[nByte];
857 if( aIn ){
858 s1 = aIn[0];
859 s2 = aIn[1];
860 }else{
861 s1 = s2 = 0;
864 assert( nByte>=8 );
865 assert( (nByte&0x00000007)==0 );
866 assert( nByte<=65536 );
867 assert( nByte%4==0 );
869 if( !nativeCksum ){
870 do {
871 s1 += BYTESWAP32(aData[0]) + s2;
872 s2 += BYTESWAP32(aData[1]) + s1;
873 aData += 2;
874 }while( aData<aEnd );
875 }else if( nByte%64==0 ){
876 do {
877 s1 += *aData++ + s2;
878 s2 += *aData++ + s1;
879 s1 += *aData++ + s2;
880 s2 += *aData++ + s1;
881 s1 += *aData++ + s2;
882 s2 += *aData++ + s1;
883 s1 += *aData++ + s2;
884 s2 += *aData++ + s1;
885 s1 += *aData++ + s2;
886 s2 += *aData++ + s1;
887 s1 += *aData++ + s2;
888 s2 += *aData++ + s1;
889 s1 += *aData++ + s2;
890 s2 += *aData++ + s1;
891 s1 += *aData++ + s2;
892 s2 += *aData++ + s1;
893 }while( aData<aEnd );
894 }else{
895 do {
896 s1 += *aData++ + s2;
897 s2 += *aData++ + s1;
898 }while( aData<aEnd );
900 assert( aData==aEnd );
902 aOut[0] = s1;
903 aOut[1] = s2;
907 ** If there is the possibility of concurrent access to the SHM file
908 ** from multiple threads and/or processes, then do a memory barrier.
910 static void walShmBarrier(Wal *pWal){
911 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
912 sqlite3OsShmBarrier(pWal->pDbFd);
917 ** Add the SQLITE_NO_TSAN as part of the return-type of a function
918 ** definition as a hint that the function contains constructs that
919 ** might give false-positive TSAN warnings.
921 ** See tag-20200519-1.
923 #if defined(__clang__) && !defined(SQLITE_NO_TSAN)
924 # define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
925 #else
926 # define SQLITE_NO_TSAN
927 #endif
930 ** Write the header information in pWal->hdr into the wal-index.
932 ** The checksum on pWal->hdr is updated before it is written.
934 static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
935 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
936 const int nCksum = offsetof(WalIndexHdr, aCksum);
938 assert( pWal->writeLock );
939 pWal->hdr.isInit = 1;
940 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
941 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
942 /* Possible TSAN false-positive. See tag-20200519-1 */
943 memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
944 walShmBarrier(pWal);
945 memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
949 ** This function encodes a single frame header and writes it to a buffer
950 ** supplied by the caller. A frame-header is made up of a series of
951 ** 4-byte big-endian integers, as follows:
953 ** 0: Page number.
954 ** 4: For commit records, the size of the database image in pages
955 ** after the commit. For all other records, zero.
956 ** 8: Salt-1 (copied from the wal-header)
957 ** 12: Salt-2 (copied from the wal-header)
958 ** 16: Checksum-1.
959 ** 20: Checksum-2.
961 static void walEncodeFrame(
962 Wal *pWal, /* The write-ahead log */
963 u32 iPage, /* Database page number for frame */
964 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
965 u8 *aData, /* Pointer to page data */
966 u8 *aFrame /* OUT: Write encoded frame here */
968 int nativeCksum; /* True for native byte-order checksums */
969 u32 *aCksum = pWal->hdr.aFrameCksum;
970 assert( WAL_FRAME_HDRSIZE==24 );
971 sqlite3Put4byte(&aFrame[0], iPage);
972 sqlite3Put4byte(&aFrame[4], nTruncate);
973 if( pWal->iReCksum==0 ){
974 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
976 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
977 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
978 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
980 sqlite3Put4byte(&aFrame[16], aCksum[0]);
981 sqlite3Put4byte(&aFrame[20], aCksum[1]);
982 }else{
983 memset(&aFrame[8], 0, 16);
988 ** Check to see if the frame with header in aFrame[] and content
989 ** in aData[] is valid. If it is a valid frame, fill *piPage and
990 ** *pnTruncate and return true. Return if the frame is not valid.
992 static int walDecodeFrame(
993 Wal *pWal, /* The write-ahead log */
994 u32 *piPage, /* OUT: Database page number for frame */
995 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
996 u8 *aData, /* Pointer to page data (for checksum) */
997 u8 *aFrame /* Frame data */
999 int nativeCksum; /* True for native byte-order checksums */
1000 u32 *aCksum = pWal->hdr.aFrameCksum;
1001 u32 pgno; /* Page number of the frame */
1002 assert( WAL_FRAME_HDRSIZE==24 );
1004 /* A frame is only valid if the salt values in the frame-header
1005 ** match the salt values in the wal-header.
1007 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
1008 return 0;
1011 /* A frame is only valid if the page number is greater than zero.
1013 pgno = sqlite3Get4byte(&aFrame[0]);
1014 if( pgno==0 ){
1015 return 0;
1018 /* A frame is only valid if a checksum of the WAL header,
1019 ** all prior frames, the first 16 bytes of this frame-header,
1020 ** and the frame-data matches the checksum in the last 8
1021 ** bytes of this frame-header.
1023 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
1024 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
1025 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
1026 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
1027 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
1029 /* Checksum failed. */
1030 return 0;
1033 /* If we reach this point, the frame is valid. Return the page number
1034 ** and the new database size.
1036 *piPage = pgno;
1037 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
1038 return 1;
1042 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
1044 ** Names of locks. This routine is used to provide debugging output and is not
1045 ** a part of an ordinary build.
1047 static const char *walLockName(int lockIdx){
1048 if( lockIdx==WAL_WRITE_LOCK ){
1049 return "WRITE-LOCK";
1050 }else if( lockIdx==WAL_CKPT_LOCK ){
1051 return "CKPT-LOCK";
1052 }else if( lockIdx==WAL_RECOVER_LOCK ){
1053 return "RECOVER-LOCK";
1054 }else{
1055 static char zName[15];
1056 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
1057 lockIdx-WAL_READ_LOCK(0));
1058 return zName;
1061 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
1065 ** Set or release locks on the WAL. Locks are either shared or exclusive.
1066 ** A lock cannot be moved directly between shared and exclusive - it must go
1067 ** through the unlocked state first.
1069 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
1071 static int walLockShared(Wal *pWal, int lockIdx){
1072 int rc;
1073 if( pWal->exclusiveMode ) return SQLITE_OK;
1074 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
1075 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
1076 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
1077 walLockName(lockIdx), rc ? "failed" : "ok"));
1078 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
1079 #ifdef SQLITE_USE_SEH
1080 if( rc==SQLITE_OK ) pWal->lockMask |= (1 << lockIdx);
1081 #endif
1082 return rc;
1084 static void walUnlockShared(Wal *pWal, int lockIdx){
1085 if( pWal->exclusiveMode ) return;
1086 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
1087 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
1088 #ifdef SQLITE_USE_SEH
1089 pWal->lockMask &= ~(1 << lockIdx);
1090 #endif
1091 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
1093 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
1094 int rc;
1095 if( pWal->exclusiveMode ) return SQLITE_OK;
1096 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
1097 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
1098 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
1099 walLockName(lockIdx), n, rc ? "failed" : "ok"));
1100 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
1101 #ifdef SQLITE_USE_SEH
1102 if( rc==SQLITE_OK ){
1103 pWal->lockMask |= (((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
1105 #endif
1106 return rc;
1108 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
1109 if( pWal->exclusiveMode ) return;
1110 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
1111 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
1112 #ifdef SQLITE_USE_SEH
1113 pWal->lockMask &= ~(((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
1114 #endif
1115 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
1116 walLockName(lockIdx), n));
1120 ** Compute a hash on a page number. The resulting hash value must land
1121 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
1122 ** the hash to the next value in the event of a collision.
1124 static int walHash(u32 iPage){
1125 assert( iPage>0 );
1126 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
1127 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
1129 static int walNextHash(int iPriorHash){
1130 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
1134 ** An instance of the WalHashLoc object is used to describe the location
1135 ** of a page hash table in the wal-index. This becomes the return value
1136 ** from walHashGet().
1138 typedef struct WalHashLoc WalHashLoc;
1139 struct WalHashLoc {
1140 volatile ht_slot *aHash; /* Start of the wal-index hash table */
1141 volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
1142 u32 iZero; /* One less than the frame number of first indexed*/
1146 ** Return pointers to the hash table and page number array stored on
1147 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
1148 ** numbered starting from 0.
1150 ** Set output variable pLoc->aHash to point to the start of the hash table
1151 ** in the wal-index file. Set pLoc->iZero to one less than the frame
1152 ** number of the first frame indexed by this hash table. If a
1153 ** slot in the hash table is set to N, it refers to frame number
1154 ** (pLoc->iZero+N) in the log.
1156 ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
1157 ** first frame indexed by the hash table, frame (pLoc->iZero).
1159 static int walHashGet(
1160 Wal *pWal, /* WAL handle */
1161 int iHash, /* Find the iHash'th table */
1162 WalHashLoc *pLoc /* OUT: Hash table location */
1164 int rc; /* Return code */
1166 rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
1167 assert( rc==SQLITE_OK || iHash>0 );
1169 if( pLoc->aPgno ){
1170 pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
1171 if( iHash==0 ){
1172 pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
1173 pLoc->iZero = 0;
1174 }else{
1175 pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
1177 }else if( NEVER(rc==SQLITE_OK) ){
1178 rc = SQLITE_ERROR;
1180 return rc;
1184 ** Return the number of the wal-index page that contains the hash-table
1185 ** and page-number array that contain entries corresponding to WAL frame
1186 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
1187 ** are numbered starting from 0.
1189 static int walFramePage(u32 iFrame){
1190 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
1191 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
1192 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
1193 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
1194 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
1195 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
1197 assert( iHash>=0 );
1198 return iHash;
1202 ** Return the page number associated with frame iFrame in this WAL.
1204 static u32 walFramePgno(Wal *pWal, u32 iFrame){
1205 int iHash = walFramePage(iFrame);
1206 SEH_INJECT_FAULT;
1207 if( iHash==0 ){
1208 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
1210 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
1214 ** Remove entries from the hash table that point to WAL slots greater
1215 ** than pWal->hdr.mxFrame.
1217 ** This function is called whenever pWal->hdr.mxFrame is decreased due
1218 ** to a rollback or savepoint.
1220 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
1221 ** updated. Any later hash tables will be automatically cleared when
1222 ** pWal->hdr.mxFrame advances to the point where those hash tables are
1223 ** actually needed.
1225 static void walCleanupHash(Wal *pWal){
1226 WalHashLoc sLoc; /* Hash table location */
1227 int iLimit = 0; /* Zero values greater than this */
1228 int nByte; /* Number of bytes to zero in aPgno[] */
1229 int i; /* Used to iterate through aHash[] */
1231 assert( pWal->writeLock );
1232 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
1233 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
1234 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
1236 if( pWal->hdr.mxFrame==0 ) return;
1238 /* Obtain pointers to the hash-table and page-number array containing
1239 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
1240 ** that the page said hash-table and array reside on is already mapped.(1)
1242 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
1243 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
1244 i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
1245 if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
1247 /* Zero all hash-table entries that correspond to frame numbers greater
1248 ** than pWal->hdr.mxFrame.
1250 iLimit = pWal->hdr.mxFrame - sLoc.iZero;
1251 assert( iLimit>0 );
1252 for(i=0; i<HASHTABLE_NSLOT; i++){
1253 if( sLoc.aHash[i]>iLimit ){
1254 sLoc.aHash[i] = 0;
1258 /* Zero the entries in the aPgno array that correspond to frames with
1259 ** frame numbers greater than pWal->hdr.mxFrame.
1261 nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
1262 assert( nByte>=0 );
1263 memset((void *)&sLoc.aPgno[iLimit], 0, nByte);
1265 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
1266 /* Verify that the every entry in the mapping region is still reachable
1267 ** via the hash table even after the cleanup.
1269 if( iLimit ){
1270 int j; /* Loop counter */
1271 int iKey; /* Hash key */
1272 for(j=0; j<iLimit; j++){
1273 for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
1274 if( sLoc.aHash[iKey]==j+1 ) break;
1276 assert( sLoc.aHash[iKey]==j+1 );
1279 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
1284 ** Set an entry in the wal-index that will map database page number
1285 ** pPage into WAL frame iFrame.
1287 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
1288 int rc; /* Return code */
1289 WalHashLoc sLoc; /* Wal-index hash table location */
1291 rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
1293 /* Assuming the wal-index file was successfully mapped, populate the
1294 ** page number array and hash table entry.
1296 if( rc==SQLITE_OK ){
1297 int iKey; /* Hash table key */
1298 int idx; /* Value to write to hash-table slot */
1299 int nCollide; /* Number of hash collisions */
1301 idx = iFrame - sLoc.iZero;
1302 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
1304 /* If this is the first entry to be added to this hash-table, zero the
1305 ** entire hash table and aPgno[] array before proceeding.
1307 if( idx==1 ){
1308 int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
1309 assert( nByte>=0 );
1310 memset((void*)sLoc.aPgno, 0, nByte);
1313 /* If the entry in aPgno[] is already set, then the previous writer
1314 ** must have exited unexpectedly in the middle of a transaction (after
1315 ** writing one or more dirty pages to the WAL to free up memory).
1316 ** Remove the remnants of that writers uncommitted transaction from
1317 ** the hash-table before writing any new entries.
1319 if( sLoc.aPgno[idx-1] ){
1320 walCleanupHash(pWal);
1321 assert( !sLoc.aPgno[idx-1] );
1324 /* Write the aPgno[] array entry and the hash-table slot. */
1325 nCollide = idx;
1326 for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
1327 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
1329 sLoc.aPgno[idx-1] = iPage;
1330 AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
1332 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
1333 /* Verify that the number of entries in the hash table exactly equals
1334 ** the number of entries in the mapping region.
1337 int i; /* Loop counter */
1338 int nEntry = 0; /* Number of entries in the hash table */
1339 for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
1340 assert( nEntry==idx );
1343 /* Verify that the every entry in the mapping region is reachable
1344 ** via the hash table. This turns out to be a really, really expensive
1345 ** thing to check, so only do this occasionally - not on every
1346 ** iteration.
1348 if( (idx&0x3ff)==0 ){
1349 int i; /* Loop counter */
1350 for(i=0; i<idx; i++){
1351 for(iKey=walHash(sLoc.aPgno[i]);
1352 sLoc.aHash[iKey];
1353 iKey=walNextHash(iKey)){
1354 if( sLoc.aHash[iKey]==i+1 ) break;
1356 assert( sLoc.aHash[iKey]==i+1 );
1359 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
1362 return rc;
1367 ** Recover the wal-index by reading the write-ahead log file.
1369 ** This routine first tries to establish an exclusive lock on the
1370 ** wal-index to prevent other threads/processes from doing anything
1371 ** with the WAL or wal-index while recovery is running. The
1372 ** WAL_RECOVER_LOCK is also held so that other threads will know
1373 ** that this thread is running recovery. If unable to establish
1374 ** the necessary locks, this routine returns SQLITE_BUSY.
1376 static int walIndexRecover(Wal *pWal){
1377 int rc; /* Return Code */
1378 i64 nSize; /* Size of log file */
1379 u32 aFrameCksum[2] = {0, 0};
1380 int iLock; /* Lock offset to lock for checkpoint */
1382 /* Obtain an exclusive lock on all byte in the locking range not already
1383 ** locked by the caller. The caller is guaranteed to have locked the
1384 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
1385 ** If successful, the same bytes that are locked here are unlocked before
1386 ** this function returns.
1388 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
1389 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
1390 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
1391 assert( pWal->writeLock );
1392 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
1393 rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
1394 if( rc ){
1395 return rc;
1398 WALTRACE(("WAL%p: recovery begin...\n", pWal));
1400 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
1402 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
1403 if( rc!=SQLITE_OK ){
1404 goto recovery_error;
1407 if( nSize>WAL_HDRSIZE ){
1408 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
1409 u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */
1410 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
1411 int szFrame; /* Number of bytes in buffer aFrame[] */
1412 u8 *aData; /* Pointer to data part of aFrame buffer */
1413 int szPage; /* Page size according to the log */
1414 u32 magic; /* Magic value read from WAL header */
1415 u32 version; /* Magic value read from WAL header */
1416 int isValid; /* True if this frame is valid */
1417 u32 iPg; /* Current 32KB wal-index page */
1418 u32 iLastFrame; /* Last frame in wal, based on nSize alone */
1420 /* Read in the WAL header. */
1421 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
1422 if( rc!=SQLITE_OK ){
1423 goto recovery_error;
1426 /* If the database page size is not a power of two, or is greater than
1427 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
1428 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
1429 ** WAL file.
1431 magic = sqlite3Get4byte(&aBuf[0]);
1432 szPage = sqlite3Get4byte(&aBuf[8]);
1433 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
1434 || szPage&(szPage-1)
1435 || szPage>SQLITE_MAX_PAGE_SIZE
1436 || szPage<512
1438 goto finished;
1440 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
1441 pWal->szPage = szPage;
1442 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
1443 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
1445 /* Verify that the WAL header checksum is correct */
1446 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
1447 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
1449 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
1450 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
1452 goto finished;
1455 /* Verify that the version number on the WAL format is one that
1456 ** are able to understand */
1457 version = sqlite3Get4byte(&aBuf[4]);
1458 if( version!=WAL_MAX_VERSION ){
1459 rc = SQLITE_CANTOPEN_BKPT;
1460 goto finished;
1463 /* Malloc a buffer to read frames into. */
1464 szFrame = szPage + WAL_FRAME_HDRSIZE;
1465 aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ);
1466 SEH_FREE_ON_ERROR(0, aFrame);
1467 if( !aFrame ){
1468 rc = SQLITE_NOMEM_BKPT;
1469 goto recovery_error;
1471 aData = &aFrame[WAL_FRAME_HDRSIZE];
1472 aPrivate = (u32*)&aData[szPage];
1474 /* Read all frames from the log file. */
1475 iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
1476 for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
1477 u32 *aShare;
1478 u32 iFrame; /* Index of last frame read */
1479 u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
1480 u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
1481 u32 nHdr, nHdr32;
1482 rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
1483 assert( aShare!=0 || rc!=SQLITE_OK );
1484 if( aShare==0 ) break;
1485 SEH_SET_ON_ERROR(iPg, aShare);
1486 pWal->apWiData[iPg] = aPrivate;
1488 for(iFrame=iFirst; iFrame<=iLast; iFrame++){
1489 i64 iOffset = walFrameOffset(iFrame, szPage);
1490 u32 pgno; /* Database page number for frame */
1491 u32 nTruncate; /* dbsize field from frame header */
1493 /* Read and decode the next log frame. */
1494 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
1495 if( rc!=SQLITE_OK ) break;
1496 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
1497 if( !isValid ) break;
1498 rc = walIndexAppend(pWal, iFrame, pgno);
1499 if( NEVER(rc!=SQLITE_OK) ) break;
1501 /* If nTruncate is non-zero, this is a commit record. */
1502 if( nTruncate ){
1503 pWal->hdr.mxFrame = iFrame;
1504 pWal->hdr.nPage = nTruncate;
1505 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
1506 testcase( szPage<=32768 );
1507 testcase( szPage>=65536 );
1508 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
1509 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
1512 pWal->apWiData[iPg] = aShare;
1513 SEH_SET_ON_ERROR(0,0);
1514 nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
1515 nHdr32 = nHdr / sizeof(u32);
1516 #ifndef SQLITE_SAFER_WALINDEX_RECOVERY
1517 /* Memcpy() should work fine here, on all reasonable implementations.
1518 ** Technically, memcpy() might change the destination to some
1519 ** intermediate value before setting to the final value, and that might
1520 ** cause a concurrent reader to malfunction. Memcpy() is allowed to
1521 ** do that, according to the spec, but no memcpy() implementation that
1522 ** we know of actually does that, which is why we say that memcpy()
1523 ** is safe for this. Memcpy() is certainly a lot faster.
1525 memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
1526 #else
1527 /* In the event that some platform is found for which memcpy()
1528 ** changes the destination to some intermediate value before
1529 ** setting the final value, this alternative copy routine is
1530 ** provided.
1533 int i;
1534 for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
1535 if( aShare[i]!=aPrivate[i] ){
1536 /* Atomic memory operations are not required here because if
1537 ** the value needs to be changed, that means it is not being
1538 ** accessed concurrently. */
1539 aShare[i] = aPrivate[i];
1543 #endif
1544 SEH_INJECT_FAULT;
1545 if( iFrame<=iLast ) break;
1548 SEH_FREE_ON_ERROR(aFrame, 0);
1549 sqlite3_free(aFrame);
1552 finished:
1553 if( rc==SQLITE_OK ){
1554 volatile WalCkptInfo *pInfo;
1555 int i;
1556 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
1557 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
1558 walIndexWriteHdr(pWal);
1560 /* Reset the checkpoint-header. This is safe because this thread is
1561 ** currently holding locks that exclude all other writers and
1562 ** checkpointers. Then set the values of read-mark slots 1 through N.
1564 pInfo = walCkptInfo(pWal);
1565 pInfo->nBackfill = 0;
1566 pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
1567 pInfo->aReadMark[0] = 0;
1568 for(i=1; i<WAL_NREADER; i++){
1569 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
1570 if( rc==SQLITE_OK ){
1571 if( i==1 && pWal->hdr.mxFrame ){
1572 pInfo->aReadMark[i] = pWal->hdr.mxFrame;
1573 }else{
1574 pInfo->aReadMark[i] = READMARK_NOT_USED;
1576 SEH_INJECT_FAULT;
1577 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
1578 }else if( rc!=SQLITE_BUSY ){
1579 goto recovery_error;
1583 /* If more than one frame was recovered from the log file, report an
1584 ** event via sqlite3_log(). This is to help with identifying performance
1585 ** problems caused by applications routinely shutting down without
1586 ** checkpointing the log file.
1588 if( pWal->hdr.nPage ){
1589 sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
1590 "recovered %d frames from WAL file %s",
1591 pWal->hdr.mxFrame, pWal->zWalName
1596 recovery_error:
1597 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
1598 walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
1599 return rc;
1603 ** Close an open wal-index.
1605 static void walIndexClose(Wal *pWal, int isDelete){
1606 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
1607 int i;
1608 for(i=0; i<pWal->nWiData; i++){
1609 sqlite3_free((void *)pWal->apWiData[i]);
1610 pWal->apWiData[i] = 0;
1613 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
1614 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
1619 ** Open a connection to the WAL file zWalName. The database file must
1620 ** already be opened on connection pDbFd. The buffer that zWalName points
1621 ** to must remain valid for the lifetime of the returned Wal* handle.
1623 ** A SHARED lock should be held on the database file when this function
1624 ** is called. The purpose of this SHARED lock is to prevent any other
1625 ** client from unlinking the WAL or wal-index file. If another process
1626 ** were to do this just after this client opened one of these files, the
1627 ** system would be badly broken.
1629 ** If the log file is successfully opened, SQLITE_OK is returned and
1630 ** *ppWal is set to point to a new WAL handle. If an error occurs,
1631 ** an SQLite error code is returned and *ppWal is left unmodified.
1633 int sqlite3WalOpen(
1634 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
1635 sqlite3_file *pDbFd, /* The open database file */
1636 const char *zWalName, /* Name of the WAL file */
1637 int bNoShm, /* True to run in heap-memory mode */
1638 i64 mxWalSize, /* Truncate WAL to this size on reset */
1639 Wal **ppWal /* OUT: Allocated Wal handle */
1641 int rc; /* Return Code */
1642 Wal *pRet; /* Object to allocate and return */
1643 int flags; /* Flags passed to OsOpen() */
1645 assert( zWalName && zWalName[0] );
1646 assert( pDbFd );
1648 /* Verify the values of various constants. Any changes to the values
1649 ** of these constants would result in an incompatible on-disk format
1650 ** for the -shm file. Any change that causes one of these asserts to
1651 ** fail is a backward compatibility problem, even if the change otherwise
1652 ** works.
1654 ** This table also serves as a helpful cross-reference when trying to
1655 ** interpret hex dumps of the -shm file.
1657 assert( 48 == sizeof(WalIndexHdr) );
1658 assert( 40 == sizeof(WalCkptInfo) );
1659 assert( 120 == WALINDEX_LOCK_OFFSET );
1660 assert( 136 == WALINDEX_HDR_SIZE );
1661 assert( 4096 == HASHTABLE_NPAGE );
1662 assert( 4062 == HASHTABLE_NPAGE_ONE );
1663 assert( 8192 == HASHTABLE_NSLOT );
1664 assert( 383 == HASHTABLE_HASH_1 );
1665 assert( 32768 == WALINDEX_PGSZ );
1666 assert( 8 == SQLITE_SHM_NLOCK );
1667 assert( 5 == WAL_NREADER );
1668 assert( 24 == WAL_FRAME_HDRSIZE );
1669 assert( 32 == WAL_HDRSIZE );
1670 assert( 120 == WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK );
1671 assert( 121 == WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK );
1672 assert( 122 == WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK );
1673 assert( 123 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) );
1674 assert( 124 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) );
1675 assert( 125 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) );
1676 assert( 126 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) );
1677 assert( 127 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) );
1679 /* In the amalgamation, the os_unix.c and os_win.c source files come before
1680 ** this source file. Verify that the #defines of the locking byte offsets
1681 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
1682 ** For that matter, if the lock offset ever changes from its initial design
1683 ** value of 120, we need to know that so there is an assert() to check it.
1685 #ifdef WIN_SHM_BASE
1686 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
1687 #endif
1688 #ifdef UNIX_SHM_BASE
1689 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
1690 #endif
1693 /* Allocate an instance of struct Wal to return. */
1694 *ppWal = 0;
1695 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
1696 if( !pRet ){
1697 return SQLITE_NOMEM_BKPT;
1700 pRet->pVfs = pVfs;
1701 pRet->pWalFd = (sqlite3_file *)&pRet[1];
1702 pRet->pDbFd = pDbFd;
1703 pRet->readLock = -1;
1704 pRet->mxWalSize = mxWalSize;
1705 pRet->zWalName = zWalName;
1706 pRet->syncHeader = 1;
1707 pRet->padToSectorBoundary = 1;
1708 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
1710 /* Open file handle on the write-ahead log file. */
1711 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
1712 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
1713 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
1714 pRet->readOnly = WAL_RDONLY;
1717 if( rc!=SQLITE_OK ){
1718 walIndexClose(pRet, 0);
1719 sqlite3OsClose(pRet->pWalFd);
1720 sqlite3_free(pRet);
1721 }else{
1722 int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
1723 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
1724 if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
1725 pRet->padToSectorBoundary = 0;
1727 *ppWal = pRet;
1728 WALTRACE(("WAL%d: opened\n", pRet));
1730 return rc;
1734 ** Change the size to which the WAL file is truncated on each reset.
1736 void sqlite3WalLimit(Wal *pWal, i64 iLimit){
1737 if( pWal ) pWal->mxWalSize = iLimit;
1741 ** Find the smallest page number out of all pages held in the WAL that
1742 ** has not been returned by any prior invocation of this method on the
1743 ** same WalIterator object. Write into *piFrame the frame index where
1744 ** that page was last written into the WAL. Write into *piPage the page
1745 ** number.
1747 ** Return 0 on success. If there are no pages in the WAL with a page
1748 ** number larger than *piPage, then return 1.
1750 static int walIteratorNext(
1751 WalIterator *p, /* Iterator */
1752 u32 *piPage, /* OUT: The page number of the next page */
1753 u32 *piFrame /* OUT: Wal frame index of next page */
1755 u32 iMin; /* Result pgno must be greater than iMin */
1756 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
1757 int i; /* For looping through segments */
1759 iMin = p->iPrior;
1760 assert( iMin<0xffffffff );
1761 for(i=p->nSegment-1; i>=0; i--){
1762 struct WalSegment *pSegment = &p->aSegment[i];
1763 while( pSegment->iNext<pSegment->nEntry ){
1764 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
1765 if( iPg>iMin ){
1766 if( iPg<iRet ){
1767 iRet = iPg;
1768 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
1770 break;
1772 pSegment->iNext++;
1776 *piPage = p->iPrior = iRet;
1777 return (iRet==0xFFFFFFFF);
1781 ** This function merges two sorted lists into a single sorted list.
1783 ** aLeft[] and aRight[] are arrays of indices. The sort key is
1784 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
1785 ** is guaranteed for all J<K:
1787 ** aContent[aLeft[J]] < aContent[aLeft[K]]
1788 ** aContent[aRight[J]] < aContent[aRight[K]]
1790 ** This routine overwrites aRight[] with a new (probably longer) sequence
1791 ** of indices such that the aRight[] contains every index that appears in
1792 ** either aLeft[] or the old aRight[] and such that the second condition
1793 ** above is still met.
1795 ** The aContent[aLeft[X]] values will be unique for all X. And the
1796 ** aContent[aRight[X]] values will be unique too. But there might be
1797 ** one or more combinations of X and Y such that
1799 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
1801 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
1803 static void walMerge(
1804 const u32 *aContent, /* Pages in wal - keys for the sort */
1805 ht_slot *aLeft, /* IN: Left hand input list */
1806 int nLeft, /* IN: Elements in array *paLeft */
1807 ht_slot **paRight, /* IN/OUT: Right hand input list */
1808 int *pnRight, /* IN/OUT: Elements in *paRight */
1809 ht_slot *aTmp /* Temporary buffer */
1811 int iLeft = 0; /* Current index in aLeft */
1812 int iRight = 0; /* Current index in aRight */
1813 int iOut = 0; /* Current index in output buffer */
1814 int nRight = *pnRight;
1815 ht_slot *aRight = *paRight;
1817 assert( nLeft>0 && nRight>0 );
1818 while( iRight<nRight || iLeft<nLeft ){
1819 ht_slot logpage;
1820 Pgno dbpage;
1822 if( (iLeft<nLeft)
1823 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
1825 logpage = aLeft[iLeft++];
1826 }else{
1827 logpage = aRight[iRight++];
1829 dbpage = aContent[logpage];
1831 aTmp[iOut++] = logpage;
1832 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
1834 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
1835 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
1838 *paRight = aLeft;
1839 *pnRight = iOut;
1840 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
1844 ** Sort the elements in list aList using aContent[] as the sort key.
1845 ** Remove elements with duplicate keys, preferring to keep the
1846 ** larger aList[] values.
1848 ** The aList[] entries are indices into aContent[]. The values in
1849 ** aList[] are to be sorted so that for all J<K:
1851 ** aContent[aList[J]] < aContent[aList[K]]
1853 ** For any X and Y such that
1855 ** aContent[aList[X]] == aContent[aList[Y]]
1857 ** Keep the larger of the two values aList[X] and aList[Y] and discard
1858 ** the smaller.
1860 static void walMergesort(
1861 const u32 *aContent, /* Pages in wal */
1862 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
1863 ht_slot *aList, /* IN/OUT: List to sort */
1864 int *pnList /* IN/OUT: Number of elements in aList[] */
1866 struct Sublist {
1867 int nList; /* Number of elements in aList */
1868 ht_slot *aList; /* Pointer to sub-list content */
1871 const int nList = *pnList; /* Size of input list */
1872 int nMerge = 0; /* Number of elements in list aMerge */
1873 ht_slot *aMerge = 0; /* List to be merged */
1874 int iList; /* Index into input list */
1875 u32 iSub = 0; /* Index into aSub array */
1876 struct Sublist aSub[13]; /* Array of sub-lists */
1878 memset(aSub, 0, sizeof(aSub));
1879 assert( nList<=HASHTABLE_NPAGE && nList>0 );
1880 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
1882 for(iList=0; iList<nList; iList++){
1883 nMerge = 1;
1884 aMerge = &aList[iList];
1885 for(iSub=0; iList & (1<<iSub); iSub++){
1886 struct Sublist *p;
1887 assert( iSub<ArraySize(aSub) );
1888 p = &aSub[iSub];
1889 assert( p->aList && p->nList<=(1<<iSub) );
1890 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
1891 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
1893 aSub[iSub].aList = aMerge;
1894 aSub[iSub].nList = nMerge;
1897 for(iSub++; iSub<ArraySize(aSub); iSub++){
1898 if( nList & (1<<iSub) ){
1899 struct Sublist *p;
1900 assert( iSub<ArraySize(aSub) );
1901 p = &aSub[iSub];
1902 assert( p->nList<=(1<<iSub) );
1903 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
1904 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
1907 assert( aMerge==aList );
1908 *pnList = nMerge;
1910 #ifdef SQLITE_DEBUG
1912 int i;
1913 for(i=1; i<*pnList; i++){
1914 assert( aContent[aList[i]] > aContent[aList[i-1]] );
1917 #endif
1921 ** Free an iterator allocated by walIteratorInit().
1923 static void walIteratorFree(WalIterator *p){
1924 sqlite3_free(p);
1928 ** Construct a WalInterator object that can be used to loop over all
1929 ** pages in the WAL following frame nBackfill in ascending order. Frames
1930 ** nBackfill or earlier may be included - excluding them is an optimization
1931 ** only. The caller must hold the checkpoint lock.
1933 ** On success, make *pp point to the newly allocated WalInterator object
1934 ** return SQLITE_OK. Otherwise, return an error code. If this routine
1935 ** returns an error, the value of *pp is undefined.
1937 ** The calling routine should invoke walIteratorFree() to destroy the
1938 ** WalIterator object when it has finished with it.
1940 static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
1941 WalIterator *p; /* Return value */
1942 int nSegment; /* Number of segments to merge */
1943 u32 iLast; /* Last frame in log */
1944 sqlite3_int64 nByte; /* Number of bytes to allocate */
1945 int i; /* Iterator variable */
1946 ht_slot *aTmp; /* Temp space used by merge-sort */
1947 int rc = SQLITE_OK; /* Return Code */
1949 /* This routine only runs while holding the checkpoint lock. And
1950 ** it only runs if there is actually content in the log (mxFrame>0).
1952 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
1953 iLast = pWal->hdr.mxFrame;
1955 /* Allocate space for the WalIterator object. */
1956 nSegment = walFramePage(iLast) + 1;
1957 nByte = sizeof(WalIterator)
1958 + (nSegment-1)*sizeof(struct WalSegment)
1959 + iLast*sizeof(ht_slot);
1960 p = (WalIterator *)sqlite3_malloc64(nByte
1961 + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
1963 if( !p ){
1964 return SQLITE_NOMEM_BKPT;
1966 memset(p, 0, nByte);
1967 p->nSegment = nSegment;
1968 aTmp = (ht_slot*)&(((u8*)p)[nByte]);
1969 SEH_FREE_ON_ERROR(0, p);
1970 for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
1971 WalHashLoc sLoc;
1973 rc = walHashGet(pWal, i, &sLoc);
1974 if( rc==SQLITE_OK ){
1975 int j; /* Counter variable */
1976 int nEntry; /* Number of entries in this segment */
1977 ht_slot *aIndex; /* Sorted index for this segment */
1979 if( (i+1)==nSegment ){
1980 nEntry = (int)(iLast - sLoc.iZero);
1981 }else{
1982 nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
1984 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
1985 sLoc.iZero++;
1987 for(j=0; j<nEntry; j++){
1988 aIndex[j] = (ht_slot)j;
1990 walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
1991 p->aSegment[i].iZero = sLoc.iZero;
1992 p->aSegment[i].nEntry = nEntry;
1993 p->aSegment[i].aIndex = aIndex;
1994 p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
1997 if( rc!=SQLITE_OK ){
1998 SEH_FREE_ON_ERROR(p, 0);
1999 walIteratorFree(p);
2000 p = 0;
2002 *pp = p;
2003 return rc;
2006 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
2010 ** Attempt to enable blocking locks that block for nMs ms. Return 1 if
2011 ** blocking locks are successfully enabled, or 0 otherwise.
2013 static int walEnableBlockingMs(Wal *pWal, int nMs){
2014 int rc = sqlite3OsFileControl(
2015 pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&nMs
2017 return (rc==SQLITE_OK);
2021 ** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
2022 ** they are supported by the VFS, and (b) the database handle is configured
2023 ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
2024 ** or 0 otherwise.
2026 static int walEnableBlocking(Wal *pWal){
2027 int res = 0;
2028 if( pWal->db ){
2029 int tmout = pWal->db->busyTimeout;
2030 if( tmout ){
2031 res = walEnableBlockingMs(pWal, tmout);
2034 return res;
2038 ** Disable blocking locks.
2040 static void walDisableBlocking(Wal *pWal){
2041 int tmout = 0;
2042 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
2046 ** If parameter bLock is true, attempt to enable blocking locks, take
2047 ** the WRITER lock, and then disable blocking locks. If blocking locks
2048 ** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
2049 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
2050 ** an error if blocking locks can not be enabled.
2052 ** If the bLock parameter is false and the WRITER lock is held, release it.
2054 int sqlite3WalWriteLock(Wal *pWal, int bLock){
2055 int rc = SQLITE_OK;
2056 assert( pWal->readLock<0 || bLock==0 );
2057 if( bLock ){
2058 assert( pWal->db );
2059 if( walEnableBlocking(pWal) ){
2060 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
2061 if( rc==SQLITE_OK ){
2062 pWal->writeLock = 1;
2064 walDisableBlocking(pWal);
2066 }else if( pWal->writeLock ){
2067 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
2068 pWal->writeLock = 0;
2070 return rc;
2074 ** Set the database handle used to determine if blocking locks are required.
2076 void sqlite3WalDb(Wal *pWal, sqlite3 *db){
2077 pWal->db = db;
2080 #else
2081 # define walEnableBlocking(x) 0
2082 # define walDisableBlocking(x)
2083 # define walEnableBlockingMs(pWal, ms) 0
2084 # define sqlite3WalDb(pWal, db)
2085 #endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
2089 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
2090 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
2091 ** busy-handler function. Invoke it and retry the lock until either the
2092 ** lock is successfully obtained or the busy-handler returns 0.
2094 static int walBusyLock(
2095 Wal *pWal, /* WAL connection */
2096 int (*xBusy)(void*), /* Function to call when busy */
2097 void *pBusyArg, /* Context argument for xBusyHandler */
2098 int lockIdx, /* Offset of first byte to lock */
2099 int n /* Number of bytes to lock */
2101 int rc;
2102 do {
2103 rc = walLockExclusive(pWal, lockIdx, n);
2104 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
2105 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
2106 if( rc==SQLITE_BUSY_TIMEOUT ){
2107 walDisableBlocking(pWal);
2108 rc = SQLITE_BUSY;
2110 #endif
2111 return rc;
2115 ** The cache of the wal-index header must be valid to call this function.
2116 ** Return the page-size in bytes used by the database.
2118 static int walPagesize(Wal *pWal){
2119 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
2123 ** The following is guaranteed when this function is called:
2125 ** a) the WRITER lock is held,
2126 ** b) the entire log file has been checkpointed, and
2127 ** c) any existing readers are reading exclusively from the database
2128 ** file - there are no readers that may attempt to read a frame from
2129 ** the log file.
2131 ** This function updates the shared-memory structures so that the next
2132 ** client to write to the database (which may be this one) does so by
2133 ** writing frames into the start of the log file.
2135 ** The value of parameter salt1 is used as the aSalt[1] value in the
2136 ** new wal-index header. It should be passed a pseudo-random value (i.e.
2137 ** one obtained from sqlite3_randomness()).
2139 static void walRestartHdr(Wal *pWal, u32 salt1){
2140 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
2141 int i; /* Loop counter */
2142 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
2143 pWal->nCkpt++;
2144 pWal->hdr.mxFrame = 0;
2145 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
2146 memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
2147 walIndexWriteHdr(pWal);
2148 AtomicStore(&pInfo->nBackfill, 0);
2149 pInfo->nBackfillAttempted = 0;
2150 pInfo->aReadMark[1] = 0;
2151 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
2152 assert( pInfo->aReadMark[0]==0 );
2156 ** Copy as much content as we can from the WAL back into the database file
2157 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
2159 ** The amount of information copies from WAL to database might be limited
2160 ** by active readers. This routine will never overwrite a database page
2161 ** that a concurrent reader might be using.
2163 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
2164 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
2165 ** checkpoints are always run by a background thread or background
2166 ** process, foreground threads will never block on a lengthy fsync call.
2168 ** Fsync is called on the WAL before writing content out of the WAL and
2169 ** into the database. This ensures that if the new content is persistent
2170 ** in the WAL and can be recovered following a power-loss or hard reset.
2172 ** Fsync is also called on the database file if (and only if) the entire
2173 ** WAL content is copied into the database file. This second fsync makes
2174 ** it safe to delete the WAL since the new content will persist in the
2175 ** database file.
2177 ** This routine uses and updates the nBackfill field of the wal-index header.
2178 ** This is the only routine that will increase the value of nBackfill.
2179 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
2180 ** its value.)
2182 ** The caller must be holding sufficient locks to ensure that no other
2183 ** checkpoint is running (in any other thread or process) at the same
2184 ** time.
2186 static int walCheckpoint(
2187 Wal *pWal, /* Wal connection */
2188 sqlite3 *db, /* Check for interrupts on this handle */
2189 int eMode, /* One of PASSIVE, FULL or RESTART */
2190 int (*xBusy)(void*), /* Function to call when busy */
2191 void *pBusyArg, /* Context argument for xBusyHandler */
2192 int sync_flags, /* Flags for OsSync() (or 0) */
2193 u8 *zBuf /* Temporary buffer to use */
2195 int rc = SQLITE_OK; /* Return code */
2196 int szPage; /* Database page-size */
2197 WalIterator *pIter = 0; /* Wal iterator context */
2198 u32 iDbpage = 0; /* Next database page to write */
2199 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
2200 u32 mxSafeFrame; /* Max frame that can be backfilled */
2201 u32 mxPage; /* Max database page to write */
2202 int i; /* Loop counter */
2203 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
2205 szPage = walPagesize(pWal);
2206 testcase( szPage<=32768 );
2207 testcase( szPage>=65536 );
2208 pInfo = walCkptInfo(pWal);
2209 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
2211 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
2212 ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
2213 assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
2215 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
2216 ** safe to write into the database. Frames beyond mxSafeFrame might
2217 ** overwrite database pages that are in use by active readers and thus
2218 ** cannot be backfilled from the WAL.
2220 mxSafeFrame = pWal->hdr.mxFrame;
2221 mxPage = pWal->hdr.nPage;
2222 for(i=1; i<WAL_NREADER; i++){
2223 u32 y = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
2224 if( mxSafeFrame>y ){
2225 assert( y<=pWal->hdr.mxFrame );
2226 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
2227 if( rc==SQLITE_OK ){
2228 u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
2229 AtomicStore(pInfo->aReadMark+i, iMark); SEH_INJECT_FAULT;
2230 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
2231 }else if( rc==SQLITE_BUSY ){
2232 mxSafeFrame = y;
2233 xBusy = 0;
2234 }else{
2235 goto walcheckpoint_out;
2240 /* Allocate the iterator */
2241 if( pInfo->nBackfill<mxSafeFrame ){
2242 rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
2243 assert( rc==SQLITE_OK || pIter==0 );
2246 if( pIter
2247 && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
2249 u32 nBackfill = pInfo->nBackfill;
2250 pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT;
2252 /* Sync the WAL to disk */
2253 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
2255 /* If the database may grow as a result of this checkpoint, hint
2256 ** about the eventual size of the db file to the VFS layer.
2258 if( rc==SQLITE_OK ){
2259 i64 nReq = ((i64)mxPage * szPage);
2260 i64 nSize; /* Current size of database file */
2261 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
2262 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
2263 if( rc==SQLITE_OK && nSize<nReq ){
2264 if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
2265 /* If the size of the final database is larger than the current
2266 ** database plus the amount of data in the wal file, plus the
2267 ** maximum size of the pending-byte page (65536 bytes), then
2268 ** must be corruption somewhere. */
2269 rc = SQLITE_CORRUPT_BKPT;
2270 }else{
2271 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
2277 /* Iterate through the contents of the WAL, copying data to the db file */
2278 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
2279 i64 iOffset;
2280 assert( walFramePgno(pWal, iFrame)==iDbpage );
2281 SEH_INJECT_FAULT;
2282 if( AtomicLoad(&db->u1.isInterrupted) ){
2283 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
2284 break;
2286 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
2287 continue;
2289 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
2290 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
2291 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
2292 if( rc!=SQLITE_OK ) break;
2293 iOffset = (iDbpage-1)*(i64)szPage;
2294 testcase( IS_BIG_INT(iOffset) );
2295 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
2296 if( rc!=SQLITE_OK ) break;
2298 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
2300 /* If work was actually accomplished... */
2301 if( rc==SQLITE_OK ){
2302 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
2303 i64 szDb = pWal->hdr.nPage*(i64)szPage;
2304 testcase( IS_BIG_INT(szDb) );
2305 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
2306 if( rc==SQLITE_OK ){
2307 rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
2310 if( rc==SQLITE_OK ){
2311 AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT;
2315 /* Release the reader lock held while backfilling */
2316 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
2319 if( rc==SQLITE_BUSY ){
2320 /* Reset the return code so as not to report a checkpoint failure
2321 ** just because there are active readers. */
2322 rc = SQLITE_OK;
2326 /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
2327 ** entire wal file has been copied into the database file, then block
2328 ** until all readers have finished using the wal file. This ensures that
2329 ** the next process to write to the database restarts the wal file.
2331 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
2332 assert( pWal->writeLock );
2333 SEH_INJECT_FAULT;
2334 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
2335 rc = SQLITE_BUSY;
2336 }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
2337 u32 salt1;
2338 sqlite3_randomness(4, &salt1);
2339 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
2340 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
2341 if( rc==SQLITE_OK ){
2342 if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
2343 /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
2344 ** SQLITE_CHECKPOINT_RESTART with the addition that it also
2345 ** truncates the log file to zero bytes just prior to a
2346 ** successful return.
2348 ** In theory, it might be safe to do this without updating the
2349 ** wal-index header in shared memory, as all subsequent reader or
2350 ** writer clients should see that the entire log file has been
2351 ** checkpointed and behave accordingly. This seems unsafe though,
2352 ** as it would leave the system in a state where the contents of
2353 ** the wal-index header do not match the contents of the
2354 ** file-system. To avoid this, update the wal-index header to
2355 ** indicate that the log file contains zero valid frames. */
2356 walRestartHdr(pWal, salt1);
2357 rc = sqlite3OsTruncate(pWal->pWalFd, 0);
2359 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
2364 walcheckpoint_out:
2365 SEH_FREE_ON_ERROR(pIter, 0);
2366 walIteratorFree(pIter);
2367 return rc;
2371 ** If the WAL file is currently larger than nMax bytes in size, truncate
2372 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
2374 static void walLimitSize(Wal *pWal, i64 nMax){
2375 i64 sz;
2376 int rx;
2377 sqlite3BeginBenignMalloc();
2378 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
2379 if( rx==SQLITE_OK && (sz > nMax ) ){
2380 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
2382 sqlite3EndBenignMalloc();
2383 if( rx ){
2384 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
2388 #ifdef SQLITE_USE_SEH
2390 ** This is the "standard" exception handler used in a few places to handle
2391 ** an exception thrown by reading from the *-shm mapping after it has become
2392 ** invalid in SQLITE_USE_SEH builds. It is used as follows:
2394 ** SEH_TRY { ... }
2395 ** SEH_EXCEPT( rc = walHandleException(pWal); )
2397 ** This function does three things:
2399 ** 1) Determines the locks that should be held, based on the contents of
2400 ** the Wal.readLock, Wal.writeLock and Wal.ckptLock variables. All other
2401 ** held locks are assumed to be transient locks that would have been
2402 ** released had the exception not been thrown and are dropped.
2404 ** 2) Frees the pointer at Wal.pFree, if any, using sqlite3_free().
2406 ** 3) Set pWal->apWiData[pWal->iWiPg] to pWal->pWiValue if not NULL
2408 ** 4) Returns SQLITE_IOERR.
2410 static int walHandleException(Wal *pWal){
2411 if( pWal->exclusiveMode==0 ){
2412 static const int S = 1;
2413 static const int E = (1<<SQLITE_SHM_NLOCK);
2414 int ii;
2415 u32 mUnlock = pWal->lockMask & ~(
2416 (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
2417 | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
2418 | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
2420 for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
2421 if( (S<<ii) & mUnlock ) walUnlockShared(pWal, ii);
2422 if( (E<<ii) & mUnlock ) walUnlockExclusive(pWal, ii, 1);
2425 sqlite3_free(pWal->pFree);
2426 pWal->pFree = 0;
2427 if( pWal->pWiValue ){
2428 pWal->apWiData[pWal->iWiPg] = pWal->pWiValue;
2429 pWal->pWiValue = 0;
2431 return SQLITE_IOERR_IN_PAGE;
2435 ** Assert that the Wal.lockMask mask, which indicates the locks held
2436 ** by the connenction, is consistent with the Wal.readLock, Wal.writeLock
2437 ** and Wal.ckptLock variables. To be used as:
2439 ** assert( walAssertLockmask(pWal) );
2441 static int walAssertLockmask(Wal *pWal){
2442 if( pWal->exclusiveMode==0 ){
2443 static const int S = 1;
2444 static const int E = (1<<SQLITE_SHM_NLOCK);
2445 u32 mExpect = (
2446 (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
2447 | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
2448 | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
2449 #ifdef SQLITE_ENABLE_SNAPSHOT
2450 | (pWal->pSnapshot ? (pWal->lockMask & (1 << WAL_CKPT_LOCK)) : 0)
2451 #endif
2453 assert( mExpect==pWal->lockMask );
2455 return 1;
2459 ** Return and zero the "system error" field set when an
2460 ** EXCEPTION_IN_PAGE_ERROR exception is caught.
2462 int sqlite3WalSystemErrno(Wal *pWal){
2463 int iRet = 0;
2464 if( pWal ){
2465 iRet = pWal->iSysErrno;
2466 pWal->iSysErrno = 0;
2468 return iRet;
2471 #else
2472 # define walAssertLockmask(x) 1
2473 #endif /* ifdef SQLITE_USE_SEH */
2476 ** Close a connection to a log file.
2478 int sqlite3WalClose(
2479 Wal *pWal, /* Wal to close */
2480 sqlite3 *db, /* For interrupt flag */
2481 int sync_flags, /* Flags to pass to OsSync() (or 0) */
2482 int nBuf,
2483 u8 *zBuf /* Buffer of at least nBuf bytes */
2485 int rc = SQLITE_OK;
2486 if( pWal ){
2487 int isDelete = 0; /* True to unlink wal and wal-index files */
2489 assert( walAssertLockmask(pWal) );
2491 /* If an EXCLUSIVE lock can be obtained on the database file (using the
2492 ** ordinary, rollback-mode locking methods, this guarantees that the
2493 ** connection associated with this log file is the only connection to
2494 ** the database. In this case checkpoint the database and unlink both
2495 ** the wal and wal-index files.
2497 ** The EXCLUSIVE lock is not released before returning.
2499 if( zBuf!=0
2500 && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
2502 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
2503 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
2505 rc = sqlite3WalCheckpoint(pWal, db,
2506 SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
2508 if( rc==SQLITE_OK ){
2509 int bPersist = -1;
2510 sqlite3OsFileControlHint(
2511 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
2513 if( bPersist!=1 ){
2514 /* Try to delete the WAL file if the checkpoint completed and
2515 ** fsynced (rc==SQLITE_OK) and if we are not in persistent-wal
2516 ** mode (!bPersist) */
2517 isDelete = 1;
2518 }else if( pWal->mxWalSize>=0 ){
2519 /* Try to truncate the WAL file to zero bytes if the checkpoint
2520 ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
2521 ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
2522 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
2523 ** to zero bytes as truncating to the journal_size_limit might
2524 ** leave a corrupt WAL file on disk. */
2525 walLimitSize(pWal, 0);
2530 walIndexClose(pWal, isDelete);
2531 sqlite3OsClose(pWal->pWalFd);
2532 if( isDelete ){
2533 sqlite3BeginBenignMalloc();
2534 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
2535 sqlite3EndBenignMalloc();
2537 WALTRACE(("WAL%p: closed\n", pWal));
2538 sqlite3_free((void *)pWal->apWiData);
2539 sqlite3_free(pWal);
2541 return rc;
2545 ** Try to read the wal-index header. Return 0 on success and 1 if
2546 ** there is a problem.
2548 ** The wal-index is in shared memory. Another thread or process might
2549 ** be writing the header at the same time this procedure is trying to
2550 ** read it, which might result in inconsistency. A dirty read is detected
2551 ** by verifying that both copies of the header are the same and also by
2552 ** a checksum on the header.
2554 ** If and only if the read is consistent and the header is different from
2555 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
2556 ** and *pChanged is set to 1.
2558 ** If the checksum cannot be verified return non-zero. If the header
2559 ** is read successfully and the checksum verified, return zero.
2561 static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
2562 u32 aCksum[2]; /* Checksum on the header content */
2563 WalIndexHdr h1, h2; /* Two copies of the header content */
2564 WalIndexHdr volatile *aHdr; /* Header in shared memory */
2566 /* The first page of the wal-index must be mapped at this point. */
2567 assert( pWal->nWiData>0 && pWal->apWiData[0] );
2569 /* Read the header. This might happen concurrently with a write to the
2570 ** same area of shared memory on a different CPU in a SMP,
2571 ** meaning it is possible that an inconsistent snapshot is read
2572 ** from the file. If this happens, return non-zero.
2574 ** tag-20200519-1:
2575 ** There are two copies of the header at the beginning of the wal-index.
2576 ** When reading, read [0] first then [1]. Writes are in the reverse order.
2577 ** Memory barriers are used to prevent the compiler or the hardware from
2578 ** reordering the reads and writes. TSAN and similar tools can sometimes
2579 ** give false-positive warnings about these accesses because the tools do not
2580 ** account for the double-read and the memory barrier. The use of mutexes
2581 ** here would be problematic as the memory being accessed is potentially
2582 ** shared among multiple processes and not all mutex implementations work
2583 ** reliably in that environment.
2585 aHdr = walIndexHdr(pWal);
2586 memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
2587 walShmBarrier(pWal);
2588 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
2590 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
2591 return 1; /* Dirty read */
2593 if( h1.isInit==0 ){
2594 return 1; /* Malformed header - probably all zeros */
2596 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
2597 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
2598 return 1; /* Checksum does not match */
2601 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
2602 *pChanged = 1;
2603 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
2604 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
2605 testcase( pWal->szPage<=32768 );
2606 testcase( pWal->szPage>=65536 );
2609 /* The header was successfully read. Return zero. */
2610 return 0;
2614 ** This is the value that walTryBeginRead returns when it needs to
2615 ** be retried.
2617 #define WAL_RETRY (-1)
2620 ** Read the wal-index header from the wal-index and into pWal->hdr.
2621 ** If the wal-header appears to be corrupt, try to reconstruct the
2622 ** wal-index from the WAL before returning.
2624 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
2625 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
2626 ** to 0.
2628 ** If the wal-index header is successfully read, return SQLITE_OK.
2629 ** Otherwise an SQLite error code.
2631 static int walIndexReadHdr(Wal *pWal, int *pChanged){
2632 int rc; /* Return code */
2633 int badHdr; /* True if a header read failed */
2634 volatile u32 *page0; /* Chunk of wal-index containing header */
2636 /* Ensure that page 0 of the wal-index (the page that contains the
2637 ** wal-index header) is mapped. Return early if an error occurs here.
2639 assert( pChanged );
2640 rc = walIndexPage(pWal, 0, &page0);
2641 if( rc!=SQLITE_OK ){
2642 assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
2643 if( rc==SQLITE_READONLY_CANTINIT ){
2644 /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
2645 ** was openable but is not writable, and this thread is unable to
2646 ** confirm that another write-capable connection has the shared-memory
2647 ** open, and hence the content of the shared-memory is unreliable,
2648 ** since the shared-memory might be inconsistent with the WAL file
2649 ** and there is no writer on hand to fix it. */
2650 assert( page0==0 );
2651 assert( pWal->writeLock==0 );
2652 assert( pWal->readOnly & WAL_SHM_RDONLY );
2653 pWal->bShmUnreliable = 1;
2654 pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
2655 *pChanged = 1;
2656 }else{
2657 return rc; /* Any other non-OK return is just an error */
2659 }else{
2660 /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
2661 ** is zero, which prevents the SHM from growing */
2662 testcase( page0!=0 );
2664 assert( page0!=0 || pWal->writeLock==0 );
2666 /* If the first page of the wal-index has been mapped, try to read the
2667 ** wal-index header immediately, without holding any lock. This usually
2668 ** works, but may fail if the wal-index header is corrupt or currently
2669 ** being modified by another thread or process.
2671 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
2673 /* If the first attempt failed, it might have been due to a race
2674 ** with a writer. So get a WRITE lock and try again.
2676 if( badHdr ){
2677 if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
2678 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
2679 walUnlockShared(pWal, WAL_WRITE_LOCK);
2680 rc = SQLITE_READONLY_RECOVERY;
2682 }else{
2683 int bWriteLock = pWal->writeLock;
2684 if( bWriteLock
2685 || SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1))
2687 pWal->writeLock = 1;
2688 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
2689 badHdr = walIndexTryHdr(pWal, pChanged);
2690 if( badHdr ){
2691 /* If the wal-index header is still malformed even while holding
2692 ** a WRITE lock, it can only mean that the header is corrupted and
2693 ** needs to be reconstructed. So run recovery to do exactly that.
2694 ** Disable blocking locks first. */
2695 walDisableBlocking(pWal);
2696 rc = walIndexRecover(pWal);
2697 *pChanged = 1;
2700 if( bWriteLock==0 ){
2701 pWal->writeLock = 0;
2702 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
2708 /* If the header is read successfully, check the version number to make
2709 ** sure the wal-index was not constructed with some future format that
2710 ** this version of SQLite cannot understand.
2712 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
2713 rc = SQLITE_CANTOPEN_BKPT;
2715 if( pWal->bShmUnreliable ){
2716 if( rc!=SQLITE_OK ){
2717 walIndexClose(pWal, 0);
2718 pWal->bShmUnreliable = 0;
2719 assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
2720 /* walIndexRecover() might have returned SHORT_READ if a concurrent
2721 ** writer truncated the WAL out from under it. If that happens, it
2722 ** indicates that a writer has fixed the SHM file for us, so retry */
2723 if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
2725 pWal->exclusiveMode = WAL_NORMAL_MODE;
2728 return rc;
2732 ** Open a transaction in a connection where the shared-memory is read-only
2733 ** and where we cannot verify that there is a separate write-capable connection
2734 ** on hand to keep the shared-memory up-to-date with the WAL file.
2736 ** This can happen, for example, when the shared-memory is implemented by
2737 ** memory-mapping a *-shm file, where a prior writer has shut down and
2738 ** left the *-shm file on disk, and now the present connection is trying
2739 ** to use that database but lacks write permission on the *-shm file.
2740 ** Other scenarios are also possible, depending on the VFS implementation.
2742 ** Precondition:
2744 ** The *-wal file has been read and an appropriate wal-index has been
2745 ** constructed in pWal->apWiData[] using heap memory instead of shared
2746 ** memory.
2748 ** If this function returns SQLITE_OK, then the read transaction has
2749 ** been successfully opened. In this case output variable (*pChanged)
2750 ** is set to true before returning if the caller should discard the
2751 ** contents of the page cache before proceeding. Or, if it returns
2752 ** WAL_RETRY, then the heap memory wal-index has been discarded and
2753 ** the caller should retry opening the read transaction from the
2754 ** beginning (including attempting to map the *-shm file).
2756 ** If an error occurs, an SQLite error code is returned.
2758 static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
2759 i64 szWal; /* Size of wal file on disk in bytes */
2760 i64 iOffset; /* Current offset when reading wal file */
2761 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
2762 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
2763 int szFrame; /* Number of bytes in buffer aFrame[] */
2764 u8 *aData; /* Pointer to data part of aFrame buffer */
2765 volatile void *pDummy; /* Dummy argument for xShmMap */
2766 int rc; /* Return code */
2767 u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
2769 assert( pWal->bShmUnreliable );
2770 assert( pWal->readOnly & WAL_SHM_RDONLY );
2771 assert( pWal->nWiData>0 && pWal->apWiData[0] );
2773 /* Take WAL_READ_LOCK(0). This has the effect of preventing any
2774 ** writers from running a checkpoint, but does not stop them
2775 ** from running recovery. */
2776 rc = walLockShared(pWal, WAL_READ_LOCK(0));
2777 if( rc!=SQLITE_OK ){
2778 if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
2779 goto begin_unreliable_shm_out;
2781 pWal->readLock = 0;
2783 /* Check to see if a separate writer has attached to the shared-memory area,
2784 ** thus making the shared-memory "reliable" again. Do this by invoking
2785 ** the xShmMap() routine of the VFS and looking to see if the return
2786 ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
2788 ** If the shared-memory is now "reliable" return WAL_RETRY, which will
2789 ** cause the heap-memory WAL-index to be discarded and the actual
2790 ** shared memory to be used in its place.
2792 ** This step is important because, even though this connection is holding
2793 ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
2794 ** have already checkpointed the WAL file and, while the current
2795 ** is active, wrap the WAL and start overwriting frames that this
2796 ** process wants to use.
2798 ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
2799 ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
2800 ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
2801 ** even if some external agent does a "chmod" to make the shared-memory
2802 ** writable by us, until sqlite3OsShmUnmap() has been called.
2803 ** This is a requirement on the VFS implementation.
2805 rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
2806 assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
2807 if( rc!=SQLITE_READONLY_CANTINIT ){
2808 rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
2809 goto begin_unreliable_shm_out;
2812 /* We reach this point only if the real shared-memory is still unreliable.
2813 ** Assume the in-memory WAL-index substitute is correct and load it
2814 ** into pWal->hdr.
2816 memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
2818 /* Make sure some writer hasn't come in and changed the WAL file out
2819 ** from under us, then disconnected, while we were not looking.
2821 rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
2822 if( rc!=SQLITE_OK ){
2823 goto begin_unreliable_shm_out;
2825 if( szWal<WAL_HDRSIZE ){
2826 /* If the wal file is too small to contain a wal-header and the
2827 ** wal-index header has mxFrame==0, then it must be safe to proceed
2828 ** reading the database file only. However, the page cache cannot
2829 ** be trusted, as a read/write connection may have connected, written
2830 ** the db, run a checkpoint, truncated the wal file and disconnected
2831 ** since this client's last read transaction. */
2832 *pChanged = 1;
2833 rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
2834 goto begin_unreliable_shm_out;
2837 /* Check the salt keys at the start of the wal file still match. */
2838 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
2839 if( rc!=SQLITE_OK ){
2840 goto begin_unreliable_shm_out;
2842 if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
2843 /* Some writer has wrapped the WAL file while we were not looking.
2844 ** Return WAL_RETRY which will cause the in-memory WAL-index to be
2845 ** rebuilt. */
2846 rc = WAL_RETRY;
2847 goto begin_unreliable_shm_out;
2850 /* Allocate a buffer to read frames into */
2851 assert( (pWal->szPage & (pWal->szPage-1))==0 );
2852 assert( pWal->szPage>=512 && pWal->szPage<=65536 );
2853 szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
2854 aFrame = (u8 *)sqlite3_malloc64(szFrame);
2855 if( aFrame==0 ){
2856 rc = SQLITE_NOMEM_BKPT;
2857 goto begin_unreliable_shm_out;
2859 aData = &aFrame[WAL_FRAME_HDRSIZE];
2861 /* Check to see if a complete transaction has been appended to the
2862 ** wal file since the heap-memory wal-index was created. If so, the
2863 ** heap-memory wal-index is discarded and WAL_RETRY returned to
2864 ** the caller. */
2865 aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
2866 aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
2867 for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
2868 iOffset+szFrame<=szWal;
2869 iOffset+=szFrame
2871 u32 pgno; /* Database page number for frame */
2872 u32 nTruncate; /* dbsize field from frame header */
2874 /* Read and decode the next log frame. */
2875 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
2876 if( rc!=SQLITE_OK ) break;
2877 if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
2879 /* If nTruncate is non-zero, then a complete transaction has been
2880 ** appended to this wal file. Set rc to WAL_RETRY and break out of
2881 ** the loop. */
2882 if( nTruncate ){
2883 rc = WAL_RETRY;
2884 break;
2887 pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
2888 pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
2890 begin_unreliable_shm_out:
2891 sqlite3_free(aFrame);
2892 if( rc!=SQLITE_OK ){
2893 int i;
2894 for(i=0; i<pWal->nWiData; i++){
2895 sqlite3_free((void*)pWal->apWiData[i]);
2896 pWal->apWiData[i] = 0;
2898 pWal->bShmUnreliable = 0;
2899 sqlite3WalEndReadTransaction(pWal);
2900 *pChanged = 1;
2902 return rc;
2906 ** The final argument passed to walTryBeginRead() is of type (int*). The
2907 ** caller should invoke walTryBeginRead as follows:
2909 ** int cnt = 0;
2910 ** do {
2911 ** rc = walTryBeginRead(..., &cnt);
2912 ** }while( rc==WAL_RETRY );
2914 ** The final value of "cnt" is of no use to the caller. It is used by
2915 ** the implementation of walTryBeginRead() as follows:
2917 ** + Each time walTryBeginRead() is called, it is incremented. Once
2918 ** it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead()
2919 ** has many times been invoked and failed with WAL_RETRY - walTryBeginRead()
2920 ** returns SQLITE_PROTOCOL.
2922 ** + If SQLITE_ENABLE_SETLK_TIMEOUT is defined and walTryBeginRead() failed
2923 ** because a blocking lock timed out (SQLITE_BUSY_TIMEOUT from the OS
2924 ** layer), the WAL_RETRY_BLOCKED_MASK bit is set in "cnt". In this case
2925 ** the next invocation of walTryBeginRead() may omit an expected call to
2926 ** sqlite3OsSleep(). There has already been a delay when the previous call
2927 ** waited on a lock.
2929 #define WAL_RETRY_PROTOCOL_LIMIT 100
2930 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
2931 # define WAL_RETRY_BLOCKED_MASK 0x10000000
2932 #else
2933 # define WAL_RETRY_BLOCKED_MASK 0
2934 #endif
2937 ** Attempt to start a read transaction. This might fail due to a race or
2938 ** other transient condition. When that happens, it returns WAL_RETRY to
2939 ** indicate to the caller that it is safe to retry immediately.
2941 ** On success return SQLITE_OK. On a permanent failure (such an
2942 ** I/O error or an SQLITE_BUSY because another process is running
2943 ** recovery) return a positive error code.
2945 ** The useWal parameter is true to force the use of the WAL and disable
2946 ** the case where the WAL is bypassed because it has been completely
2947 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
2948 ** to make a copy of the wal-index header into pWal->hdr. If the
2949 ** wal-index header has changed, *pChanged is set to 1 (as an indication
2950 ** to the caller that the local page cache is obsolete and needs to be
2951 ** flushed.) When useWal==1, the wal-index header is assumed to already
2952 ** be loaded and the pChanged parameter is unused.
2954 ** The caller must set the cnt parameter to the number of prior calls to
2955 ** this routine during the current read attempt that returned WAL_RETRY.
2956 ** This routine will start taking more aggressive measures to clear the
2957 ** race conditions after multiple WAL_RETRY returns, and after an excessive
2958 ** number of errors will ultimately return SQLITE_PROTOCOL. The
2959 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
2960 ** and is not honoring the locking protocol. There is a vanishingly small
2961 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
2962 ** bad luck when there is lots of contention for the wal-index, but that
2963 ** possibility is so small that it can be safely neglected, we believe.
2965 ** On success, this routine obtains a read lock on
2966 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
2967 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
2968 ** that means the Wal does not hold any read lock. The reader must not
2969 ** access any database page that is modified by a WAL frame up to and
2970 ** including frame number aReadMark[pWal->readLock]. The reader will
2971 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
2972 ** Or if pWal->readLock==0, then the reader will ignore the WAL
2973 ** completely and get all content directly from the database file.
2974 ** If the useWal parameter is 1 then the WAL will never be ignored and
2975 ** this routine will always set pWal->readLock>0 on success.
2976 ** When the read transaction is completed, the caller must release the
2977 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
2979 ** This routine uses the nBackfill and aReadMark[] fields of the header
2980 ** to select a particular WAL_READ_LOCK() that strives to let the
2981 ** checkpoint process do as much work as possible. This routine might
2982 ** update values of the aReadMark[] array in the header, but if it does
2983 ** so it takes care to hold an exclusive lock on the corresponding
2984 ** WAL_READ_LOCK() while changing values.
2986 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){
2987 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
2988 u32 mxReadMark; /* Largest aReadMark[] value */
2989 int mxI; /* Index of largest aReadMark[] value */
2990 int i; /* Loop counter */
2991 int rc = SQLITE_OK; /* Return code */
2992 u32 mxFrame; /* Wal frame to lock to */
2993 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
2994 int nBlockTmout = 0;
2995 #endif
2997 assert( pWal->readLock<0 ); /* Not currently locked */
2999 /* useWal may only be set for read/write connections */
3000 assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
3002 /* Take steps to avoid spinning forever if there is a protocol error.
3004 ** Circumstances that cause a RETRY should only last for the briefest
3005 ** instances of time. No I/O or other system calls are done while the
3006 ** locks are held, so the locks should not be held for very long. But
3007 ** if we are unlucky, another process that is holding a lock might get
3008 ** paged out or take a page-fault that is time-consuming to resolve,
3009 ** during the few nanoseconds that it is holding the lock. In that case,
3010 ** it might take longer than normal for the lock to free.
3012 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
3013 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
3014 ** is more of a scheduler yield than an actual delay. But on the 10th
3015 ** an subsequent retries, the delays start becoming longer and longer,
3016 ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
3017 ** The total delay time before giving up is less than 10 seconds.
3019 (*pCnt)++;
3020 if( *pCnt>5 ){
3021 int nDelay = 1; /* Pause time in microseconds */
3022 int cnt = (*pCnt & ~WAL_RETRY_BLOCKED_MASK);
3023 if( cnt>WAL_RETRY_PROTOCOL_LIMIT ){
3024 VVA_ONLY( pWal->lockError = 1; )
3025 return SQLITE_PROTOCOL;
3027 if( *pCnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
3028 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3029 /* In SQLITE_ENABLE_SETLK_TIMEOUT builds, configure the file-descriptor
3030 ** to block for locks for approximately nDelay us. This affects three
3031 ** locks: (a) the shared lock taken on the DMS slot in os_unix.c (if
3032 ** using os_unix.c), (b) the WRITER lock taken in walIndexReadHdr() if the
3033 ** first attempted read fails, and (c) the shared lock taken on the
3034 ** read-mark.
3036 ** If the previous call failed due to an SQLITE_BUSY_TIMEOUT error,
3037 ** then sleep for the minimum of 1us. The previous call already provided
3038 ** an extra delay while it was blocking on the lock.
3040 nBlockTmout = (nDelay+998) / 1000;
3041 if( !useWal && walEnableBlockingMs(pWal, nBlockTmout) ){
3042 if( *pCnt & WAL_RETRY_BLOCKED_MASK ) nDelay = 1;
3044 #endif
3045 sqlite3OsSleep(pWal->pVfs, nDelay);
3046 *pCnt &= ~WAL_RETRY_BLOCKED_MASK;
3049 if( !useWal ){
3050 assert( rc==SQLITE_OK );
3051 if( pWal->bShmUnreliable==0 ){
3052 rc = walIndexReadHdr(pWal, pChanged);
3054 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3055 walDisableBlocking(pWal);
3056 if( rc==SQLITE_BUSY_TIMEOUT ){
3057 rc = SQLITE_BUSY;
3058 *pCnt |= WAL_RETRY_BLOCKED_MASK;
3060 #endif
3061 if( rc==SQLITE_BUSY ){
3062 /* If there is not a recovery running in another thread or process
3063 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
3064 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
3065 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
3066 ** would be technically correct. But the race is benign since with
3067 ** WAL_RETRY this routine will be called again and will probably be
3068 ** right on the second iteration.
3070 if( pWal->apWiData[0]==0 ){
3071 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
3072 ** We assume this is a transient condition, so return WAL_RETRY. The
3073 ** xShmMap() implementation used by the default unix and win32 VFS
3074 ** modules may return SQLITE_BUSY due to a race condition in the
3075 ** code that determines whether or not the shared-memory region
3076 ** must be zeroed before the requested page is returned.
3078 rc = WAL_RETRY;
3079 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
3080 walUnlockShared(pWal, WAL_RECOVER_LOCK);
3081 rc = WAL_RETRY;
3082 }else if( rc==SQLITE_BUSY ){
3083 rc = SQLITE_BUSY_RECOVERY;
3086 if( rc!=SQLITE_OK ){
3087 return rc;
3089 else if( pWal->bShmUnreliable ){
3090 return walBeginShmUnreliable(pWal, pChanged);
3094 assert( pWal->nWiData>0 );
3095 assert( pWal->apWiData[0]!=0 );
3096 pInfo = walCkptInfo(pWal);
3097 SEH_INJECT_FAULT;
3098 if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
3099 #ifdef SQLITE_ENABLE_SNAPSHOT
3100 && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
3101 #endif
3103 /* The WAL has been completely backfilled (or it is empty).
3104 ** and can be safely ignored.
3106 rc = walLockShared(pWal, WAL_READ_LOCK(0));
3107 walShmBarrier(pWal);
3108 if( rc==SQLITE_OK ){
3109 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
3110 /* It is not safe to allow the reader to continue here if frames
3111 ** may have been appended to the log before READ_LOCK(0) was obtained.
3112 ** When holding READ_LOCK(0), the reader ignores the entire log file,
3113 ** which implies that the database file contains a trustworthy
3114 ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
3115 ** happening, this is usually correct.
3117 ** However, if frames have been appended to the log (or if the log
3118 ** is wrapped and written for that matter) before the READ_LOCK(0)
3119 ** is obtained, that is not necessarily true. A checkpointer may
3120 ** have started to backfill the appended frames but crashed before
3121 ** it finished. Leaving a corrupt image in the database file.
3123 walUnlockShared(pWal, WAL_READ_LOCK(0));
3124 return WAL_RETRY;
3126 pWal->readLock = 0;
3127 return SQLITE_OK;
3128 }else if( rc!=SQLITE_BUSY ){
3129 return rc;
3133 /* If we get this far, it means that the reader will want to use
3134 ** the WAL to get at content from recent commits. The job now is
3135 ** to select one of the aReadMark[] entries that is closest to
3136 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
3138 mxReadMark = 0;
3139 mxI = 0;
3140 mxFrame = pWal->hdr.mxFrame;
3141 #ifdef SQLITE_ENABLE_SNAPSHOT
3142 if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
3143 mxFrame = pWal->pSnapshot->mxFrame;
3145 #endif
3146 for(i=1; i<WAL_NREADER; i++){
3147 u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
3148 if( mxReadMark<=thisMark && thisMark<=mxFrame ){
3149 assert( thisMark!=READMARK_NOT_USED );
3150 mxReadMark = thisMark;
3151 mxI = i;
3154 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
3155 && (mxReadMark<mxFrame || mxI==0)
3157 for(i=1; i<WAL_NREADER; i++){
3158 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
3159 if( rc==SQLITE_OK ){
3160 AtomicStore(pInfo->aReadMark+i,mxFrame);
3161 mxReadMark = mxFrame;
3162 mxI = i;
3163 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
3164 break;
3165 }else if( rc!=SQLITE_BUSY ){
3166 return rc;
3170 if( mxI==0 ){
3171 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
3172 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
3175 (void)walEnableBlockingMs(pWal, nBlockTmout);
3176 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
3177 walDisableBlocking(pWal);
3178 if( rc ){
3179 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3180 if( rc==SQLITE_BUSY_TIMEOUT ){
3181 *pCnt |= WAL_RETRY_BLOCKED_MASK;
3183 #else
3184 assert( rc!=SQLITE_BUSY_TIMEOUT );
3185 #endif
3186 assert( (rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT );
3187 return (rc&0xFF)==SQLITE_BUSY ? WAL_RETRY : rc;
3189 /* Now that the read-lock has been obtained, check that neither the
3190 ** value in the aReadMark[] array or the contents of the wal-index
3191 ** header have changed.
3193 ** It is necessary to check that the wal-index header did not change
3194 ** between the time it was read and when the shared-lock was obtained
3195 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
3196 ** that the log file may have been wrapped by a writer, or that frames
3197 ** that occur later in the log than pWal->hdr.mxFrame may have been
3198 ** copied into the database by a checkpointer. If either of these things
3199 ** happened, then reading the database with the current value of
3200 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
3201 ** instead.
3203 ** Before checking that the live wal-index header has not changed
3204 ** since it was read, set Wal.minFrame to the first frame in the wal
3205 ** file that has not yet been checkpointed. This client will not need
3206 ** to read any frames earlier than minFrame from the wal file - they
3207 ** can be safely read directly from the database file.
3209 ** Because a ShmBarrier() call is made between taking the copy of
3210 ** nBackfill and checking that the wal-header in shared-memory still
3211 ** matches the one cached in pWal->hdr, it is guaranteed that the
3212 ** checkpointer that set nBackfill was not working with a wal-index
3213 ** header newer than that cached in pWal->hdr. If it were, that could
3214 ** cause a problem. The checkpointer could omit to checkpoint
3215 ** a version of page X that lies before pWal->minFrame (call that version
3216 ** A) on the basis that there is a newer version (version B) of the same
3217 ** page later in the wal file. But if version B happens to like past
3218 ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
3219 ** that it can read version A from the database file. However, since
3220 ** we can guarantee that the checkpointer that set nBackfill could not
3221 ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
3223 pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT;
3224 walShmBarrier(pWal);
3225 if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
3226 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
3228 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
3229 return WAL_RETRY;
3230 }else{
3231 assert( mxReadMark<=pWal->hdr.mxFrame );
3232 pWal->readLock = (i16)mxI;
3234 return rc;
3237 #ifdef SQLITE_ENABLE_SNAPSHOT
3239 ** This function does the work of sqlite3WalSnapshotRecover().
3241 static int walSnapshotRecover(
3242 Wal *pWal, /* WAL handle */
3243 void *pBuf1, /* Temp buffer pWal->szPage bytes in size */
3244 void *pBuf2 /* Temp buffer pWal->szPage bytes in size */
3246 int szPage = (int)pWal->szPage;
3247 int rc;
3248 i64 szDb; /* Size of db file in bytes */
3250 rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
3251 if( rc==SQLITE_OK ){
3252 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
3253 u32 i = pInfo->nBackfillAttempted;
3254 for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
3255 WalHashLoc sLoc; /* Hash table location */
3256 u32 pgno; /* Page number in db file */
3257 i64 iDbOff; /* Offset of db file entry */
3258 i64 iWalOff; /* Offset of wal file entry */
3260 rc = walHashGet(pWal, walFramePage(i), &sLoc);
3261 if( rc!=SQLITE_OK ) break;
3262 assert( i - sLoc.iZero - 1 >=0 );
3263 pgno = sLoc.aPgno[i-sLoc.iZero-1];
3264 iDbOff = (i64)(pgno-1) * szPage;
3266 if( iDbOff+szPage<=szDb ){
3267 iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
3268 rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
3270 if( rc==SQLITE_OK ){
3271 rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
3274 if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
3275 break;
3279 pInfo->nBackfillAttempted = i-1;
3283 return rc;
3287 ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
3288 ** variable so that older snapshots can be accessed. To do this, loop
3289 ** through all wal frames from nBackfillAttempted to (nBackfill+1),
3290 ** comparing their content to the corresponding page with the database
3291 ** file, if any. Set nBackfillAttempted to the frame number of the
3292 ** first frame for which the wal file content matches the db file.
3294 ** This is only really safe if the file-system is such that any page
3295 ** writes made by earlier checkpointers were atomic operations, which
3296 ** is not always true. It is also possible that nBackfillAttempted
3297 ** may be left set to a value larger than expected, if a wal frame
3298 ** contains content that duplicate of an earlier version of the same
3299 ** page.
3301 ** SQLITE_OK is returned if successful, or an SQLite error code if an
3302 ** error occurs. It is not an error if nBackfillAttempted cannot be
3303 ** decreased at all.
3305 int sqlite3WalSnapshotRecover(Wal *pWal){
3306 int rc;
3308 assert( pWal->readLock>=0 );
3309 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
3310 if( rc==SQLITE_OK ){
3311 void *pBuf1 = sqlite3_malloc(pWal->szPage);
3312 void *pBuf2 = sqlite3_malloc(pWal->szPage);
3313 if( pBuf1==0 || pBuf2==0 ){
3314 rc = SQLITE_NOMEM;
3315 }else{
3316 pWal->ckptLock = 1;
3317 SEH_TRY {
3318 rc = walSnapshotRecover(pWal, pBuf1, pBuf2);
3320 SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
3321 pWal->ckptLock = 0;
3324 sqlite3_free(pBuf1);
3325 sqlite3_free(pBuf2);
3326 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
3329 return rc;
3331 #endif /* SQLITE_ENABLE_SNAPSHOT */
3334 ** This function does the work of sqlite3WalBeginReadTransaction() (see
3335 ** below). That function simply calls this one inside an SEH_TRY{...} block.
3337 static int walBeginReadTransaction(Wal *pWal, int *pChanged){
3338 int rc; /* Return code */
3339 int cnt = 0; /* Number of TryBeginRead attempts */
3340 #ifdef SQLITE_ENABLE_SNAPSHOT
3341 int ckptLock = 0;
3342 int bChanged = 0;
3343 WalIndexHdr *pSnapshot = pWal->pSnapshot;
3344 #endif
3346 assert( pWal->ckptLock==0 );
3347 assert( pWal->nSehTry>0 );
3349 #ifdef SQLITE_ENABLE_SNAPSHOT
3350 if( pSnapshot ){
3351 if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
3352 bChanged = 1;
3355 /* It is possible that there is a checkpointer thread running
3356 ** concurrent with this code. If this is the case, it may be that the
3357 ** checkpointer has already determined that it will checkpoint
3358 ** snapshot X, where X is later in the wal file than pSnapshot, but
3359 ** has not yet set the pInfo->nBackfillAttempted variable to indicate
3360 ** its intent. To avoid the race condition this leads to, ensure that
3361 ** there is no checkpointer process by taking a shared CKPT lock
3362 ** before checking pInfo->nBackfillAttempted. */
3363 (void)walEnableBlocking(pWal);
3364 rc = walLockShared(pWal, WAL_CKPT_LOCK);
3365 walDisableBlocking(pWal);
3367 if( rc!=SQLITE_OK ){
3368 return rc;
3370 ckptLock = 1;
3372 #endif
3375 rc = walTryBeginRead(pWal, pChanged, 0, &cnt);
3376 }while( rc==WAL_RETRY );
3377 testcase( (rc&0xff)==SQLITE_BUSY );
3378 testcase( (rc&0xff)==SQLITE_IOERR );
3379 testcase( rc==SQLITE_PROTOCOL );
3380 testcase( rc==SQLITE_OK );
3382 #ifdef SQLITE_ENABLE_SNAPSHOT
3383 if( rc==SQLITE_OK ){
3384 if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
3385 /* At this point the client has a lock on an aReadMark[] slot holding
3386 ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
3387 ** is populated with the wal-index header corresponding to the head
3388 ** of the wal file. Verify that pSnapshot is still valid before
3389 ** continuing. Reasons why pSnapshot might no longer be valid:
3391 ** (1) The WAL file has been reset since the snapshot was taken.
3392 ** In this case, the salt will have changed.
3394 ** (2) A checkpoint as been attempted that wrote frames past
3395 ** pSnapshot->mxFrame into the database file. Note that the
3396 ** checkpoint need not have completed for this to cause problems.
3398 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
3400 assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
3401 assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
3403 /* Check that the wal file has not been wrapped. Assuming that it has
3404 ** not, also check that no checkpointer has attempted to checkpoint any
3405 ** frames beyond pSnapshot->mxFrame. If either of these conditions are
3406 ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
3407 ** with *pSnapshot and set *pChanged as appropriate for opening the
3408 ** snapshot. */
3409 if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
3410 && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
3412 assert( pWal->readLock>0 );
3413 memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
3414 *pChanged = bChanged;
3415 }else{
3416 rc = SQLITE_ERROR_SNAPSHOT;
3419 /* A client using a non-current snapshot may not ignore any frames
3420 ** from the start of the wal file. This is because, for a system
3421 ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
3422 ** have omitted to checkpoint a frame earlier than minFrame in
3423 ** the file because there exists a frame after iSnapshot that
3424 ** is the same database page. */
3425 pWal->minFrame = 1;
3427 if( rc!=SQLITE_OK ){
3428 sqlite3WalEndReadTransaction(pWal);
3433 /* Release the shared CKPT lock obtained above. */
3434 if( ckptLock ){
3435 assert( pSnapshot );
3436 walUnlockShared(pWal, WAL_CKPT_LOCK);
3438 #endif
3439 return rc;
3443 ** Begin a read transaction on the database.
3445 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
3446 ** it takes a snapshot of the state of the WAL and wal-index for the current
3447 ** instant in time. The current thread will continue to use this snapshot.
3448 ** Other threads might append new content to the WAL and wal-index but
3449 ** that extra content is ignored by the current thread.
3451 ** If the database contents have changes since the previous read
3452 ** transaction, then *pChanged is set to 1 before returning. The
3453 ** Pager layer will use this to know that its cache is stale and
3454 ** needs to be flushed.
3456 int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
3457 int rc;
3458 SEH_TRY {
3459 rc = walBeginReadTransaction(pWal, pChanged);
3461 SEH_EXCEPT( rc = walHandleException(pWal); )
3462 return rc;
3466 ** Finish with a read transaction. All this does is release the
3467 ** read-lock.
3469 void sqlite3WalEndReadTransaction(Wal *pWal){
3470 sqlite3WalEndWriteTransaction(pWal);
3471 if( pWal->readLock>=0 ){
3472 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
3473 pWal->readLock = -1;
3478 ** Search the wal file for page pgno. If found, set *piRead to the frame that
3479 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
3480 ** to zero.
3482 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
3483 ** error does occur, the final value of *piRead is undefined.
3485 static int walFindFrame(
3486 Wal *pWal, /* WAL handle */
3487 Pgno pgno, /* Database page number to read data for */
3488 u32 *piRead /* OUT: Frame number (or zero) */
3490 u32 iRead = 0; /* If !=0, WAL frame to return data from */
3491 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
3492 int iHash; /* Used to loop through N hash tables */
3493 int iMinHash;
3495 /* This routine is only be called from within a read transaction. */
3496 assert( pWal->readLock>=0 || pWal->lockError );
3498 /* If the "last page" field of the wal-index header snapshot is 0, then
3499 ** no data will be read from the wal under any circumstances. Return early
3500 ** in this case as an optimization. Likewise, if pWal->readLock==0,
3501 ** then the WAL is ignored by the reader so return early, as if the
3502 ** WAL were empty.
3504 if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
3505 *piRead = 0;
3506 return SQLITE_OK;
3509 /* Search the hash table or tables for an entry matching page number
3510 ** pgno. Each iteration of the following for() loop searches one
3511 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
3513 ** This code might run concurrently to the code in walIndexAppend()
3514 ** that adds entries to the wal-index (and possibly to this hash
3515 ** table). This means the value just read from the hash
3516 ** slot (aHash[iKey]) may have been added before or after the
3517 ** current read transaction was opened. Values added after the
3518 ** read transaction was opened may have been written incorrectly -
3519 ** i.e. these slots may contain garbage data. However, we assume
3520 ** that any slots written before the current read transaction was
3521 ** opened remain unmodified.
3523 ** For the reasons above, the if(...) condition featured in the inner
3524 ** loop of the following block is more stringent that would be required
3525 ** if we had exclusive access to the hash-table:
3527 ** (aPgno[iFrame]==pgno):
3528 ** This condition filters out normal hash-table collisions.
3530 ** (iFrame<=iLast):
3531 ** This condition filters out entries that were added to the hash
3532 ** table after the current read-transaction had started.
3534 iMinHash = walFramePage(pWal->minFrame);
3535 for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
3536 WalHashLoc sLoc; /* Hash table location */
3537 int iKey; /* Hash slot index */
3538 int nCollide; /* Number of hash collisions remaining */
3539 int rc; /* Error code */
3540 u32 iH;
3542 rc = walHashGet(pWal, iHash, &sLoc);
3543 if( rc!=SQLITE_OK ){
3544 return rc;
3546 nCollide = HASHTABLE_NSLOT;
3547 iKey = walHash(pgno);
3548 SEH_INJECT_FAULT;
3549 while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
3550 u32 iFrame = iH + sLoc.iZero;
3551 if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
3552 assert( iFrame>iRead || CORRUPT_DB );
3553 iRead = iFrame;
3555 if( (nCollide--)==0 ){
3556 *piRead = 0;
3557 return SQLITE_CORRUPT_BKPT;
3559 iKey = walNextHash(iKey);
3561 if( iRead ) break;
3564 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
3565 /* If expensive assert() statements are available, do a linear search
3566 ** of the wal-index file content. Make sure the results agree with the
3567 ** result obtained using the hash indexes above. */
3569 u32 iRead2 = 0;
3570 u32 iTest;
3571 assert( pWal->bShmUnreliable || pWal->minFrame>0 );
3572 for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
3573 if( walFramePgno(pWal, iTest)==pgno ){
3574 iRead2 = iTest;
3575 break;
3578 assert( iRead==iRead2 );
3580 #endif
3582 *piRead = iRead;
3583 return SQLITE_OK;
3587 ** Search the wal file for page pgno. If found, set *piRead to the frame that
3588 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
3589 ** to zero.
3591 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
3592 ** error does occur, the final value of *piRead is undefined.
3594 ** The difference between this function and walFindFrame() is that this
3595 ** function wraps walFindFrame() in an SEH_TRY{...} block.
3597 int sqlite3WalFindFrame(
3598 Wal *pWal, /* WAL handle */
3599 Pgno pgno, /* Database page number to read data for */
3600 u32 *piRead /* OUT: Frame number (or zero) */
3602 int rc;
3603 SEH_TRY {
3604 rc = walFindFrame(pWal, pgno, piRead);
3606 SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
3607 return rc;
3611 ** Read the contents of frame iRead from the wal file into buffer pOut
3612 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
3613 ** error code otherwise.
3615 int sqlite3WalReadFrame(
3616 Wal *pWal, /* WAL handle */
3617 u32 iRead, /* Frame to read */
3618 int nOut, /* Size of buffer pOut in bytes */
3619 u8 *pOut /* Buffer to write page data to */
3621 int sz;
3622 i64 iOffset;
3623 sz = pWal->hdr.szPage;
3624 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
3625 testcase( sz<=32768 );
3626 testcase( sz>=65536 );
3627 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
3628 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
3629 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
3633 ** Return the size of the database in pages (or zero, if unknown).
3635 Pgno sqlite3WalDbsize(Wal *pWal){
3636 if( pWal && ALWAYS(pWal->readLock>=0) ){
3637 return pWal->hdr.nPage;
3639 return 0;
3644 ** This function starts a write transaction on the WAL.
3646 ** A read transaction must have already been started by a prior call
3647 ** to sqlite3WalBeginReadTransaction().
3649 ** If another thread or process has written into the database since
3650 ** the read transaction was started, then it is not possible for this
3651 ** thread to write as doing so would cause a fork. So this routine
3652 ** returns SQLITE_BUSY in that case and no write transaction is started.
3654 ** There can only be a single writer active at a time.
3656 int sqlite3WalBeginWriteTransaction(Wal *pWal){
3657 int rc;
3659 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3660 /* If the write-lock is already held, then it was obtained before the
3661 ** read-transaction was even opened, making this call a no-op.
3662 ** Return early. */
3663 if( pWal->writeLock ){
3664 assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
3665 return SQLITE_OK;
3667 #endif
3669 /* Cannot start a write transaction without first holding a read
3670 ** transaction. */
3671 assert( pWal->readLock>=0 );
3672 assert( pWal->writeLock==0 && pWal->iReCksum==0 );
3674 if( pWal->readOnly ){
3675 return SQLITE_READONLY;
3678 /* Only one writer allowed at a time. Get the write lock. Return
3679 ** SQLITE_BUSY if unable.
3681 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
3682 if( rc ){
3683 return rc;
3685 pWal->writeLock = 1;
3687 /* If another connection has written to the database file since the
3688 ** time the read transaction on this connection was started, then
3689 ** the write is disallowed.
3691 SEH_TRY {
3692 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
3693 rc = SQLITE_BUSY_SNAPSHOT;
3696 SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
3698 if( rc!=SQLITE_OK ){
3699 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
3700 pWal->writeLock = 0;
3702 return rc;
3706 ** End a write transaction. The commit has already been done. This
3707 ** routine merely releases the lock.
3709 int sqlite3WalEndWriteTransaction(Wal *pWal){
3710 if( pWal->writeLock ){
3711 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
3712 pWal->writeLock = 0;
3713 pWal->iReCksum = 0;
3714 pWal->truncateOnCommit = 0;
3716 return SQLITE_OK;
3720 ** If any data has been written (but not committed) to the log file, this
3721 ** function moves the write-pointer back to the start of the transaction.
3723 ** Additionally, the callback function is invoked for each frame written
3724 ** to the WAL since the start of the transaction. If the callback returns
3725 ** other than SQLITE_OK, it is not invoked again and the error code is
3726 ** returned to the caller.
3728 ** Otherwise, if the callback function does not return an error, this
3729 ** function returns SQLITE_OK.
3731 int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
3732 int rc = SQLITE_OK;
3733 if( ALWAYS(pWal->writeLock) ){
3734 Pgno iMax = pWal->hdr.mxFrame;
3735 Pgno iFrame;
3737 SEH_TRY {
3738 /* Restore the clients cache of the wal-index header to the state it
3739 ** was in before the client began writing to the database.
3741 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
3743 for(iFrame=pWal->hdr.mxFrame+1;
3744 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
3745 iFrame++
3747 /* This call cannot fail. Unless the page for which the page number
3748 ** is passed as the second argument is (a) in the cache and
3749 ** (b) has an outstanding reference, then xUndo is either a no-op
3750 ** (if (a) is false) or simply expels the page from the cache (if (b)
3751 ** is false).
3753 ** If the upper layer is doing a rollback, it is guaranteed that there
3754 ** are no outstanding references to any page other than page 1. And
3755 ** page 1 is never written to the log until the transaction is
3756 ** committed. As a result, the call to xUndo may not fail.
3758 assert( walFramePgno(pWal, iFrame)!=1 );
3759 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
3761 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
3763 SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
3765 return rc;
3769 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
3770 ** values. This function populates the array with values required to
3771 ** "rollback" the write position of the WAL handle back to the current
3772 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
3774 void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
3775 assert( pWal->writeLock );
3776 aWalData[0] = pWal->hdr.mxFrame;
3777 aWalData[1] = pWal->hdr.aFrameCksum[0];
3778 aWalData[2] = pWal->hdr.aFrameCksum[1];
3779 aWalData[3] = pWal->nCkpt;
3783 ** Move the write position of the WAL back to the point identified by
3784 ** the values in the aWalData[] array. aWalData must point to an array
3785 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
3786 ** by a call to WalSavepoint().
3788 int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
3789 int rc = SQLITE_OK;
3791 assert( pWal->writeLock );
3792 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
3794 if( aWalData[3]!=pWal->nCkpt ){
3795 /* This savepoint was opened immediately after the write-transaction
3796 ** was started. Right after that, the writer decided to wrap around
3797 ** to the start of the log. Update the savepoint values to match.
3799 aWalData[0] = 0;
3800 aWalData[3] = pWal->nCkpt;
3803 if( aWalData[0]<pWal->hdr.mxFrame ){
3804 pWal->hdr.mxFrame = aWalData[0];
3805 pWal->hdr.aFrameCksum[0] = aWalData[1];
3806 pWal->hdr.aFrameCksum[1] = aWalData[2];
3807 SEH_TRY {
3808 walCleanupHash(pWal);
3810 SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
3813 return rc;
3817 ** This function is called just before writing a set of frames to the log
3818 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
3819 ** to the current log file, it is possible to overwrite the start of the
3820 ** existing log file with the new frames (i.e. "reset" the log). If so,
3821 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
3822 ** unchanged.
3824 ** SQLITE_OK is returned if no error is encountered (regardless of whether
3825 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
3826 ** if an error occurs.
3828 static int walRestartLog(Wal *pWal){
3829 int rc = SQLITE_OK;
3830 int cnt;
3832 if( pWal->readLock==0 ){
3833 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
3834 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
3835 if( pInfo->nBackfill>0 ){
3836 u32 salt1;
3837 sqlite3_randomness(4, &salt1);
3838 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
3839 if( rc==SQLITE_OK ){
3840 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
3841 ** readers are currently using the WAL), then the transactions
3842 ** frames will overwrite the start of the existing log. Update the
3843 ** wal-index header to reflect this.
3845 ** In theory it would be Ok to update the cache of the header only
3846 ** at this point. But updating the actual wal-index header is also
3847 ** safe and means there is no special case for sqlite3WalUndo()
3848 ** to handle if this transaction is rolled back. */
3849 walRestartHdr(pWal, salt1);
3850 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
3851 }else if( rc!=SQLITE_BUSY ){
3852 return rc;
3855 walUnlockShared(pWal, WAL_READ_LOCK(0));
3856 pWal->readLock = -1;
3857 cnt = 0;
3859 int notUsed;
3860 rc = walTryBeginRead(pWal, &notUsed, 1, &cnt);
3861 }while( rc==WAL_RETRY );
3862 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
3863 testcase( (rc&0xff)==SQLITE_IOERR );
3864 testcase( rc==SQLITE_PROTOCOL );
3865 testcase( rc==SQLITE_OK );
3867 return rc;
3871 ** Information about the current state of the WAL file and where
3872 ** the next fsync should occur - passed from sqlite3WalFrames() into
3873 ** walWriteToLog().
3875 typedef struct WalWriter {
3876 Wal *pWal; /* The complete WAL information */
3877 sqlite3_file *pFd; /* The WAL file to which we write */
3878 sqlite3_int64 iSyncPoint; /* Fsync at this offset */
3879 int syncFlags; /* Flags for the fsync */
3880 int szPage; /* Size of one page */
3881 } WalWriter;
3884 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
3885 ** Do a sync when crossing the p->iSyncPoint boundary.
3887 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
3888 ** first write the part before iSyncPoint, then sync, then write the
3889 ** rest.
3891 static int walWriteToLog(
3892 WalWriter *p, /* WAL to write to */
3893 void *pContent, /* Content to be written */
3894 int iAmt, /* Number of bytes to write */
3895 sqlite3_int64 iOffset /* Start writing at this offset */
3897 int rc;
3898 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
3899 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
3900 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
3901 if( rc ) return rc;
3902 iOffset += iFirstAmt;
3903 iAmt -= iFirstAmt;
3904 pContent = (void*)(iFirstAmt + (char*)pContent);
3905 assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
3906 rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
3907 if( iAmt==0 || rc ) return rc;
3909 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
3910 return rc;
3914 ** Write out a single frame of the WAL
3916 static int walWriteOneFrame(
3917 WalWriter *p, /* Where to write the frame */
3918 PgHdr *pPage, /* The page of the frame to be written */
3919 int nTruncate, /* The commit flag. Usually 0. >0 for commit */
3920 sqlite3_int64 iOffset /* Byte offset at which to write */
3922 int rc; /* Result code from subfunctions */
3923 void *pData; /* Data actually written */
3924 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
3925 pData = pPage->pData;
3926 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
3927 rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
3928 if( rc ) return rc;
3929 /* Write the page data */
3930 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
3931 return rc;
3935 ** This function is called as part of committing a transaction within which
3936 ** one or more frames have been overwritten. It updates the checksums for
3937 ** all frames written to the wal file by the current transaction starting
3938 ** with the earliest to have been overwritten.
3940 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
3942 static int walRewriteChecksums(Wal *pWal, u32 iLast){
3943 const int szPage = pWal->szPage;/* Database page size */
3944 int rc = SQLITE_OK; /* Return code */
3945 u8 *aBuf; /* Buffer to load data from wal file into */
3946 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
3947 u32 iRead; /* Next frame to read from wal file */
3948 i64 iCksumOff;
3950 aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
3951 if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
3953 /* Find the checksum values to use as input for the recalculating the
3954 ** first checksum. If the first frame is frame 1 (implying that the current
3955 ** transaction restarted the wal file), these values must be read from the
3956 ** wal-file header. Otherwise, read them from the frame header of the
3957 ** previous frame. */
3958 assert( pWal->iReCksum>0 );
3959 if( pWal->iReCksum==1 ){
3960 iCksumOff = 24;
3961 }else{
3962 iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
3964 rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
3965 pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
3966 pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
3968 iRead = pWal->iReCksum;
3969 pWal->iReCksum = 0;
3970 for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
3971 i64 iOff = walFrameOffset(iRead, szPage);
3972 rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
3973 if( rc==SQLITE_OK ){
3974 u32 iPgno, nDbSize;
3975 iPgno = sqlite3Get4byte(aBuf);
3976 nDbSize = sqlite3Get4byte(&aBuf[4]);
3978 walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
3979 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
3983 sqlite3_free(aBuf);
3984 return rc;
3988 ** Write a set of frames to the log. The caller must hold the write-lock
3989 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
3991 static int walFrames(
3992 Wal *pWal, /* Wal handle to write to */
3993 int szPage, /* Database page-size in bytes */
3994 PgHdr *pList, /* List of dirty pages to write */
3995 Pgno nTruncate, /* Database size after this commit */
3996 int isCommit, /* True if this is a commit */
3997 int sync_flags /* Flags to pass to OsSync() (or 0) */
3999 int rc; /* Used to catch return codes */
4000 u32 iFrame; /* Next frame address */
4001 PgHdr *p; /* Iterator to run through pList with. */
4002 PgHdr *pLast = 0; /* Last frame in list */
4003 int nExtra = 0; /* Number of extra copies of last page */
4004 int szFrame; /* The size of a single frame */
4005 i64 iOffset; /* Next byte to write in WAL file */
4006 WalWriter w; /* The writer */
4007 u32 iFirst = 0; /* First frame that may be overwritten */
4008 WalIndexHdr *pLive; /* Pointer to shared header */
4010 assert( pList );
4011 assert( pWal->writeLock );
4013 /* If this frame set completes a transaction, then nTruncate>0. If
4014 ** nTruncate==0 then this frame set does not complete the transaction. */
4015 assert( (isCommit!=0)==(nTruncate!=0) );
4017 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
4018 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
4019 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
4020 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
4022 #endif
4024 pLive = (WalIndexHdr*)walIndexHdr(pWal);
4025 if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
4026 iFirst = pLive->mxFrame+1;
4029 /* See if it is possible to write these frames into the start of the
4030 ** log file, instead of appending to it at pWal->hdr.mxFrame.
4032 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
4033 return rc;
4036 /* If this is the first frame written into the log, write the WAL
4037 ** header to the start of the WAL file. See comments at the top of
4038 ** this source file for a description of the WAL header format.
4040 iFrame = pWal->hdr.mxFrame;
4041 if( iFrame==0 ){
4042 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
4043 u32 aCksum[2]; /* Checksum for wal-header */
4045 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
4046 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
4047 sqlite3Put4byte(&aWalHdr[8], szPage);
4048 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
4049 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
4050 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
4051 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
4052 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
4053 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
4055 pWal->szPage = szPage;
4056 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
4057 pWal->hdr.aFrameCksum[0] = aCksum[0];
4058 pWal->hdr.aFrameCksum[1] = aCksum[1];
4059 pWal->truncateOnCommit = 1;
4061 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
4062 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
4063 if( rc!=SQLITE_OK ){
4064 return rc;
4067 /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
4068 ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
4069 ** an out-of-order write following a WAL restart could result in
4070 ** database corruption. See the ticket:
4072 ** https://sqlite.org/src/info/ff5be73dee
4074 if( pWal->syncHeader ){
4075 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
4076 if( rc ) return rc;
4079 if( (int)pWal->szPage!=szPage ){
4080 return SQLITE_CORRUPT_BKPT; /* TH3 test case: cov1/corrupt155.test */
4083 /* Setup information needed to write frames into the WAL */
4084 w.pWal = pWal;
4085 w.pFd = pWal->pWalFd;
4086 w.iSyncPoint = 0;
4087 w.syncFlags = sync_flags;
4088 w.szPage = szPage;
4089 iOffset = walFrameOffset(iFrame+1, szPage);
4090 szFrame = szPage + WAL_FRAME_HDRSIZE;
4092 /* Write all frames into the log file exactly once */
4093 for(p=pList; p; p=p->pDirty){
4094 int nDbSize; /* 0 normally. Positive == commit flag */
4096 /* Check if this page has already been written into the wal file by
4097 ** the current transaction. If so, overwrite the existing frame and
4098 ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
4099 ** checksums must be recomputed when the transaction is committed. */
4100 if( iFirst && (p->pDirty || isCommit==0) ){
4101 u32 iWrite = 0;
4102 VVA_ONLY(rc =) walFindFrame(pWal, p->pgno, &iWrite);
4103 assert( rc==SQLITE_OK || iWrite==0 );
4104 if( iWrite>=iFirst ){
4105 i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
4106 void *pData;
4107 if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
4108 pWal->iReCksum = iWrite;
4110 pData = p->pData;
4111 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
4112 if( rc ) return rc;
4113 p->flags &= ~PGHDR_WAL_APPEND;
4114 continue;
4118 iFrame++;
4119 assert( iOffset==walFrameOffset(iFrame, szPage) );
4120 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
4121 rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
4122 if( rc ) return rc;
4123 pLast = p;
4124 iOffset += szFrame;
4125 p->flags |= PGHDR_WAL_APPEND;
4128 /* Recalculate checksums within the wal file if required. */
4129 if( isCommit && pWal->iReCksum ){
4130 rc = walRewriteChecksums(pWal, iFrame);
4131 if( rc ) return rc;
4134 /* If this is the end of a transaction, then we might need to pad
4135 ** the transaction and/or sync the WAL file.
4137 ** Padding and syncing only occur if this set of frames complete a
4138 ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
4139 ** or synchronous==OFF, then no padding or syncing are needed.
4141 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
4142 ** needed and only the sync is done. If padding is needed, then the
4143 ** final frame is repeated (with its commit mark) until the next sector
4144 ** boundary is crossed. Only the part of the WAL prior to the last
4145 ** sector boundary is synced; the part of the last frame that extends
4146 ** past the sector boundary is written after the sync.
4148 if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
4149 int bSync = 1;
4150 if( pWal->padToSectorBoundary ){
4151 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
4152 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
4153 bSync = (w.iSyncPoint==iOffset);
4154 testcase( bSync );
4155 while( iOffset<w.iSyncPoint ){
4156 rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
4157 if( rc ) return rc;
4158 iOffset += szFrame;
4159 nExtra++;
4160 assert( pLast!=0 );
4163 if( bSync ){
4164 assert( rc==SQLITE_OK );
4165 rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
4169 /* If this frame set completes the first transaction in the WAL and
4170 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
4171 ** journal size limit, if possible.
4173 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
4174 i64 sz = pWal->mxWalSize;
4175 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
4176 sz = walFrameOffset(iFrame+nExtra+1, szPage);
4178 walLimitSize(pWal, sz);
4179 pWal->truncateOnCommit = 0;
4182 /* Append data to the wal-index. It is not necessary to lock the
4183 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
4184 ** guarantees that there are no other writers, and no data that may
4185 ** be in use by existing readers is being overwritten.
4187 iFrame = pWal->hdr.mxFrame;
4188 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
4189 if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
4190 iFrame++;
4191 rc = walIndexAppend(pWal, iFrame, p->pgno);
4193 assert( pLast!=0 || nExtra==0 );
4194 while( rc==SQLITE_OK && nExtra>0 ){
4195 iFrame++;
4196 nExtra--;
4197 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
4200 if( rc==SQLITE_OK ){
4201 /* Update the private copy of the header. */
4202 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
4203 testcase( szPage<=32768 );
4204 testcase( szPage>=65536 );
4205 pWal->hdr.mxFrame = iFrame;
4206 if( isCommit ){
4207 pWal->hdr.iChange++;
4208 pWal->hdr.nPage = nTruncate;
4210 /* If this is a commit, update the wal-index header too. */
4211 if( isCommit ){
4212 walIndexWriteHdr(pWal);
4213 pWal->iCallback = iFrame;
4217 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
4218 return rc;
4222 ** Write a set of frames to the log. The caller must hold the write-lock
4223 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
4225 ** The difference between this function and walFrames() is that this
4226 ** function wraps walFrames() in an SEH_TRY{...} block.
4228 int sqlite3WalFrames(
4229 Wal *pWal, /* Wal handle to write to */
4230 int szPage, /* Database page-size in bytes */
4231 PgHdr *pList, /* List of dirty pages to write */
4232 Pgno nTruncate, /* Database size after this commit */
4233 int isCommit, /* True if this is a commit */
4234 int sync_flags /* Flags to pass to OsSync() (or 0) */
4236 int rc;
4237 SEH_TRY {
4238 rc = walFrames(pWal, szPage, pList, nTruncate, isCommit, sync_flags);
4240 SEH_EXCEPT( rc = walHandleException(pWal); )
4241 return rc;
4245 ** This routine is called to implement sqlite3_wal_checkpoint() and
4246 ** related interfaces.
4248 ** Obtain a CHECKPOINT lock and then backfill as much information as
4249 ** we can from WAL into the database.
4251 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
4252 ** callback. In this case this function runs a blocking checkpoint.
4254 int sqlite3WalCheckpoint(
4255 Wal *pWal, /* Wal connection */
4256 sqlite3 *db, /* Check this handle's interrupt flag */
4257 int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
4258 int (*xBusy)(void*), /* Function to call when busy */
4259 void *pBusyArg, /* Context argument for xBusyHandler */
4260 int sync_flags, /* Flags to sync db file with (or 0) */
4261 int nBuf, /* Size of temporary buffer */
4262 u8 *zBuf, /* Temporary buffer to use */
4263 int *pnLog, /* OUT: Number of frames in WAL */
4264 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
4266 int rc; /* Return code */
4267 int isChanged = 0; /* True if a new wal-index header is loaded */
4268 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
4269 int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
4271 assert( pWal->ckptLock==0 );
4272 assert( pWal->writeLock==0 );
4274 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
4275 ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
4276 assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
4278 if( pWal->readOnly ) return SQLITE_READONLY;
4279 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
4281 /* Enable blocking locks, if possible. */
4282 sqlite3WalDb(pWal, db);
4283 if( xBusy2 ) (void)walEnableBlocking(pWal);
4285 /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
4286 ** "checkpoint" lock on the database file.
4287 ** EVIDENCE-OF: R-10421-19736 If any other process is running a
4288 ** checkpoint operation at the same time, the lock cannot be obtained and
4289 ** SQLITE_BUSY is returned.
4290 ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
4291 ** it will not be invoked in this case.
4293 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
4294 testcase( rc==SQLITE_BUSY );
4295 testcase( rc!=SQLITE_OK && xBusy2!=0 );
4296 if( rc==SQLITE_OK ){
4297 pWal->ckptLock = 1;
4299 /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
4300 ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
4301 ** file.
4303 ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
4304 ** immediately, and a busy-handler is configured, it is invoked and the
4305 ** writer lock retried until either the busy-handler returns 0 or the
4306 ** lock is successfully obtained.
4308 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
4309 rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
4310 if( rc==SQLITE_OK ){
4311 pWal->writeLock = 1;
4312 }else if( rc==SQLITE_BUSY ){
4313 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
4314 xBusy2 = 0;
4315 rc = SQLITE_OK;
4321 /* Read the wal-index header. */
4322 SEH_TRY {
4323 if( rc==SQLITE_OK ){
4324 /* For a passive checkpoint, do not re-enable blocking locks after
4325 ** reading the wal-index header. A passive checkpoint should not block
4326 ** or invoke the busy handler. The only lock such a checkpoint may
4327 ** attempt to obtain is a lock on a read-slot, and it should give up
4328 ** immediately and do a partial checkpoint if it cannot obtain it. */
4329 walDisableBlocking(pWal);
4330 rc = walIndexReadHdr(pWal, &isChanged);
4331 if( eMode2!=SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal);
4332 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
4333 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
4337 /* Copy data from the log to the database file. */
4338 if( rc==SQLITE_OK ){
4339 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
4340 rc = SQLITE_CORRUPT_BKPT;
4341 }else{
4342 rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf);
4345 /* If no error occurred, set the output variables. */
4346 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
4347 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
4348 SEH_INJECT_FAULT;
4349 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
4353 SEH_EXCEPT( rc = walHandleException(pWal); )
4355 if( isChanged ){
4356 /* If a new wal-index header was loaded before the checkpoint was
4357 ** performed, then the pager-cache associated with pWal is now
4358 ** out of date. So zero the cached wal-index header to ensure that
4359 ** next time the pager opens a snapshot on this database it knows that
4360 ** the cache needs to be reset.
4362 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
4365 walDisableBlocking(pWal);
4366 sqlite3WalDb(pWal, 0);
4368 /* Release the locks. */
4369 sqlite3WalEndWriteTransaction(pWal);
4370 if( pWal->ckptLock ){
4371 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
4372 pWal->ckptLock = 0;
4374 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
4375 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4376 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
4377 #endif
4378 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
4381 /* Return the value to pass to a sqlite3_wal_hook callback, the
4382 ** number of frames in the WAL at the point of the last commit since
4383 ** sqlite3WalCallback() was called. If no commits have occurred since
4384 ** the last call, then return 0.
4386 int sqlite3WalCallback(Wal *pWal){
4387 u32 ret = 0;
4388 if( pWal ){
4389 ret = pWal->iCallback;
4390 pWal->iCallback = 0;
4392 return (int)ret;
4396 ** This function is called to change the WAL subsystem into or out
4397 ** of locking_mode=EXCLUSIVE.
4399 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
4400 ** into locking_mode=NORMAL. This means that we must acquire a lock
4401 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
4402 ** or if the acquisition of the lock fails, then return 0. If the
4403 ** transition out of exclusive-mode is successful, return 1. This
4404 ** operation must occur while the pager is still holding the exclusive
4405 ** lock on the main database file.
4407 ** If op is one, then change from locking_mode=NORMAL into
4408 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
4409 ** be released. Return 1 if the transition is made and 0 if the
4410 ** WAL is already in exclusive-locking mode - meaning that this
4411 ** routine is a no-op. The pager must already hold the exclusive lock
4412 ** on the main database file before invoking this operation.
4414 ** If op is negative, then do a dry-run of the op==1 case but do
4415 ** not actually change anything. The pager uses this to see if it
4416 ** should acquire the database exclusive lock prior to invoking
4417 ** the op==1 case.
4419 int sqlite3WalExclusiveMode(Wal *pWal, int op){
4420 int rc;
4421 assert( pWal->writeLock==0 );
4422 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
4424 /* pWal->readLock is usually set, but might be -1 if there was a
4425 ** prior error while attempting to acquire are read-lock. This cannot
4426 ** happen if the connection is actually in exclusive mode (as no xShmLock
4427 ** locks are taken in this case). Nor should the pager attempt to
4428 ** upgrade to exclusive-mode following such an error.
4430 #ifndef SQLITE_USE_SEH
4431 assert( pWal->readLock>=0 || pWal->lockError );
4432 #endif
4433 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
4435 if( op==0 ){
4436 if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
4437 pWal->exclusiveMode = WAL_NORMAL_MODE;
4438 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
4439 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
4441 rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
4442 }else{
4443 /* Already in locking_mode=NORMAL */
4444 rc = 0;
4446 }else if( op>0 ){
4447 assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
4448 assert( pWal->readLock>=0 );
4449 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
4450 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
4451 rc = 1;
4452 }else{
4453 rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
4455 return rc;
4459 ** Return true if the argument is non-NULL and the WAL module is using
4460 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
4461 ** WAL module is using shared-memory, return false.
4463 int sqlite3WalHeapMemory(Wal *pWal){
4464 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
4467 #ifdef SQLITE_ENABLE_SNAPSHOT
4468 /* Create a snapshot object. The content of a snapshot is opaque to
4469 ** every other subsystem, so the WAL module can put whatever it needs
4470 ** in the object.
4472 int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
4473 int rc = SQLITE_OK;
4474 WalIndexHdr *pRet;
4475 static const u32 aZero[4] = { 0, 0, 0, 0 };
4477 assert( pWal->readLock>=0 && pWal->writeLock==0 );
4479 if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
4480 *ppSnapshot = 0;
4481 return SQLITE_ERROR;
4483 pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
4484 if( pRet==0 ){
4485 rc = SQLITE_NOMEM_BKPT;
4486 }else{
4487 memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
4488 *ppSnapshot = (sqlite3_snapshot*)pRet;
4491 return rc;
4494 /* Try to open on pSnapshot when the next read-transaction starts
4496 void sqlite3WalSnapshotOpen(
4497 Wal *pWal,
4498 sqlite3_snapshot *pSnapshot
4500 pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
4504 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
4505 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
4507 int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
4508 WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
4509 WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
4511 /* aSalt[0] is a copy of the value stored in the wal file header. It
4512 ** is incremented each time the wal file is restarted. */
4513 if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
4514 if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
4515 if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
4516 if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
4517 return 0;
4521 ** The caller currently has a read transaction open on the database.
4522 ** This function takes a SHARED lock on the CHECKPOINTER slot and then
4523 ** checks if the snapshot passed as the second argument is still
4524 ** available. If so, SQLITE_OK is returned.
4526 ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
4527 ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
4528 ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
4529 ** lock is released before returning.
4531 int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
4532 int rc;
4533 SEH_TRY {
4534 rc = walLockShared(pWal, WAL_CKPT_LOCK);
4535 if( rc==SQLITE_OK ){
4536 WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
4537 if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
4538 || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
4540 rc = SQLITE_ERROR_SNAPSHOT;
4541 walUnlockShared(pWal, WAL_CKPT_LOCK);
4545 SEH_EXCEPT( rc = walHandleException(pWal); )
4546 return rc;
4550 ** Release a lock obtained by an earlier successful call to
4551 ** sqlite3WalSnapshotCheck().
4553 void sqlite3WalSnapshotUnlock(Wal *pWal){
4554 assert( pWal );
4555 walUnlockShared(pWal, WAL_CKPT_LOCK);
4559 #endif /* SQLITE_ENABLE_SNAPSHOT */
4561 #ifdef SQLITE_ENABLE_ZIPVFS
4563 ** If the argument is not NULL, it points to a Wal object that holds a
4564 ** read-lock. This function returns the database page-size if it is known,
4565 ** or zero if it is not (or if pWal is NULL).
4567 int sqlite3WalFramesize(Wal *pWal){
4568 assert( pWal==0 || pWal->readLock>=0 );
4569 return (pWal ? pWal->szPage : 0);
4571 #endif
4573 /* Return the sqlite3_file object for the WAL file
4575 sqlite3_file *sqlite3WalFile(Wal *pWal){
4576 return pWal->pWalFd;
4579 #endif /* #ifndef SQLITE_OMIT_WAL */