000001  /*
000002  ** 2010 February 1
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  **
000013  ** This file contains the implementation of a write-ahead log (WAL) used in
000014  ** "journal_mode=WAL" mode.
000015  **
000016  ** WRITE-AHEAD LOG (WAL) FILE FORMAT
000017  **
000018  ** A WAL file consists of a header followed by zero or more "frames".
000019  ** Each frame records the revised content of a single page from the
000020  ** database file.  All changes to the database are recorded by writing
000021  ** frames into the WAL.  Transactions commit when a frame is written that
000022  ** contains a commit marker.  A single WAL can and usually does record
000023  ** multiple transactions.  Periodically, the content of the WAL is
000024  ** transferred back into the database file in an operation called a
000025  ** "checkpoint".
000026  **
000027  ** A single WAL file can be used multiple times.  In other words, the
000028  ** WAL can fill up with frames and then be checkpointed and then new
000029  ** frames can overwrite the old ones.  A WAL always grows from beginning
000030  ** toward the end.  Checksums and counters attached to each frame are
000031  ** used to determine which frames within the WAL are valid and which
000032  ** are leftovers from prior checkpoints.
000033  **
000034  ** The WAL header is 32 bytes in size and consists of the following eight
000035  ** big-endian 32-bit unsigned integer values:
000036  **
000037  **     0: Magic number.  0x377f0682 or 0x377f0683
000038  **     4: File format version.  Currently 3007000
000039  **     8: Database page size.  Example: 1024
000040  **    12: Checkpoint sequence number
000041  **    16: Salt-1, random integer incremented with each checkpoint
000042  **    20: Salt-2, a different random integer changing with each ckpt
000043  **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
000044  **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
000045  **
000046  ** Immediately following the wal-header are zero or more frames. Each
000047  ** frame consists of a 24-byte frame-header followed by <page-size> bytes
000048  ** of page data. The frame-header is six big-endian 32-bit unsigned
000049  ** integer values, as follows:
000050  **
000051  **     0: Page number.
000052  **     4: For commit records, the size of the database image in pages
000053  **        after the commit. For all other records, zero.
000054  **     8: Salt-1 (copied from the header)
000055  **    12: Salt-2 (copied from the header)
000056  **    16: Checksum-1.
000057  **    20: Checksum-2.
000058  **
000059  ** A frame is considered valid if and only if the following conditions are
000060  ** true:
000061  **
000062  **    (1) The salt-1 and salt-2 values in the frame-header match
000063  **        salt values in the wal-header
000064  **
000065  **    (2) The checksum values in the final 8 bytes of the frame-header
000066  **        exactly match the checksum computed consecutively on the
000067  **        WAL header and the first 8 bytes and the content of all frames
000068  **        up to and including the current frame.
000069  **
000070  ** The checksum is computed using 32-bit big-endian integers if the
000071  ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
000072  ** is computed using little-endian if the magic number is 0x377f0682.
000073  ** The checksum values are always stored in the frame header in a
000074  ** big-endian format regardless of which byte order is used to compute
000075  ** the checksum.  The checksum is computed by interpreting the input as
000076  ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
000077  ** algorithm used for the checksum is as follows:
000078  **
000079  **   for i from 0 to n-1 step 2:
000080  **     s0 += x[i] + s1;
000081  **     s1 += x[i+1] + s0;
000082  **   endfor
000083  **
000084  ** Note that s0 and s1 are both weighted checksums using fibonacci weights
000085  ** in reverse order (the largest fibonacci weight occurs on the first element
000086  ** of the sequence being summed.)  The s1 value spans all 32-bit
000087  ** terms of the sequence whereas s0 omits the final term.
000088  **
000089  ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
000090  ** WAL is transferred into the database, then the database is VFS.xSync-ed.
000091  ** The VFS.xSync operations serve as write barriers - all writes launched
000092  ** before the xSync must complete before any write that launches after the
000093  ** xSync begins.
000094  **
000095  ** After each checkpoint, the salt-1 value is incremented and the salt-2
000096  ** value is randomized.  This prevents old and new frames in the WAL from
000097  ** being considered valid at the same time and being checkpointing together
000098  ** following a crash.
000099  **
000100  ** READER ALGORITHM
000101  **
000102  ** To read a page from the database (call it page number P), a reader
000103  ** first checks the WAL to see if it contains page P.  If so, then the
000104  ** last valid instance of page P that is a followed by a commit frame
000105  ** or is a commit frame itself becomes the value read.  If the WAL
000106  ** contains no copies of page P that are valid and which are a commit
000107  ** frame or are followed by a commit frame, then page P is read from
000108  ** the database file.
000109  **
000110  ** To start a read transaction, the reader records the index of the last
000111  ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
000112  ** for all subsequent read operations.  New transactions can be appended
000113  ** to the WAL, but as long as the reader uses its original mxFrame value
000114  ** and ignores the newly appended content, it will see a consistent snapshot
000115  ** of the database from a single point in time.  This technique allows
000116  ** multiple concurrent readers to view different versions of the database
000117  ** content simultaneously.
000118  **
000119  ** The reader algorithm in the previous paragraphs works correctly, but
000120  ** because frames for page P can appear anywhere within the WAL, the
000121  ** reader has to scan the entire WAL looking for page P frames.  If the
000122  ** WAL is large (multiple megabytes is typical) that scan can be slow,
000123  ** and read performance suffers.  To overcome this problem, a separate
000124  ** data structure called the wal-index is maintained to expedite the
000125  ** search for frames of a particular page.
000126  **
000127  ** WAL-INDEX FORMAT
000128  **
000129  ** Conceptually, the wal-index is shared memory, though VFS implementations
000130  ** might choose to implement the wal-index using a mmapped file.  Because
000131  ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
000132  ** on a network filesystem.  All users of the database must be able to
000133  ** share memory.
000134  **
000135  ** In the default unix and windows implementation, the wal-index is a mmapped
000136  ** file whose name is the database name with a "-shm" suffix added.  For that
000137  ** reason, the wal-index is sometimes called the "shm" file.
000138  **
000139  ** The wal-index is transient.  After a crash, the wal-index can (and should
000140  ** be) reconstructed from the original WAL file.  In fact, the VFS is required
000141  ** to either truncate or zero the header of the wal-index when the last
000142  ** connection to it closes.  Because the wal-index is transient, it can
000143  ** use an architecture-specific format; it does not have to be cross-platform.
000144  ** Hence, unlike the database and WAL file formats which store all values
000145  ** as big endian, the wal-index can store multi-byte values in the native
000146  ** byte order of the host computer.
000147  **
000148  ** The purpose of the wal-index is to answer this question quickly:  Given
000149  ** a page number P and a maximum frame index M, return the index of the
000150  ** last frame in the wal before frame M for page P in the WAL, or return
000151  ** NULL if there are no frames for page P in the WAL prior to M.
000152  **
000153  ** The wal-index consists of a header region, followed by an one or
000154  ** more index blocks.
000155  **
000156  ** The wal-index header contains the total number of frames within the WAL
000157  ** in the mxFrame field.
000158  **
000159  ** Each index block except for the first contains information on
000160  ** HASHTABLE_NPAGE frames. The first index block contains information on
000161  ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
000162  ** HASHTABLE_NPAGE are selected so that together the wal-index header and
000163  ** first index block are the same size as all other index blocks in the
000164  ** wal-index.  The values are:
000165  **
000166  **   HASHTABLE_NPAGE      4096
000167  **   HASHTABLE_NPAGE_ONE  4062
000168  **
000169  ** Each index block contains two sections, a page-mapping that contains the
000170  ** database page number associated with each wal frame, and a hash-table
000171  ** that allows readers to query an index block for a specific page number.
000172  ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
000173  ** for the first index block) 32-bit page numbers. The first entry in the
000174  ** first index-block contains the database page number corresponding to the
000175  ** first frame in the WAL file. The first entry in the second index block
000176  ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
000177  ** the log, and so on.
000178  **
000179  ** The last index block in a wal-index usually contains less than the full
000180  ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
000181  ** depending on the contents of the WAL file. This does not change the
000182  ** allocated size of the page-mapping array - the page-mapping array merely
000183  ** contains unused entries.
000184  **
000185  ** Even without using the hash table, the last frame for page P
000186  ** can be found by scanning the page-mapping sections of each index block
000187  ** starting with the last index block and moving toward the first, and
000188  ** within each index block, starting at the end and moving toward the
000189  ** beginning.  The first entry that equals P corresponds to the frame
000190  ** holding the content for that page.
000191  **
000192  ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
000193  ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
000194  ** hash table for each page number in the mapping section, so the hash
000195  ** table is never more than half full.  The expected number of collisions
000196  ** prior to finding a match is 1.  Each entry of the hash table is an
000197  ** 1-based index of an entry in the mapping section of the same
000198  ** index block.   Let K be the 1-based index of the largest entry in
000199  ** the mapping section.  (For index blocks other than the last, K will
000200  ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
000201  ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
000202  ** contain a value of 0.
000203  **
000204  ** To look for page P in the hash table, first compute a hash iKey on
000205  ** P as follows:
000206  **
000207  **      iKey = (P * 383) % HASHTABLE_NSLOT
000208  **
000209  ** Then start scanning entries of the hash table, starting with iKey
000210  ** (wrapping around to the beginning when the end of the hash table is
000211  ** reached) until an unused hash slot is found. Let the first unused slot
000212  ** be at index iUnused.  (iUnused might be less than iKey if there was
000213  ** wrap-around.) Because the hash table is never more than half full,
000214  ** the search is guaranteed to eventually hit an unused entry.  Let
000215  ** iMax be the value between iKey and iUnused, closest to iUnused,
000216  ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
000217  ** no hash slot such that aHash[i]==p) then page P is not in the
000218  ** current index block.  Otherwise the iMax-th mapping entry of the
000219  ** current index block corresponds to the last entry that references
000220  ** page P.
000221  **
000222  ** A hash search begins with the last index block and moves toward the
000223  ** first index block, looking for entries corresponding to page P.  On
000224  ** average, only two or three slots in each index block need to be
000225  ** examined in order to either find the last entry for page P, or to
000226  ** establish that no such entry exists in the block.  Each index block
000227  ** holds over 4000 entries.  So two or three index blocks are sufficient
000228  ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
000229  ** comparisons (on average) suffice to either locate a frame in the
000230  ** WAL or to establish that the frame does not exist in the WAL.  This
000231  ** is much faster than scanning the entire 10MB WAL.
000232  **
000233  ** Note that entries are added in order of increasing K.  Hence, one
000234  ** reader might be using some value K0 and a second reader that started
000235  ** at a later time (after additional transactions were added to the WAL
000236  ** and to the wal-index) might be using a different value K1, where K1>K0.
000237  ** Both readers can use the same hash table and mapping section to get
000238  ** the correct result.  There may be entries in the hash table with
000239  ** K>K0 but to the first reader, those entries will appear to be unused
000240  ** slots in the hash table and so the first reader will get an answer as
000241  ** if no values greater than K0 had ever been inserted into the hash table
000242  ** in the first place - which is what reader one wants.  Meanwhile, the
000243  ** second reader using K1 will see additional values that were inserted
000244  ** later, which is exactly what reader two wants.
000245  **
000246  ** When a rollback occurs, the value of K is decreased. Hash table entries
000247  ** that correspond to frames greater than the new K value are removed
000248  ** from the hash table at this point.
000249  */
000250  #ifndef SQLITE_OMIT_WAL
000251  
000252  #include "wal.h"
000253  
000254  /*
000255  ** Trace output macros
000256  */
000257  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
000258  int sqlite3WalTrace = 0;
000259  # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
000260  #else
000261  # define WALTRACE(X)
000262  #endif
000263  
000264  /*
000265  ** The maximum (and only) versions of the wal and wal-index formats
000266  ** that may be interpreted by this version of SQLite.
000267  **
000268  ** If a client begins recovering a WAL file and finds that (a) the checksum
000269  ** values in the wal-header are correct and (b) the version field is not
000270  ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
000271  **
000272  ** Similarly, if a client successfully reads a wal-index header (i.e. the
000273  ** checksum test is successful) and finds that the version field is not
000274  ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
000275  ** returns SQLITE_CANTOPEN.
000276  */
000277  #define WAL_MAX_VERSION      3007000
000278  #define WALINDEX_MAX_VERSION 3007000
000279  
000280  /*
000281  ** Index numbers for various locking bytes.   WAL_NREADER is the number
000282  ** of available reader locks and should be at least 3.  The default
000283  ** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
000284  **
000285  ** Technically, the various VFSes are free to implement these locks however
000286  ** they see fit.  However, compatibility is encouraged so that VFSes can
000287  ** interoperate.  The standard implementation used on both unix and windows
000288  ** is for the index number to indicate a byte offset into the
000289  ** WalCkptInfo.aLock[] array in the wal-index header.  In other words, all
000290  ** locks are on the shm file.  The WALINDEX_LOCK_OFFSET constant (which
000291  ** should be 120) is the location in the shm file for the first locking
000292  ** byte.
000293  */
000294  #define WAL_WRITE_LOCK         0
000295  #define WAL_ALL_BUT_WRITE      1
000296  #define WAL_CKPT_LOCK          1
000297  #define WAL_RECOVER_LOCK       2
000298  #define WAL_READ_LOCK(I)       (3+(I))
000299  #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
000300  
000301  
000302  /* Object declarations */
000303  typedef struct WalIndexHdr WalIndexHdr;
000304  typedef struct WalIterator WalIterator;
000305  typedef struct WalCkptInfo WalCkptInfo;
000306  
000307  
000308  /*
000309  ** The following object holds a copy of the wal-index header content.
000310  **
000311  ** The actual header in the wal-index consists of two copies of this
000312  ** object followed by one instance of the WalCkptInfo object.
000313  ** For all versions of SQLite through 3.10.0 and probably beyond,
000314  ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
000315  ** the total header size is 136 bytes.
000316  **
000317  ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
000318  ** Or it can be 1 to represent a 65536-byte page.  The latter case was
000319  ** added in 3.7.1 when support for 64K pages was added.
000320  */
000321  struct WalIndexHdr {
000322    u32 iVersion;                   /* Wal-index version */
000323    u32 unused;                     /* Unused (padding) field */
000324    u32 iChange;                    /* Counter incremented each transaction */
000325    u8 isInit;                      /* 1 when initialized */
000326    u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
000327    u16 szPage;                     /* Database page size in bytes. 1==64K */
000328    u32 mxFrame;                    /* Index of last valid frame in the WAL */
000329    u32 nPage;                      /* Size of database in pages */
000330    u32 aFrameCksum[2];             /* Checksum of last frame in log */
000331    u32 aSalt[2];                   /* Two salt values copied from WAL header */
000332    u32 aCksum[2];                  /* Checksum over all prior fields */
000333  };
000334  
000335  /*
000336  ** A copy of the following object occurs in the wal-index immediately
000337  ** following the second copy of the WalIndexHdr.  This object stores
000338  ** information used by checkpoint.
000339  **
000340  ** nBackfill is the number of frames in the WAL that have been written
000341  ** back into the database. (We call the act of moving content from WAL to
000342  ** database "backfilling".)  The nBackfill number is never greater than
000343  ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
000344  ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
000345  ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
000346  ** mxFrame back to zero when the WAL is reset.
000347  **
000348  ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
000349  ** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
000350  ** the nBackfillAttempted is set before any backfilling is done and the
000351  ** nBackfill is only set after all backfilling completes.  So if a checkpoint
000352  ** crashes, nBackfillAttempted might be larger than nBackfill.  The
000353  ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
000354  **
000355  ** The aLock[] field is a set of bytes used for locking.  These bytes should
000356  ** never be read or written.
000357  **
000358  ** There is one entry in aReadMark[] for each reader lock.  If a reader
000359  ** holds read-lock K, then the value in aReadMark[K] is no greater than
000360  ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
000361  ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
000362  ** a special case; its value is never used and it exists as a place-holder
000363  ** to avoid having to offset aReadMark[] indexes by one.  Readers holding
000364  ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
000365  ** directly from the database.
000366  **
000367  ** The value of aReadMark[K] may only be changed by a thread that
000368  ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
000369  ** aReadMark[K] cannot changed while there is a reader is using that mark
000370  ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
000371  **
000372  ** The checkpointer may only transfer frames from WAL to database where
000373  ** the frame numbers are less than or equal to every aReadMark[] that is
000374  ** in use (that is, every aReadMark[j] for which there is a corresponding
000375  ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
000376  ** largest value and will increase an unused aReadMark[] to mxFrame if there
000377  ** is not already an aReadMark[] equal to mxFrame.  The exception to the
000378  ** previous sentence is when nBackfill equals mxFrame (meaning that everything
000379  ** in the WAL has been backfilled into the database) then new readers
000380  ** will choose aReadMark[0] which has value 0 and hence such reader will
000381  ** get all their all content directly from the database file and ignore
000382  ** the WAL.
000383  **
000384  ** Writers normally append new frames to the end of the WAL.  However,
000385  ** if nBackfill equals mxFrame (meaning that all WAL content has been
000386  ** written back into the database) and if no readers are using the WAL
000387  ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
000388  ** the writer will first "reset" the WAL back to the beginning and start
000389  ** writing new content beginning at frame 1.
000390  **
000391  ** We assume that 32-bit loads are atomic and so no locks are needed in
000392  ** order to read from any aReadMark[] entries.
000393  */
000394  struct WalCkptInfo {
000395    u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
000396    u32 aReadMark[WAL_NREADER];     /* Reader marks */
000397    u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
000398    u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
000399    u32 notUsed0;                   /* Available for future enhancements */
000400  };
000401  #define READMARK_NOT_USED  0xffffffff
000402  
000403  /*
000404  ** This is a schematic view of the complete 136-byte header of the
000405  ** wal-index file (also known as the -shm file):
000406  **
000407  **      +-----------------------------+
000408  **   0: | iVersion                    | \
000409  **      +-----------------------------+  |
000410  **   4: | (unused padding)            |  |
000411  **      +-----------------------------+  |
000412  **   8: | iChange                     |  |
000413  **      +-------+-------+-------------+  |
000414  **  12: | bInit |  bBig |   szPage    |  |
000415  **      +-------+-------+-------------+  |
000416  **  16: | mxFrame                     |  |  First copy of the
000417  **      +-----------------------------+  |  WalIndexHdr object
000418  **  20: | nPage                       |  |
000419  **      +-----------------------------+  |
000420  **  24: | aFrameCksum                 |  |
000421  **      |                             |  |
000422  **      +-----------------------------+  |
000423  **  32: | aSalt                       |  |
000424  **      |                             |  |
000425  **      +-----------------------------+  |
000426  **  40: | aCksum                      |  |
000427  **      |                             | /
000428  **      +-----------------------------+
000429  **  48: | iVersion                    | \
000430  **      +-----------------------------+  |
000431  **  52: | (unused padding)            |  |
000432  **      +-----------------------------+  |
000433  **  56: | iChange                     |  |
000434  **      +-------+-------+-------------+  |
000435  **  60: | bInit |  bBig |   szPage    |  |
000436  **      +-------+-------+-------------+  |  Second copy of the
000437  **  64: | mxFrame                     |  |  WalIndexHdr
000438  **      +-----------------------------+  |
000439  **  68: | nPage                       |  |
000440  **      +-----------------------------+  |
000441  **  72: | aFrameCksum                 |  |
000442  **      |                             |  |
000443  **      +-----------------------------+  |
000444  **  80: | aSalt                       |  |
000445  **      |                             |  |
000446  **      +-----------------------------+  |
000447  **  88: | aCksum                      |  |
000448  **      |                             | /
000449  **      +-----------------------------+
000450  **  96: | nBackfill                   |
000451  **      +-----------------------------+
000452  ** 100: | 5 read marks                |
000453  **      |                             |
000454  **      |                             |
000455  **      |                             |
000456  **      |                             |
000457  **      +-------+-------+------+------+
000458  ** 120: | Write | Ckpt  | Rcvr | Rd0  | \
000459  **      +-------+-------+------+------+  ) 8 lock bytes
000460  **      | Read1 | Read2 | Rd3  | Rd4  | /
000461  **      +-------+-------+------+------+
000462  ** 128: | nBackfillAttempted          |
000463  **      +-----------------------------+
000464  ** 132: | (unused padding)            |
000465  **      +-----------------------------+
000466  */
000467  
000468  /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
000469  ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
000470  ** only support mandatory file-locks, we do not read or write data
000471  ** from the region of the file on which locks are applied.
000472  */
000473  #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
000474  #define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
000475  
000476  /* Size of header before each frame in wal */
000477  #define WAL_FRAME_HDRSIZE 24
000478  
000479  /* Size of write ahead log header, including checksum. */
000480  #define WAL_HDRSIZE 32
000481  
000482  /* WAL magic value. Either this value, or the same value with the least
000483  ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
000484  ** big-endian format in the first 4 bytes of a WAL file.
000485  **
000486  ** If the LSB is set, then the checksums for each frame within the WAL
000487  ** file are calculated by treating all data as an array of 32-bit
000488  ** big-endian words. Otherwise, they are calculated by interpreting
000489  ** all data as 32-bit little-endian words.
000490  */
000491  #define WAL_MAGIC 0x377f0682
000492  
000493  /*
000494  ** Return the offset of frame iFrame in the write-ahead log file,
000495  ** assuming a database page size of szPage bytes. The offset returned
000496  ** is to the start of the write-ahead log frame-header.
000497  */
000498  #define walFrameOffset(iFrame, szPage) (                               \
000499    WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
000500  )
000501  
000502  /*
000503  ** An open write-ahead log file is represented by an instance of the
000504  ** following object.
000505  */
000506  struct Wal {
000507    sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
000508    sqlite3_file *pDbFd;       /* File handle for the database file */
000509    sqlite3_file *pWalFd;      /* File handle for WAL file */
000510    u32 iCallback;             /* Value to pass to log callback (or 0) */
000511    i64 mxWalSize;             /* Truncate WAL to this size upon reset */
000512    int nWiData;               /* Size of array apWiData */
000513    int szFirstBlock;          /* Size of first block written to WAL file */
000514    volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
000515    u32 szPage;                /* Database page size */
000516    i16 readLock;              /* Which read lock is being held.  -1 for none */
000517    u8 syncFlags;              /* Flags to use to sync header writes */
000518    u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
000519    u8 writeLock;              /* True if in a write transaction */
000520    u8 ckptLock;               /* True if holding a checkpoint lock */
000521    u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
000522    u8 truncateOnCommit;       /* True to truncate WAL file on commit */
000523    u8 syncHeader;             /* Fsync the WAL header if true */
000524    u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
000525    u8 bShmUnreliable;         /* SHM content is read-only and unreliable */
000526    WalIndexHdr hdr;           /* Wal-index header for current transaction */
000527    u32 minFrame;              /* Ignore wal frames before this one */
000528    u32 iReCksum;              /* On commit, recalculate checksums from here */
000529    const char *zWalName;      /* Name of WAL file */
000530    u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
000531  #ifdef SQLITE_USE_SEH
000532    u32 lockMask;              /* Mask of locks held */
000533    void *pFree;               /* Pointer to sqlite3_free() if exception thrown */
000534    u32 *pWiValue;             /* Value to write into apWiData[iWiPg] */
000535    int iWiPg;                 /* Write pWiValue into apWiData[iWiPg] */
000536    int iSysErrno;             /* System error code following exception */
000537  #endif
000538  #ifdef SQLITE_DEBUG
000539    int nSehTry;               /* Number of nested SEH_TRY{} blocks */
000540    u8 lockError;              /* True if a locking error has occurred */
000541  #endif
000542  #ifdef SQLITE_ENABLE_SNAPSHOT
000543    WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
000544    int bGetSnapshot;          /* Transaction opened for sqlite3_get_snapshot() */
000545  #endif
000546  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
000547    sqlite3 *db;
000548  #endif
000549  };
000550  
000551  /*
000552  ** Candidate values for Wal.exclusiveMode.
000553  */
000554  #define WAL_NORMAL_MODE     0
000555  #define WAL_EXCLUSIVE_MODE  1
000556  #define WAL_HEAPMEMORY_MODE 2
000557  
000558  /*
000559  ** Possible values for WAL.readOnly
000560  */
000561  #define WAL_RDWR        0    /* Normal read/write connection */
000562  #define WAL_RDONLY      1    /* The WAL file is readonly */
000563  #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
000564  
000565  /*
000566  ** Each page of the wal-index mapping contains a hash-table made up of
000567  ** an array of HASHTABLE_NSLOT elements of the following type.
000568  */
000569  typedef u16 ht_slot;
000570  
000571  /*
000572  ** This structure is used to implement an iterator that loops through
000573  ** all frames in the WAL in database page order. Where two or more frames
000574  ** correspond to the same database page, the iterator visits only the
000575  ** frame most recently written to the WAL (in other words, the frame with
000576  ** the largest index).
000577  **
000578  ** The internals of this structure are only accessed by:
000579  **
000580  **   walIteratorInit() - Create a new iterator,
000581  **   walIteratorNext() - Step an iterator,
000582  **   walIteratorFree() - Free an iterator.
000583  **
000584  ** This functionality is used by the checkpoint code (see walCheckpoint()).
000585  */
000586  struct WalIterator {
000587    u32 iPrior;                     /* Last result returned from the iterator */
000588    int nSegment;                   /* Number of entries in aSegment[] */
000589    struct WalSegment {
000590      int iNext;                    /* Next slot in aIndex[] not yet returned */
000591      ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
000592      u32 *aPgno;                   /* Array of page numbers. */
000593      int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
000594      int iZero;                    /* Frame number associated with aPgno[0] */
000595    } aSegment[1];                  /* One for every 32KB page in the wal-index */
000596  };
000597  
000598  /*
000599  ** Define the parameters of the hash tables in the wal-index file. There
000600  ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
000601  ** wal-index.
000602  **
000603  ** Changing any of these constants will alter the wal-index format and
000604  ** create incompatibilities.
000605  */
000606  #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
000607  #define HASHTABLE_HASH_1     383                  /* Should be prime */
000608  #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
000609  
000610  /*
000611  ** The block of page numbers associated with the first hash-table in a
000612  ** wal-index is smaller than usual. This is so that there is a complete
000613  ** hash-table on each aligned 32KB page of the wal-index.
000614  */
000615  #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
000616  
000617  /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
000618  #define WALINDEX_PGSZ   (                                         \
000619      sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
000620  )
000621  
000622  /*
000623  ** Structured Exception Handling (SEH) is a Windows-specific technique
000624  ** for catching exceptions raised while accessing memory-mapped files.
000625  **
000626  ** The -DSQLITE_USE_SEH compile-time option means to use SEH to catch and
000627  ** deal with system-level errors that arise during WAL -shm file processing.
000628  ** Without this compile-time option, any system-level faults that appear
000629  ** while accessing the memory-mapped -shm file will cause a process-wide
000630  ** signal to be deliver, which will more than likely cause the entire
000631  ** process to exit.
000632  */
000633  #ifdef SQLITE_USE_SEH
000634  #include <Windows.h>
000635  
000636  /* Beginning of a block of code in which an exception might occur */
000637  # define SEH_TRY    __try { \
000638     assert( walAssertLockmask(pWal) && pWal->nSehTry==0 ); \
000639     VVA_ONLY(pWal->nSehTry++);
000640  
000641  /* The end of a block of code in which an exception might occur */
000642  # define SEH_EXCEPT(X) \
000643     VVA_ONLY(pWal->nSehTry--); \
000644     assert( pWal->nSehTry==0 ); \
000645     } __except( sehExceptionFilter(pWal, GetExceptionCode(), GetExceptionInformation() ) ){ X }
000646  
000647  /* Simulate a memory-mapping fault in the -shm file for testing purposes */
000648  # define SEH_INJECT_FAULT sehInjectFault(pWal) 
000649  
000650  /*
000651  ** The second argument is the return value of GetExceptionCode() for the 
000652  ** current exception. Return EXCEPTION_EXECUTE_HANDLER if the exception code
000653  ** indicates that the exception may have been caused by accessing the *-shm 
000654  ** file mapping. Or EXCEPTION_CONTINUE_SEARCH otherwise.
000655  */
000656  static int sehExceptionFilter(Wal *pWal, int eCode, EXCEPTION_POINTERS *p){
000657    VVA_ONLY(pWal->nSehTry--);
000658    if( eCode==EXCEPTION_IN_PAGE_ERROR ){
000659      if( p && p->ExceptionRecord && p->ExceptionRecord->NumberParameters>=3 ){
000660        /* From MSDN: For this type of exception, the first element of the
000661        ** ExceptionInformation[] array is a read-write flag - 0 if the exception
000662        ** was thrown while reading, 1 if while writing. The second element is
000663        ** the virtual address being accessed. The "third array element specifies
000664        ** the underlying NTSTATUS code that resulted in the exception". */
000665        pWal->iSysErrno = (int)p->ExceptionRecord->ExceptionInformation[2];
000666      }
000667      return EXCEPTION_EXECUTE_HANDLER;
000668    }
000669    return EXCEPTION_CONTINUE_SEARCH;
000670  }
000671  
000672  /*
000673  ** If one is configured, invoke the xTestCallback callback with 650 as
000674  ** the argument. If it returns true, throw the same exception that is
000675  ** thrown by the system if the *-shm file mapping is accessed after it
000676  ** has been invalidated.
000677  */
000678  static void sehInjectFault(Wal *pWal){
000679    int res;
000680    assert( pWal->nSehTry>0 );
000681  
000682    res = sqlite3FaultSim(650);
000683    if( res!=0 ){
000684      ULONG_PTR aArg[3];
000685      aArg[0] = 0;
000686      aArg[1] = 0;
000687      aArg[2] = (ULONG_PTR)res;
000688      RaiseException(EXCEPTION_IN_PAGE_ERROR, 0, 3, (const ULONG_PTR*)aArg);
000689    }
000690  }
000691  
000692  /*
000693  ** There are two ways to use this macro. To set a pointer to be freed
000694  ** if an exception is thrown:
000695  **
000696  **   SEH_FREE_ON_ERROR(0, pPtr);
000697  **
000698  ** and to cancel the same:
000699  **
000700  **   SEH_FREE_ON_ERROR(pPtr, 0);
000701  **
000702  ** In the first case, there must not already be a pointer registered to
000703  ** be freed. In the second case, pPtr must be the registered pointer.
000704  */
000705  #define SEH_FREE_ON_ERROR(X,Y) \
000706    assert( (X==0 || Y==0) && pWal->pFree==X ); pWal->pFree = Y
000707  
000708  /*
000709  ** There are two ways to use this macro. To arrange for pWal->apWiData[iPg]
000710  ** to be set to pValue if an exception is thrown:
000711  **
000712  **   SEH_SET_ON_ERROR(iPg, pValue);
000713  **
000714  ** and to cancel the same:
000715  **
000716  **   SEH_SET_ON_ERROR(0, 0);
000717  */
000718  #define SEH_SET_ON_ERROR(X,Y)  pWal->iWiPg = X; pWal->pWiValue = Y
000719  
000720  #else
000721  # define SEH_TRY          VVA_ONLY(pWal->nSehTry++);
000722  # define SEH_EXCEPT(X)    VVA_ONLY(pWal->nSehTry--); assert( pWal->nSehTry==0 );
000723  # define SEH_INJECT_FAULT assert( pWal->nSehTry>0 );
000724  # define SEH_FREE_ON_ERROR(X,Y)
000725  # define SEH_SET_ON_ERROR(X,Y)
000726  #endif /* ifdef SQLITE_USE_SEH */
000727  
000728  
000729  /*
000730  ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
000731  ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
000732  ** numbered from zero.
000733  **
000734  ** If the wal-index is currently smaller the iPage pages then the size
000735  ** of the wal-index might be increased, but only if it is safe to do
000736  ** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
000737  ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
000738  **
000739  ** Three possible result scenarios:
000740  **
000741  **   (1)  rc==SQLITE_OK    and *ppPage==Requested-Wal-Index-Page
000742  **   (2)  rc>=SQLITE_ERROR and *ppPage==NULL
000743  **   (3)  rc==SQLITE_OK    and *ppPage==NULL  // only if iPage==0
000744  **
000745  ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
000746  */
000747  static SQLITE_NOINLINE int walIndexPageRealloc(
000748    Wal *pWal,               /* The WAL context */
000749    int iPage,               /* The page we seek */
000750    volatile u32 **ppPage    /* Write the page pointer here */
000751  ){
000752    int rc = SQLITE_OK;
000753  
000754    /* Enlarge the pWal->apWiData[] array if required */
000755    if( pWal->nWiData<=iPage ){
000756      sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
000757      volatile u32 **apNew;
000758      apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
000759      if( !apNew ){
000760        *ppPage = 0;
000761        return SQLITE_NOMEM_BKPT;
000762      }
000763      memset((void*)&apNew[pWal->nWiData], 0,
000764             sizeof(u32*)*(iPage+1-pWal->nWiData));
000765      pWal->apWiData = apNew;
000766      pWal->nWiData = iPage+1;
000767    }
000768  
000769    /* Request a pointer to the required page from the VFS */
000770    assert( pWal->apWiData[iPage]==0 );
000771    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
000772      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
000773      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
000774    }else{
000775      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
000776          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
000777      );
000778      assert( pWal->apWiData[iPage]!=0
000779           || rc!=SQLITE_OK
000780           || (pWal->writeLock==0 && iPage==0) );
000781      testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
000782      if( rc==SQLITE_OK ){
000783        if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
000784      }else if( (rc&0xff)==SQLITE_READONLY ){
000785        pWal->readOnly |= WAL_SHM_RDONLY;
000786        if( rc==SQLITE_READONLY ){
000787          rc = SQLITE_OK;
000788        }
000789      }
000790    }
000791  
000792    *ppPage = pWal->apWiData[iPage];
000793    assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
000794    return rc;
000795  }
000796  static int walIndexPage(
000797    Wal *pWal,               /* The WAL context */
000798    int iPage,               /* The page we seek */
000799    volatile u32 **ppPage    /* Write the page pointer here */
000800  ){
000801    SEH_INJECT_FAULT;
000802    if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
000803      return walIndexPageRealloc(pWal, iPage, ppPage);
000804    }
000805    return SQLITE_OK;
000806  }
000807  
000808  /*
000809  ** Return a pointer to the WalCkptInfo structure in the wal-index.
000810  */
000811  static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
000812    assert( pWal->nWiData>0 && pWal->apWiData[0] );
000813    SEH_INJECT_FAULT;
000814    return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
000815  }
000816  
000817  /*
000818  ** Return a pointer to the WalIndexHdr structure in the wal-index.
000819  */
000820  static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
000821    assert( pWal->nWiData>0 && pWal->apWiData[0] );
000822    SEH_INJECT_FAULT;
000823    return (volatile WalIndexHdr*)pWal->apWiData[0];
000824  }
000825  
000826  /*
000827  ** The argument to this macro must be of type u32. On a little-endian
000828  ** architecture, it returns the u32 value that results from interpreting
000829  ** the 4 bytes as a big-endian value. On a big-endian architecture, it
000830  ** returns the value that would be produced by interpreting the 4 bytes
000831  ** of the input value as a little-endian integer.
000832  */
000833  #define BYTESWAP32(x) ( \
000834      (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
000835    + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
000836  )
000837  
000838  /*
000839  ** Generate or extend an 8 byte checksum based on the data in
000840  ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
000841  ** initial values of 0 and 0 if aIn==NULL).
000842  **
000843  ** The checksum is written back into aOut[] before returning.
000844  **
000845  ** nByte must be a positive multiple of 8.
000846  */
000847  static void walChecksumBytes(
000848    int nativeCksum, /* True for native byte-order, false for non-native */
000849    u8 *a,           /* Content to be checksummed */
000850    int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
000851    const u32 *aIn,  /* Initial checksum value input */
000852    u32 *aOut        /* OUT: Final checksum value output */
000853  ){
000854    u32 s1, s2;
000855    u32 *aData = (u32 *)a;
000856    u32 *aEnd = (u32 *)&a[nByte];
000857  
000858    if( aIn ){
000859      s1 = aIn[0];
000860      s2 = aIn[1];
000861    }else{
000862      s1 = s2 = 0;
000863    }
000864  
000865    assert( nByte>=8 );
000866    assert( (nByte&0x00000007)==0 );
000867    assert( nByte<=65536 );
000868    assert( nByte%4==0 );
000869  
000870    if( !nativeCksum ){
000871      do {
000872        s1 += BYTESWAP32(aData[0]) + s2;
000873        s2 += BYTESWAP32(aData[1]) + s1;
000874        aData += 2;
000875      }while( aData<aEnd );
000876    }else if( nByte%64==0 ){
000877      do {
000878        s1 += *aData++ + s2;
000879        s2 += *aData++ + s1;
000880        s1 += *aData++ + s2;
000881        s2 += *aData++ + s1;
000882        s1 += *aData++ + s2;
000883        s2 += *aData++ + s1;
000884        s1 += *aData++ + s2;
000885        s2 += *aData++ + s1;
000886        s1 += *aData++ + s2;
000887        s2 += *aData++ + s1;
000888        s1 += *aData++ + s2;
000889        s2 += *aData++ + s1;
000890        s1 += *aData++ + s2;
000891        s2 += *aData++ + s1;
000892        s1 += *aData++ + s2;
000893        s2 += *aData++ + s1;
000894      }while( aData<aEnd );
000895    }else{
000896      do {
000897        s1 += *aData++ + s2;
000898        s2 += *aData++ + s1;
000899      }while( aData<aEnd );
000900    }
000901    assert( aData==aEnd );
000902  
000903    aOut[0] = s1;
000904    aOut[1] = s2;
000905  }
000906  
000907  /*
000908  ** If there is the possibility of concurrent access to the SHM file
000909  ** from multiple threads and/or processes, then do a memory barrier.
000910  */
000911  static void walShmBarrier(Wal *pWal){
000912    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
000913      sqlite3OsShmBarrier(pWal->pDbFd);
000914    }
000915  }
000916  
000917  /*
000918  ** Add the SQLITE_NO_TSAN as part of the return-type of a function
000919  ** definition as a hint that the function contains constructs that
000920  ** might give false-positive TSAN warnings.
000921  **
000922  ** See tag-20200519-1.
000923  */
000924  #if defined(__clang__) && !defined(SQLITE_NO_TSAN)
000925  # define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
000926  #else
000927  # define SQLITE_NO_TSAN
000928  #endif
000929  
000930  /*
000931  ** Write the header information in pWal->hdr into the wal-index.
000932  **
000933  ** The checksum on pWal->hdr is updated before it is written.
000934  */
000935  static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
000936    volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
000937    const int nCksum = offsetof(WalIndexHdr, aCksum);
000938  
000939    assert( pWal->writeLock );
000940    pWal->hdr.isInit = 1;
000941    pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
000942    walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
000943    /* Possible TSAN false-positive.  See tag-20200519-1 */
000944    memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
000945    walShmBarrier(pWal);
000946    memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
000947  }
000948  
000949  /*
000950  ** This function encodes a single frame header and writes it to a buffer
000951  ** supplied by the caller. A frame-header is made up of a series of
000952  ** 4-byte big-endian integers, as follows:
000953  **
000954  **     0: Page number.
000955  **     4: For commit records, the size of the database image in pages
000956  **        after the commit. For all other records, zero.
000957  **     8: Salt-1 (copied from the wal-header)
000958  **    12: Salt-2 (copied from the wal-header)
000959  **    16: Checksum-1.
000960  **    20: Checksum-2.
000961  */
000962  static void walEncodeFrame(
000963    Wal *pWal,                      /* The write-ahead log */
000964    u32 iPage,                      /* Database page number for frame */
000965    u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
000966    u8 *aData,                      /* Pointer to page data */
000967    u8 *aFrame                      /* OUT: Write encoded frame here */
000968  ){
000969    int nativeCksum;                /* True for native byte-order checksums */
000970    u32 *aCksum = pWal->hdr.aFrameCksum;
000971    assert( WAL_FRAME_HDRSIZE==24 );
000972    sqlite3Put4byte(&aFrame[0], iPage);
000973    sqlite3Put4byte(&aFrame[4], nTruncate);
000974    if( pWal->iReCksum==0 ){
000975      memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
000976  
000977      nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
000978      walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
000979      walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
000980  
000981      sqlite3Put4byte(&aFrame[16], aCksum[0]);
000982      sqlite3Put4byte(&aFrame[20], aCksum[1]);
000983    }else{
000984      memset(&aFrame[8], 0, 16);
000985    }
000986  }
000987  
000988  /*
000989  ** Check to see if the frame with header in aFrame[] and content
000990  ** in aData[] is valid.  If it is a valid frame, fill *piPage and
000991  ** *pnTruncate and return true.  Return if the frame is not valid.
000992  */
000993  static int walDecodeFrame(
000994    Wal *pWal,                      /* The write-ahead log */
000995    u32 *piPage,                    /* OUT: Database page number for frame */
000996    u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
000997    u8 *aData,                      /* Pointer to page data (for checksum) */
000998    u8 *aFrame                      /* Frame data */
000999  ){
001000    int nativeCksum;                /* True for native byte-order checksums */
001001    u32 *aCksum = pWal->hdr.aFrameCksum;
001002    u32 pgno;                       /* Page number of the frame */
001003    assert( WAL_FRAME_HDRSIZE==24 );
001004  
001005    /* A frame is only valid if the salt values in the frame-header
001006    ** match the salt values in the wal-header.
001007    */
001008    if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
001009      return 0;
001010    }
001011  
001012    /* A frame is only valid if the page number is greater than zero.
001013    */
001014    pgno = sqlite3Get4byte(&aFrame[0]);
001015    if( pgno==0 ){
001016      return 0;
001017    }
001018  
001019    /* A frame is only valid if a checksum of the WAL header,
001020    ** all prior frames, the first 16 bytes of this frame-header,
001021    ** and the frame-data matches the checksum in the last 8
001022    ** bytes of this frame-header.
001023    */
001024    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
001025    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
001026    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
001027    if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
001028     || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
001029    ){
001030      /* Checksum failed. */
001031      return 0;
001032    }
001033  
001034    /* If we reach this point, the frame is valid.  Return the page number
001035    ** and the new database size.
001036    */
001037    *piPage = pgno;
001038    *pnTruncate = sqlite3Get4byte(&aFrame[4]);
001039    return 1;
001040  }
001041  
001042  
001043  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
001044  /*
001045  ** Names of locks.  This routine is used to provide debugging output and is not
001046  ** a part of an ordinary build.
001047  */
001048  static const char *walLockName(int lockIdx){
001049    if( lockIdx==WAL_WRITE_LOCK ){
001050      return "WRITE-LOCK";
001051    }else if( lockIdx==WAL_CKPT_LOCK ){
001052      return "CKPT-LOCK";
001053    }else if( lockIdx==WAL_RECOVER_LOCK ){
001054      return "RECOVER-LOCK";
001055    }else{
001056      static char zName[15];
001057      sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
001058                       lockIdx-WAL_READ_LOCK(0));
001059      return zName;
001060    }
001061  }
001062  #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
001063  
001064  
001065  /*
001066  ** Set or release locks on the WAL.  Locks are either shared or exclusive.
001067  ** A lock cannot be moved directly between shared and exclusive - it must go
001068  ** through the unlocked state first.
001069  **
001070  ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
001071  */
001072  static int walLockShared(Wal *pWal, int lockIdx){
001073    int rc;
001074    if( pWal->exclusiveMode ) return SQLITE_OK;
001075    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
001076                          SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
001077    WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
001078              walLockName(lockIdx), rc ? "failed" : "ok"));
001079    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
001080  #ifdef SQLITE_USE_SEH
001081    if( rc==SQLITE_OK ) pWal->lockMask |= (1 << lockIdx);
001082  #endif
001083    return rc;
001084  }
001085  static void walUnlockShared(Wal *pWal, int lockIdx){
001086    if( pWal->exclusiveMode ) return;
001087    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
001088                           SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
001089  #ifdef SQLITE_USE_SEH
001090    pWal->lockMask &= ~(1 << lockIdx);
001091  #endif
001092    WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
001093  }
001094  static int walLockExclusive(Wal *pWal, int lockIdx, int n){
001095    int rc;
001096    if( pWal->exclusiveMode ) return SQLITE_OK;
001097    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
001098                          SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
001099    WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
001100              walLockName(lockIdx), n, rc ? "failed" : "ok"));
001101    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
001102  #ifdef SQLITE_USE_SEH
001103    if( rc==SQLITE_OK ){
001104      pWal->lockMask |= (((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
001105    }
001106  #endif
001107    return rc;
001108  }
001109  static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
001110    if( pWal->exclusiveMode ) return;
001111    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
001112                           SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
001113  #ifdef SQLITE_USE_SEH
001114    pWal->lockMask &= ~(((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
001115  #endif
001116    WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
001117               walLockName(lockIdx), n));
001118  }
001119  
001120  /*
001121  ** Compute a hash on a page number.  The resulting hash value must land
001122  ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
001123  ** the hash to the next value in the event of a collision.
001124  */
001125  static int walHash(u32 iPage){
001126    assert( iPage>0 );
001127    assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
001128    return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
001129  }
001130  static int walNextHash(int iPriorHash){
001131    return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
001132  }
001133  
001134  /*
001135  ** An instance of the WalHashLoc object is used to describe the location
001136  ** of a page hash table in the wal-index.  This becomes the return value
001137  ** from walHashGet().
001138  */
001139  typedef struct WalHashLoc WalHashLoc;
001140  struct WalHashLoc {
001141    volatile ht_slot *aHash;  /* Start of the wal-index hash table */
001142    volatile u32 *aPgno;      /* aPgno[1] is the page of first frame indexed */
001143    u32 iZero;                /* One less than the frame number of first indexed*/
001144  };
001145  
001146  /*
001147  ** Return pointers to the hash table and page number array stored on
001148  ** page iHash of the wal-index. The wal-index is broken into 32KB pages
001149  ** numbered starting from 0.
001150  **
001151  ** Set output variable pLoc->aHash to point to the start of the hash table
001152  ** in the wal-index file. Set pLoc->iZero to one less than the frame
001153  ** number of the first frame indexed by this hash table. If a
001154  ** slot in the hash table is set to N, it refers to frame number
001155  ** (pLoc->iZero+N) in the log.
001156  **
001157  ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
001158  ** first frame indexed by the hash table, frame (pLoc->iZero).
001159  */
001160  static int walHashGet(
001161    Wal *pWal,                      /* WAL handle */
001162    int iHash,                      /* Find the iHash'th table */
001163    WalHashLoc *pLoc                /* OUT: Hash table location */
001164  ){
001165    int rc;                         /* Return code */
001166  
001167    rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
001168    assert( rc==SQLITE_OK || iHash>0 );
001169  
001170    if( pLoc->aPgno ){
001171      pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
001172      if( iHash==0 ){
001173        pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
001174        pLoc->iZero = 0;
001175      }else{
001176        pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
001177      }
001178    }else if( NEVER(rc==SQLITE_OK) ){
001179      rc = SQLITE_ERROR;
001180    }
001181    return rc;
001182  }
001183  
001184  /*
001185  ** Return the number of the wal-index page that contains the hash-table
001186  ** and page-number array that contain entries corresponding to WAL frame
001187  ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
001188  ** are numbered starting from 0.
001189  */
001190  static int walFramePage(u32 iFrame){
001191    int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
001192    assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
001193         && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
001194         && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
001195         && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
001196         && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
001197    );
001198    assert( iHash>=0 );
001199    return iHash;
001200  }
001201  
001202  /*
001203  ** Return the page number associated with frame iFrame in this WAL.
001204  */
001205  static u32 walFramePgno(Wal *pWal, u32 iFrame){
001206    int iHash = walFramePage(iFrame);
001207    SEH_INJECT_FAULT;
001208    if( iHash==0 ){
001209      return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
001210    }
001211    return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
001212  }
001213  
001214  /*
001215  ** Remove entries from the hash table that point to WAL slots greater
001216  ** than pWal->hdr.mxFrame.
001217  **
001218  ** This function is called whenever pWal->hdr.mxFrame is decreased due
001219  ** to a rollback or savepoint.
001220  **
001221  ** At most only the hash table containing pWal->hdr.mxFrame needs to be
001222  ** updated.  Any later hash tables will be automatically cleared when
001223  ** pWal->hdr.mxFrame advances to the point where those hash tables are
001224  ** actually needed.
001225  */
001226  static void walCleanupHash(Wal *pWal){
001227    WalHashLoc sLoc;                /* Hash table location */
001228    int iLimit = 0;                 /* Zero values greater than this */
001229    int nByte;                      /* Number of bytes to zero in aPgno[] */
001230    int i;                          /* Used to iterate through aHash[] */
001231  
001232    assert( pWal->writeLock );
001233    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
001234    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
001235    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
001236  
001237    if( pWal->hdr.mxFrame==0 ) return;
001238  
001239    /* Obtain pointers to the hash-table and page-number array containing
001240    ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
001241    ** that the page said hash-table and array reside on is already mapped.(1)
001242    */
001243    assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
001244    assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
001245    i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
001246    if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
001247  
001248    /* Zero all hash-table entries that correspond to frame numbers greater
001249    ** than pWal->hdr.mxFrame.
001250    */
001251    iLimit = pWal->hdr.mxFrame - sLoc.iZero;
001252    assert( iLimit>0 );
001253    for(i=0; i<HASHTABLE_NSLOT; i++){
001254      if( sLoc.aHash[i]>iLimit ){
001255        sLoc.aHash[i] = 0;
001256      }
001257    }
001258  
001259    /* Zero the entries in the aPgno array that correspond to frames with
001260    ** frame numbers greater than pWal->hdr.mxFrame.
001261    */
001262    nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
001263    assert( nByte>=0 );
001264    memset((void *)&sLoc.aPgno[iLimit], 0, nByte);
001265  
001266  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
001267    /* Verify that the every entry in the mapping region is still reachable
001268    ** via the hash table even after the cleanup.
001269    */
001270    if( iLimit ){
001271      int j;           /* Loop counter */
001272      int iKey;        /* Hash key */
001273      for(j=0; j<iLimit; j++){
001274        for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
001275          if( sLoc.aHash[iKey]==j+1 ) break;
001276        }
001277        assert( sLoc.aHash[iKey]==j+1 );
001278      }
001279    }
001280  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
001281  }
001282  
001283  
001284  /*
001285  ** Set an entry in the wal-index that will map database page number
001286  ** pPage into WAL frame iFrame.
001287  */
001288  static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
001289    int rc;                         /* Return code */
001290    WalHashLoc sLoc;                /* Wal-index hash table location */
001291  
001292    rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
001293  
001294    /* Assuming the wal-index file was successfully mapped, populate the
001295    ** page number array and hash table entry.
001296    */
001297    if( rc==SQLITE_OK ){
001298      int iKey;                     /* Hash table key */
001299      int idx;                      /* Value to write to hash-table slot */
001300      int nCollide;                 /* Number of hash collisions */
001301  
001302      idx = iFrame - sLoc.iZero;
001303      assert( idx <= HASHTABLE_NSLOT/2 + 1 );
001304  
001305      /* If this is the first entry to be added to this hash-table, zero the
001306      ** entire hash table and aPgno[] array before proceeding.
001307      */
001308      if( idx==1 ){
001309        int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
001310        assert( nByte>=0 );
001311        memset((void*)sLoc.aPgno, 0, nByte);
001312      }
001313  
001314      /* If the entry in aPgno[] is already set, then the previous writer
001315      ** must have exited unexpectedly in the middle of a transaction (after
001316      ** writing one or more dirty pages to the WAL to free up memory).
001317      ** Remove the remnants of that writers uncommitted transaction from
001318      ** the hash-table before writing any new entries.
001319      */
001320      if( sLoc.aPgno[idx-1] ){
001321        walCleanupHash(pWal);
001322        assert( !sLoc.aPgno[idx-1] );
001323      }
001324  
001325      /* Write the aPgno[] array entry and the hash-table slot. */
001326      nCollide = idx;
001327      for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
001328        if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
001329      }
001330      sLoc.aPgno[idx-1] = iPage;
001331      AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
001332  
001333  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
001334      /* Verify that the number of entries in the hash table exactly equals
001335      ** the number of entries in the mapping region.
001336      */
001337      {
001338        int i;           /* Loop counter */
001339        int nEntry = 0;  /* Number of entries in the hash table */
001340        for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
001341        assert( nEntry==idx );
001342      }
001343  
001344      /* Verify that the every entry in the mapping region is reachable
001345      ** via the hash table.  This turns out to be a really, really expensive
001346      ** thing to check, so only do this occasionally - not on every
001347      ** iteration.
001348      */
001349      if( (idx&0x3ff)==0 ){
001350        int i;           /* Loop counter */
001351        for(i=0; i<idx; i++){
001352          for(iKey=walHash(sLoc.aPgno[i]);
001353              sLoc.aHash[iKey];
001354              iKey=walNextHash(iKey)){
001355            if( sLoc.aHash[iKey]==i+1 ) break;
001356          }
001357          assert( sLoc.aHash[iKey]==i+1 );
001358        }
001359      }
001360  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
001361    }
001362  
001363    return rc;
001364  }
001365  
001366  
001367  /*
001368  ** Recover the wal-index by reading the write-ahead log file.
001369  **
001370  ** This routine first tries to establish an exclusive lock on the
001371  ** wal-index to prevent other threads/processes from doing anything
001372  ** with the WAL or wal-index while recovery is running.  The
001373  ** WAL_RECOVER_LOCK is also held so that other threads will know
001374  ** that this thread is running recovery.  If unable to establish
001375  ** the necessary locks, this routine returns SQLITE_BUSY.
001376  */
001377  static int walIndexRecover(Wal *pWal){
001378    int rc;                         /* Return Code */
001379    i64 nSize;                      /* Size of log file */
001380    u32 aFrameCksum[2] = {0, 0};
001381    int iLock;                      /* Lock offset to lock for checkpoint */
001382  
001383    /* Obtain an exclusive lock on all byte in the locking range not already
001384    ** locked by the caller. The caller is guaranteed to have locked the
001385    ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
001386    ** If successful, the same bytes that are locked here are unlocked before
001387    ** this function returns.
001388    */
001389    assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
001390    assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
001391    assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
001392    assert( pWal->writeLock );
001393    iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
001394    rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
001395    if( rc ){
001396      return rc;
001397    }
001398  
001399    WALTRACE(("WAL%p: recovery begin...\n", pWal));
001400  
001401    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
001402  
001403    rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
001404    if( rc!=SQLITE_OK ){
001405      goto recovery_error;
001406    }
001407  
001408    if( nSize>WAL_HDRSIZE ){
001409      u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
001410      u32 *aPrivate = 0;            /* Heap copy of *-shm hash being populated */
001411      u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
001412      int szFrame;                  /* Number of bytes in buffer aFrame[] */
001413      u8 *aData;                    /* Pointer to data part of aFrame buffer */
001414      int szPage;                   /* Page size according to the log */
001415      u32 magic;                    /* Magic value read from WAL header */
001416      u32 version;                  /* Magic value read from WAL header */
001417      int isValid;                  /* True if this frame is valid */
001418      u32 iPg;                      /* Current 32KB wal-index page */
001419      u32 iLastFrame;               /* Last frame in wal, based on nSize alone */
001420  
001421      /* Read in the WAL header. */
001422      rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
001423      if( rc!=SQLITE_OK ){
001424        goto recovery_error;
001425      }
001426  
001427      /* If the database page size is not a power of two, or is greater than
001428      ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
001429      ** data. Similarly, if the 'magic' value is invalid, ignore the whole
001430      ** WAL file.
001431      */
001432      magic = sqlite3Get4byte(&aBuf[0]);
001433      szPage = sqlite3Get4byte(&aBuf[8]);
001434      if( (magic&0xFFFFFFFE)!=WAL_MAGIC
001435       || szPage&(szPage-1)
001436       || szPage>SQLITE_MAX_PAGE_SIZE
001437       || szPage<512
001438      ){
001439        goto finished;
001440      }
001441      pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
001442      pWal->szPage = szPage;
001443      pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
001444      memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
001445  
001446      /* Verify that the WAL header checksum is correct */
001447      walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
001448          aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
001449      );
001450      if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
001451       || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
001452      ){
001453        goto finished;
001454      }
001455  
001456      /* Verify that the version number on the WAL format is one that
001457      ** are able to understand */
001458      version = sqlite3Get4byte(&aBuf[4]);
001459      if( version!=WAL_MAX_VERSION ){
001460        rc = SQLITE_CANTOPEN_BKPT;
001461        goto finished;
001462      }
001463  
001464      /* Malloc a buffer to read frames into. */
001465      szFrame = szPage + WAL_FRAME_HDRSIZE;
001466      aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ);
001467      SEH_FREE_ON_ERROR(0, aFrame);
001468      if( !aFrame ){
001469        rc = SQLITE_NOMEM_BKPT;
001470        goto recovery_error;
001471      }
001472      aData = &aFrame[WAL_FRAME_HDRSIZE];
001473      aPrivate = (u32*)&aData[szPage];
001474  
001475      /* Read all frames from the log file. */
001476      iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
001477      for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
001478        u32 *aShare;
001479        u32 iFrame;                 /* Index of last frame read */
001480        u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
001481        u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
001482        u32 nHdr, nHdr32;
001483        rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
001484        assert( aShare!=0 || rc!=SQLITE_OK );
001485        if( aShare==0 ) break;
001486        SEH_SET_ON_ERROR(iPg, aShare);
001487        pWal->apWiData[iPg] = aPrivate;
001488  
001489        for(iFrame=iFirst; iFrame<=iLast; iFrame++){
001490          i64 iOffset = walFrameOffset(iFrame, szPage);
001491          u32 pgno;                 /* Database page number for frame */
001492          u32 nTruncate;            /* dbsize field from frame header */
001493  
001494          /* Read and decode the next log frame. */
001495          rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
001496          if( rc!=SQLITE_OK ) break;
001497          isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
001498          if( !isValid ) break;
001499          rc = walIndexAppend(pWal, iFrame, pgno);
001500          if( NEVER(rc!=SQLITE_OK) ) break;
001501  
001502          /* If nTruncate is non-zero, this is a commit record. */
001503          if( nTruncate ){
001504            pWal->hdr.mxFrame = iFrame;
001505            pWal->hdr.nPage = nTruncate;
001506            pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
001507            testcase( szPage<=32768 );
001508            testcase( szPage>=65536 );
001509            aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
001510            aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
001511          }
001512        }
001513        pWal->apWiData[iPg] = aShare;
001514        SEH_SET_ON_ERROR(0,0);
001515        nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
001516        nHdr32 = nHdr / sizeof(u32);
001517  #ifndef SQLITE_SAFER_WALINDEX_RECOVERY
001518        /* Memcpy() should work fine here, on all reasonable implementations.
001519        ** Technically, memcpy() might change the destination to some
001520        ** intermediate value before setting to the final value, and that might
001521        ** cause a concurrent reader to malfunction.  Memcpy() is allowed to
001522        ** do that, according to the spec, but no memcpy() implementation that
001523        ** we know of actually does that, which is why we say that memcpy()
001524        ** is safe for this.  Memcpy() is certainly a lot faster.
001525        */
001526        memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
001527  #else
001528        /* In the event that some platform is found for which memcpy()
001529        ** changes the destination to some intermediate value before
001530        ** setting the final value, this alternative copy routine is
001531        ** provided.
001532        */
001533        {
001534          int i;
001535          for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
001536            if( aShare[i]!=aPrivate[i] ){
001537              /* Atomic memory operations are not required here because if
001538              ** the value needs to be changed, that means it is not being
001539              ** accessed concurrently. */
001540              aShare[i] = aPrivate[i];
001541            }
001542          }
001543        }
001544  #endif
001545        SEH_INJECT_FAULT;
001546        if( iFrame<=iLast ) break;
001547      }
001548  
001549      SEH_FREE_ON_ERROR(aFrame, 0);
001550      sqlite3_free(aFrame);
001551    }
001552  
001553  finished:
001554    if( rc==SQLITE_OK ){
001555      volatile WalCkptInfo *pInfo;
001556      int i;
001557      pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
001558      pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
001559      walIndexWriteHdr(pWal);
001560  
001561      /* Reset the checkpoint-header. This is safe because this thread is
001562      ** currently holding locks that exclude all other writers and
001563      ** checkpointers. Then set the values of read-mark slots 1 through N.
001564      */
001565      pInfo = walCkptInfo(pWal);
001566      pInfo->nBackfill = 0;
001567      pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
001568      pInfo->aReadMark[0] = 0;
001569      for(i=1; i<WAL_NREADER; i++){
001570        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
001571        if( rc==SQLITE_OK ){
001572          if( i==1 && pWal->hdr.mxFrame ){
001573            pInfo->aReadMark[i] = pWal->hdr.mxFrame;
001574          }else{
001575            pInfo->aReadMark[i] = READMARK_NOT_USED;
001576          }
001577          SEH_INJECT_FAULT;
001578          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
001579        }else if( rc!=SQLITE_BUSY ){
001580          goto recovery_error;
001581        }
001582      }
001583  
001584      /* If more than one frame was recovered from the log file, report an
001585      ** event via sqlite3_log(). This is to help with identifying performance
001586      ** problems caused by applications routinely shutting down without
001587      ** checkpointing the log file.
001588      */
001589      if( pWal->hdr.nPage ){
001590        sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
001591            "recovered %d frames from WAL file %s",
001592            pWal->hdr.mxFrame, pWal->zWalName
001593        );
001594      }
001595    }
001596  
001597  recovery_error:
001598    WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
001599    walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
001600    return rc;
001601  }
001602  
001603  /*
001604  ** Close an open wal-index.
001605  */
001606  static void walIndexClose(Wal *pWal, int isDelete){
001607    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
001608      int i;
001609      for(i=0; i<pWal->nWiData; i++){
001610        sqlite3_free((void *)pWal->apWiData[i]);
001611        pWal->apWiData[i] = 0;
001612      }
001613    }
001614    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
001615      sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
001616    }
001617  }
001618  
001619  /*
001620  ** Open a connection to the WAL file zWalName. The database file must
001621  ** already be opened on connection pDbFd. The buffer that zWalName points
001622  ** to must remain valid for the lifetime of the returned Wal* handle.
001623  **
001624  ** A SHARED lock should be held on the database file when this function
001625  ** is called. The purpose of this SHARED lock is to prevent any other
001626  ** client from unlinking the WAL or wal-index file. If another process
001627  ** were to do this just after this client opened one of these files, the
001628  ** system would be badly broken.
001629  **
001630  ** If the log file is successfully opened, SQLITE_OK is returned and
001631  ** *ppWal is set to point to a new WAL handle. If an error occurs,
001632  ** an SQLite error code is returned and *ppWal is left unmodified.
001633  */
001634  int sqlite3WalOpen(
001635    sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
001636    sqlite3_file *pDbFd,            /* The open database file */
001637    const char *zWalName,           /* Name of the WAL file */
001638    int bNoShm,                     /* True to run in heap-memory mode */
001639    i64 mxWalSize,                  /* Truncate WAL to this size on reset */
001640    Wal **ppWal                     /* OUT: Allocated Wal handle */
001641  ){
001642    int rc;                         /* Return Code */
001643    Wal *pRet;                      /* Object to allocate and return */
001644    int flags;                      /* Flags passed to OsOpen() */
001645  
001646    assert( zWalName && zWalName[0] );
001647    assert( pDbFd );
001648  
001649    /* Verify the values of various constants.  Any changes to the values
001650    ** of these constants would result in an incompatible on-disk format
001651    ** for the -shm file.  Any change that causes one of these asserts to
001652    ** fail is a backward compatibility problem, even if the change otherwise
001653    ** works.
001654    **
001655    ** This table also serves as a helpful cross-reference when trying to
001656    ** interpret hex dumps of the -shm file.
001657    */
001658    assert(    48 ==  sizeof(WalIndexHdr)  );
001659    assert(    40 ==  sizeof(WalCkptInfo)  );
001660    assert(   120 ==  WALINDEX_LOCK_OFFSET );
001661    assert(   136 ==  WALINDEX_HDR_SIZE    );
001662    assert(  4096 ==  HASHTABLE_NPAGE      );
001663    assert(  4062 ==  HASHTABLE_NPAGE_ONE  );
001664    assert(  8192 ==  HASHTABLE_NSLOT      );
001665    assert(   383 ==  HASHTABLE_HASH_1     );
001666    assert( 32768 ==  WALINDEX_PGSZ        );
001667    assert(     8 ==  SQLITE_SHM_NLOCK     );
001668    assert(     5 ==  WAL_NREADER          );
001669    assert(    24 ==  WAL_FRAME_HDRSIZE    );
001670    assert(    32 ==  WAL_HDRSIZE          );
001671    assert(   120 ==  WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK   );
001672    assert(   121 ==  WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK    );
001673    assert(   122 ==  WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK );
001674    assert(   123 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) );
001675    assert(   124 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) );
001676    assert(   125 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) );
001677    assert(   126 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) );
001678    assert(   127 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) );
001679  
001680    /* In the amalgamation, the os_unix.c and os_win.c source files come before
001681    ** this source file.  Verify that the #defines of the locking byte offsets
001682    ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
001683    ** For that matter, if the lock offset ever changes from its initial design
001684    ** value of 120, we need to know that so there is an assert() to check it.
001685    */
001686  #ifdef WIN_SHM_BASE
001687    assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
001688  #endif
001689  #ifdef UNIX_SHM_BASE
001690    assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
001691  #endif
001692  
001693  
001694    /* Allocate an instance of struct Wal to return. */
001695    *ppWal = 0;
001696    pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
001697    if( !pRet ){
001698      return SQLITE_NOMEM_BKPT;
001699    }
001700  
001701    pRet->pVfs = pVfs;
001702    pRet->pWalFd = (sqlite3_file *)&pRet[1];
001703    pRet->pDbFd = pDbFd;
001704    pRet->readLock = -1;
001705    pRet->mxWalSize = mxWalSize;
001706    pRet->zWalName = zWalName;
001707    pRet->syncHeader = 1;
001708    pRet->padToSectorBoundary = 1;
001709    pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
001710  
001711    /* Open file handle on the write-ahead log file. */
001712    flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
001713    rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
001714    if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
001715      pRet->readOnly = WAL_RDONLY;
001716    }
001717  
001718    if( rc!=SQLITE_OK ){
001719      walIndexClose(pRet, 0);
001720      sqlite3OsClose(pRet->pWalFd);
001721      sqlite3_free(pRet);
001722    }else{
001723      int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
001724      if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
001725      if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
001726        pRet->padToSectorBoundary = 0;
001727      }
001728      *ppWal = pRet;
001729      WALTRACE(("WAL%d: opened\n", pRet));
001730    }
001731    return rc;
001732  }
001733  
001734  /*
001735  ** Change the size to which the WAL file is truncated on each reset.
001736  */
001737  void sqlite3WalLimit(Wal *pWal, i64 iLimit){
001738    if( pWal ) pWal->mxWalSize = iLimit;
001739  }
001740  
001741  /*
001742  ** Find the smallest page number out of all pages held in the WAL that
001743  ** has not been returned by any prior invocation of this method on the
001744  ** same WalIterator object.   Write into *piFrame the frame index where
001745  ** that page was last written into the WAL.  Write into *piPage the page
001746  ** number.
001747  **
001748  ** Return 0 on success.  If there are no pages in the WAL with a page
001749  ** number larger than *piPage, then return 1.
001750  */
001751  static int walIteratorNext(
001752    WalIterator *p,               /* Iterator */
001753    u32 *piPage,                  /* OUT: The page number of the next page */
001754    u32 *piFrame                  /* OUT: Wal frame index of next page */
001755  ){
001756    u32 iMin;                     /* Result pgno must be greater than iMin */
001757    u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
001758    int i;                        /* For looping through segments */
001759  
001760    iMin = p->iPrior;
001761    assert( iMin<0xffffffff );
001762    for(i=p->nSegment-1; i>=0; i--){
001763      struct WalSegment *pSegment = &p->aSegment[i];
001764      while( pSegment->iNext<pSegment->nEntry ){
001765        u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
001766        if( iPg>iMin ){
001767          if( iPg<iRet ){
001768            iRet = iPg;
001769            *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
001770          }
001771          break;
001772        }
001773        pSegment->iNext++;
001774      }
001775    }
001776  
001777    *piPage = p->iPrior = iRet;
001778    return (iRet==0xFFFFFFFF);
001779  }
001780  
001781  /*
001782  ** This function merges two sorted lists into a single sorted list.
001783  **
001784  ** aLeft[] and aRight[] are arrays of indices.  The sort key is
001785  ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
001786  ** is guaranteed for all J<K:
001787  **
001788  **        aContent[aLeft[J]] < aContent[aLeft[K]]
001789  **        aContent[aRight[J]] < aContent[aRight[K]]
001790  **
001791  ** This routine overwrites aRight[] with a new (probably longer) sequence
001792  ** of indices such that the aRight[] contains every index that appears in
001793  ** either aLeft[] or the old aRight[] and such that the second condition
001794  ** above is still met.
001795  **
001796  ** The aContent[aLeft[X]] values will be unique for all X.  And the
001797  ** aContent[aRight[X]] values will be unique too.  But there might be
001798  ** one or more combinations of X and Y such that
001799  **
001800  **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
001801  **
001802  ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
001803  */
001804  static void walMerge(
001805    const u32 *aContent,            /* Pages in wal - keys for the sort */
001806    ht_slot *aLeft,                 /* IN: Left hand input list */
001807    int nLeft,                      /* IN: Elements in array *paLeft */
001808    ht_slot **paRight,              /* IN/OUT: Right hand input list */
001809    int *pnRight,                   /* IN/OUT: Elements in *paRight */
001810    ht_slot *aTmp                   /* Temporary buffer */
001811  ){
001812    int iLeft = 0;                  /* Current index in aLeft */
001813    int iRight = 0;                 /* Current index in aRight */
001814    int iOut = 0;                   /* Current index in output buffer */
001815    int nRight = *pnRight;
001816    ht_slot *aRight = *paRight;
001817  
001818    assert( nLeft>0 && nRight>0 );
001819    while( iRight<nRight || iLeft<nLeft ){
001820      ht_slot logpage;
001821      Pgno dbpage;
001822  
001823      if( (iLeft<nLeft)
001824       && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
001825      ){
001826        logpage = aLeft[iLeft++];
001827      }else{
001828        logpage = aRight[iRight++];
001829      }
001830      dbpage = aContent[logpage];
001831  
001832      aTmp[iOut++] = logpage;
001833      if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
001834  
001835      assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
001836      assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
001837    }
001838  
001839    *paRight = aLeft;
001840    *pnRight = iOut;
001841    memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
001842  }
001843  
001844  /*
001845  ** Sort the elements in list aList using aContent[] as the sort key.
001846  ** Remove elements with duplicate keys, preferring to keep the
001847  ** larger aList[] values.
001848  **
001849  ** The aList[] entries are indices into aContent[].  The values in
001850  ** aList[] are to be sorted so that for all J<K:
001851  **
001852  **      aContent[aList[J]] < aContent[aList[K]]
001853  **
001854  ** For any X and Y such that
001855  **
001856  **      aContent[aList[X]] == aContent[aList[Y]]
001857  **
001858  ** Keep the larger of the two values aList[X] and aList[Y] and discard
001859  ** the smaller.
001860  */
001861  static void walMergesort(
001862    const u32 *aContent,            /* Pages in wal */
001863    ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
001864    ht_slot *aList,                 /* IN/OUT: List to sort */
001865    int *pnList                     /* IN/OUT: Number of elements in aList[] */
001866  ){
001867    struct Sublist {
001868      int nList;                    /* Number of elements in aList */
001869      ht_slot *aList;               /* Pointer to sub-list content */
001870    };
001871  
001872    const int nList = *pnList;      /* Size of input list */
001873    int nMerge = 0;                 /* Number of elements in list aMerge */
001874    ht_slot *aMerge = 0;            /* List to be merged */
001875    int iList;                      /* Index into input list */
001876    u32 iSub = 0;                   /* Index into aSub array */
001877    struct Sublist aSub[13];        /* Array of sub-lists */
001878  
001879    memset(aSub, 0, sizeof(aSub));
001880    assert( nList<=HASHTABLE_NPAGE && nList>0 );
001881    assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
001882  
001883    for(iList=0; iList<nList; iList++){
001884      nMerge = 1;
001885      aMerge = &aList[iList];
001886      for(iSub=0; iList & (1<<iSub); iSub++){
001887        struct Sublist *p;
001888        assert( iSub<ArraySize(aSub) );
001889        p = &aSub[iSub];
001890        assert( p->aList && p->nList<=(1<<iSub) );
001891        assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
001892        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
001893      }
001894      aSub[iSub].aList = aMerge;
001895      aSub[iSub].nList = nMerge;
001896    }
001897  
001898    for(iSub++; iSub<ArraySize(aSub); iSub++){
001899      if( nList & (1<<iSub) ){
001900        struct Sublist *p;
001901        assert( iSub<ArraySize(aSub) );
001902        p = &aSub[iSub];
001903        assert( p->nList<=(1<<iSub) );
001904        assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
001905        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
001906      }
001907    }
001908    assert( aMerge==aList );
001909    *pnList = nMerge;
001910  
001911  #ifdef SQLITE_DEBUG
001912    {
001913      int i;
001914      for(i=1; i<*pnList; i++){
001915        assert( aContent[aList[i]] > aContent[aList[i-1]] );
001916      }
001917    }
001918  #endif
001919  }
001920  
001921  /*
001922  ** Free an iterator allocated by walIteratorInit().
001923  */
001924  static void walIteratorFree(WalIterator *p){
001925    sqlite3_free(p);
001926  }
001927  
001928  /*
001929  ** Construct a WalInterator object that can be used to loop over all
001930  ** pages in the WAL following frame nBackfill in ascending order. Frames
001931  ** nBackfill or earlier may be included - excluding them is an optimization
001932  ** only. The caller must hold the checkpoint lock.
001933  **
001934  ** On success, make *pp point to the newly allocated WalInterator object
001935  ** return SQLITE_OK. Otherwise, return an error code. If this routine
001936  ** returns an error, the value of *pp is undefined.
001937  **
001938  ** The calling routine should invoke walIteratorFree() to destroy the
001939  ** WalIterator object when it has finished with it.
001940  */
001941  static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
001942    WalIterator *p;                 /* Return value */
001943    int nSegment;                   /* Number of segments to merge */
001944    u32 iLast;                      /* Last frame in log */
001945    sqlite3_int64 nByte;            /* Number of bytes to allocate */
001946    int i;                          /* Iterator variable */
001947    ht_slot *aTmp;                  /* Temp space used by merge-sort */
001948    int rc = SQLITE_OK;             /* Return Code */
001949  
001950    /* This routine only runs while holding the checkpoint lock. And
001951    ** it only runs if there is actually content in the log (mxFrame>0).
001952    */
001953    assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
001954    iLast = pWal->hdr.mxFrame;
001955  
001956    /* Allocate space for the WalIterator object. */
001957    nSegment = walFramePage(iLast) + 1;
001958    nByte = sizeof(WalIterator)
001959          + (nSegment-1)*sizeof(struct WalSegment)
001960          + iLast*sizeof(ht_slot);
001961    p = (WalIterator *)sqlite3_malloc64(nByte
001962        + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
001963    );
001964    if( !p ){
001965      return SQLITE_NOMEM_BKPT;
001966    }
001967    memset(p, 0, nByte);
001968    p->nSegment = nSegment;
001969    aTmp = (ht_slot*)&(((u8*)p)[nByte]);
001970    SEH_FREE_ON_ERROR(0, p);
001971    for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
001972      WalHashLoc sLoc;
001973  
001974      rc = walHashGet(pWal, i, &sLoc);
001975      if( rc==SQLITE_OK ){
001976        int j;                      /* Counter variable */
001977        int nEntry;                 /* Number of entries in this segment */
001978        ht_slot *aIndex;            /* Sorted index for this segment */
001979  
001980        if( (i+1)==nSegment ){
001981          nEntry = (int)(iLast - sLoc.iZero);
001982        }else{
001983          nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
001984        }
001985        aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
001986        sLoc.iZero++;
001987  
001988        for(j=0; j<nEntry; j++){
001989          aIndex[j] = (ht_slot)j;
001990        }
001991        walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
001992        p->aSegment[i].iZero = sLoc.iZero;
001993        p->aSegment[i].nEntry = nEntry;
001994        p->aSegment[i].aIndex = aIndex;
001995        p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
001996      }
001997    }
001998    if( rc!=SQLITE_OK ){
001999      SEH_FREE_ON_ERROR(p, 0);
002000      walIteratorFree(p);
002001      p = 0;
002002    }
002003    *pp = p;
002004    return rc;
002005  }
002006  
002007  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
002008  
002009  
002010  /*
002011  ** Attempt to enable blocking locks that block for nMs ms. Return 1 if 
002012  ** blocking locks are successfully enabled, or 0 otherwise.
002013  */
002014  static int walEnableBlockingMs(Wal *pWal, int nMs){
002015    int rc = sqlite3OsFileControl(
002016        pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&nMs
002017    );
002018    return (rc==SQLITE_OK);
002019  }
002020  
002021  /*
002022  ** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
002023  ** they are supported by the VFS, and (b) the database handle is configured
002024  ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
002025  ** or 0 otherwise.
002026  */
002027  static int walEnableBlocking(Wal *pWal){
002028    int res = 0;
002029    if( pWal->db ){
002030      int tmout = pWal->db->busyTimeout;
002031      if( tmout ){
002032        res = walEnableBlockingMs(pWal, tmout);
002033      }
002034    }
002035    return res;
002036  }
002037  
002038  /*
002039  ** Disable blocking locks.
002040  */
002041  static void walDisableBlocking(Wal *pWal){
002042    int tmout = 0;
002043    sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
002044  }
002045  
002046  /*
002047  ** If parameter bLock is true, attempt to enable blocking locks, take
002048  ** the WRITER lock, and then disable blocking locks. If blocking locks
002049  ** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
002050  ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
002051  ** an error if blocking locks can not be enabled.
002052  **
002053  ** If the bLock parameter is false and the WRITER lock is held, release it.
002054  */
002055  int sqlite3WalWriteLock(Wal *pWal, int bLock){
002056    int rc = SQLITE_OK;
002057    assert( pWal->readLock<0 || bLock==0 );
002058    if( bLock ){
002059      assert( pWal->db );
002060      if( walEnableBlocking(pWal) ){
002061        rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
002062        if( rc==SQLITE_OK ){
002063          pWal->writeLock = 1;
002064        }
002065        walDisableBlocking(pWal);
002066      }
002067    }else if( pWal->writeLock ){
002068      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
002069      pWal->writeLock = 0;
002070    }
002071    return rc;
002072  }
002073  
002074  /*
002075  ** Set the database handle used to determine if blocking locks are required.
002076  */
002077  void sqlite3WalDb(Wal *pWal, sqlite3 *db){
002078    pWal->db = db;
002079  }
002080  
002081  #else
002082  # define walEnableBlocking(x) 0
002083  # define walDisableBlocking(x)
002084  # define walEnableBlockingMs(pWal, ms) 0
002085  # define sqlite3WalDb(pWal, db)
002086  #endif   /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
002087  
002088  
002089  /*
002090  ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
002091  ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
002092  ** busy-handler function. Invoke it and retry the lock until either the
002093  ** lock is successfully obtained or the busy-handler returns 0.
002094  */
002095  static int walBusyLock(
002096    Wal *pWal,                      /* WAL connection */
002097    int (*xBusy)(void*),            /* Function to call when busy */
002098    void *pBusyArg,                 /* Context argument for xBusyHandler */
002099    int lockIdx,                    /* Offset of first byte to lock */
002100    int n                           /* Number of bytes to lock */
002101  ){
002102    int rc;
002103    do {
002104      rc = walLockExclusive(pWal, lockIdx, n);
002105    }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
002106  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
002107    if( rc==SQLITE_BUSY_TIMEOUT ){
002108      walDisableBlocking(pWal);
002109      rc = SQLITE_BUSY;
002110    }
002111  #endif
002112    return rc;
002113  }
002114  
002115  /*
002116  ** The cache of the wal-index header must be valid to call this function.
002117  ** Return the page-size in bytes used by the database.
002118  */
002119  static int walPagesize(Wal *pWal){
002120    return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
002121  }
002122  
002123  /*
002124  ** The following is guaranteed when this function is called:
002125  **
002126  **   a) the WRITER lock is held,
002127  **   b) the entire log file has been checkpointed, and
002128  **   c) any existing readers are reading exclusively from the database
002129  **      file - there are no readers that may attempt to read a frame from
002130  **      the log file.
002131  **
002132  ** This function updates the shared-memory structures so that the next
002133  ** client to write to the database (which may be this one) does so by
002134  ** writing frames into the start of the log file.
002135  **
002136  ** The value of parameter salt1 is used as the aSalt[1] value in the
002137  ** new wal-index header. It should be passed a pseudo-random value (i.e.
002138  ** one obtained from sqlite3_randomness()).
002139  */
002140  static void walRestartHdr(Wal *pWal, u32 salt1){
002141    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
002142    int i;                          /* Loop counter */
002143    u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
002144    pWal->nCkpt++;
002145    pWal->hdr.mxFrame = 0;
002146    sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
002147    memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
002148    walIndexWriteHdr(pWal);
002149    AtomicStore(&pInfo->nBackfill, 0);
002150    pInfo->nBackfillAttempted = 0;
002151    pInfo->aReadMark[1] = 0;
002152    for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
002153    assert( pInfo->aReadMark[0]==0 );
002154  }
002155  
002156  /*
002157  ** Copy as much content as we can from the WAL back into the database file
002158  ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
002159  **
002160  ** The amount of information copies from WAL to database might be limited
002161  ** by active readers.  This routine will never overwrite a database page
002162  ** that a concurrent reader might be using.
002163  **
002164  ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
002165  ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
002166  ** checkpoints are always run by a background thread or background
002167  ** process, foreground threads will never block on a lengthy fsync call.
002168  **
002169  ** Fsync is called on the WAL before writing content out of the WAL and
002170  ** into the database.  This ensures that if the new content is persistent
002171  ** in the WAL and can be recovered following a power-loss or hard reset.
002172  **
002173  ** Fsync is also called on the database file if (and only if) the entire
002174  ** WAL content is copied into the database file.  This second fsync makes
002175  ** it safe to delete the WAL since the new content will persist in the
002176  ** database file.
002177  **
002178  ** This routine uses and updates the nBackfill field of the wal-index header.
002179  ** This is the only routine that will increase the value of nBackfill.
002180  ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
002181  ** its value.)
002182  **
002183  ** The caller must be holding sufficient locks to ensure that no other
002184  ** checkpoint is running (in any other thread or process) at the same
002185  ** time.
002186  */
002187  static int walCheckpoint(
002188    Wal *pWal,                      /* Wal connection */
002189    sqlite3 *db,                    /* Check for interrupts on this handle */
002190    int eMode,                      /* One of PASSIVE, FULL or RESTART */
002191    int (*xBusy)(void*),            /* Function to call when busy */
002192    void *pBusyArg,                 /* Context argument for xBusyHandler */
002193    int sync_flags,                 /* Flags for OsSync() (or 0) */
002194    u8 *zBuf                        /* Temporary buffer to use */
002195  ){
002196    int rc = SQLITE_OK;             /* Return code */
002197    int szPage;                     /* Database page-size */
002198    WalIterator *pIter = 0;         /* Wal iterator context */
002199    u32 iDbpage = 0;                /* Next database page to write */
002200    u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
002201    u32 mxSafeFrame;                /* Max frame that can be backfilled */
002202    u32 mxPage;                     /* Max database page to write */
002203    int i;                          /* Loop counter */
002204    volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
002205  
002206    szPage = walPagesize(pWal);
002207    testcase( szPage<=32768 );
002208    testcase( szPage>=65536 );
002209    pInfo = walCkptInfo(pWal);
002210    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
002211  
002212      /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
002213      ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
002214      assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
002215  
002216      /* Compute in mxSafeFrame the index of the last frame of the WAL that is
002217      ** safe to write into the database.  Frames beyond mxSafeFrame might
002218      ** overwrite database pages that are in use by active readers and thus
002219      ** cannot be backfilled from the WAL.
002220      */
002221      mxSafeFrame = pWal->hdr.mxFrame;
002222      mxPage = pWal->hdr.nPage;
002223      for(i=1; i<WAL_NREADER; i++){
002224        u32 y = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
002225        if( mxSafeFrame>y ){
002226          assert( y<=pWal->hdr.mxFrame );
002227          rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
002228          if( rc==SQLITE_OK ){
002229            u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
002230            AtomicStore(pInfo->aReadMark+i, iMark); SEH_INJECT_FAULT;
002231            walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
002232          }else if( rc==SQLITE_BUSY ){
002233            mxSafeFrame = y;
002234            xBusy = 0;
002235          }else{
002236            goto walcheckpoint_out;
002237          }
002238        }
002239      }
002240  
002241      /* Allocate the iterator */
002242      if( pInfo->nBackfill<mxSafeFrame ){
002243        rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
002244        assert( rc==SQLITE_OK || pIter==0 );
002245      }
002246  
002247      if( pIter
002248       && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
002249      ){
002250        u32 nBackfill = pInfo->nBackfill;
002251        pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT;
002252  
002253        /* Sync the WAL to disk */
002254        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
002255  
002256        /* If the database may grow as a result of this checkpoint, hint
002257        ** about the eventual size of the db file to the VFS layer.
002258        */
002259        if( rc==SQLITE_OK ){
002260          i64 nReq = ((i64)mxPage * szPage);
002261          i64 nSize;                    /* Current size of database file */
002262          sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
002263          rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
002264          if( rc==SQLITE_OK && nSize<nReq ){
002265            if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
002266              /* If the size of the final database is larger than the current
002267              ** database plus the amount of data in the wal file, plus the
002268              ** maximum size of the pending-byte page (65536 bytes), then
002269              ** must be corruption somewhere.  */
002270              rc = SQLITE_CORRUPT_BKPT;
002271            }else{
002272              sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
002273            }
002274          }
002275  
002276        }
002277  
002278        /* Iterate through the contents of the WAL, copying data to the db file */
002279        while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
002280          i64 iOffset;
002281          assert( walFramePgno(pWal, iFrame)==iDbpage );
002282          SEH_INJECT_FAULT;
002283          if( AtomicLoad(&db->u1.isInterrupted) ){
002284            rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
002285            break;
002286          }
002287          if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
002288            continue;
002289          }
002290          iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
002291          /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
002292          rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
002293          if( rc!=SQLITE_OK ) break;
002294          iOffset = (iDbpage-1)*(i64)szPage;
002295          testcase( IS_BIG_INT(iOffset) );
002296          rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
002297          if( rc!=SQLITE_OK ) break;
002298        }
002299        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
002300  
002301        /* If work was actually accomplished... */
002302        if( rc==SQLITE_OK ){
002303          if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
002304            i64 szDb = pWal->hdr.nPage*(i64)szPage;
002305            testcase( IS_BIG_INT(szDb) );
002306            rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
002307            if( rc==SQLITE_OK ){
002308              rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
002309            }
002310          }
002311          if( rc==SQLITE_OK ){
002312            AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT;
002313          }
002314        }
002315  
002316        /* Release the reader lock held while backfilling */
002317        walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
002318      }
002319  
002320      if( rc==SQLITE_BUSY ){
002321        /* Reset the return code so as not to report a checkpoint failure
002322        ** just because there are active readers.  */
002323        rc = SQLITE_OK;
002324      }
002325    }
002326  
002327    /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
002328    ** entire wal file has been copied into the database file, then block
002329    ** until all readers have finished using the wal file. This ensures that
002330    ** the next process to write to the database restarts the wal file.
002331    */
002332    if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
002333      assert( pWal->writeLock );
002334      SEH_INJECT_FAULT;
002335      if( pInfo->nBackfill<pWal->hdr.mxFrame ){
002336        rc = SQLITE_BUSY;
002337      }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
002338        u32 salt1;
002339        sqlite3_randomness(4, &salt1);
002340        assert( pInfo->nBackfill==pWal->hdr.mxFrame );
002341        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
002342        if( rc==SQLITE_OK ){
002343          if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
002344            /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
002345            ** SQLITE_CHECKPOINT_RESTART with the addition that it also
002346            ** truncates the log file to zero bytes just prior to a
002347            ** successful return.
002348            **
002349            ** In theory, it might be safe to do this without updating the
002350            ** wal-index header in shared memory, as all subsequent reader or
002351            ** writer clients should see that the entire log file has been
002352            ** checkpointed and behave accordingly. This seems unsafe though,
002353            ** as it would leave the system in a state where the contents of
002354            ** the wal-index header do not match the contents of the
002355            ** file-system. To avoid this, update the wal-index header to
002356            ** indicate that the log file contains zero valid frames.  */
002357            walRestartHdr(pWal, salt1);
002358            rc = sqlite3OsTruncate(pWal->pWalFd, 0);
002359          }
002360          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
002361        }
002362      }
002363    }
002364  
002365   walcheckpoint_out:
002366    SEH_FREE_ON_ERROR(pIter, 0);
002367    walIteratorFree(pIter);
002368    return rc;
002369  }
002370  
002371  /*
002372  ** If the WAL file is currently larger than nMax bytes in size, truncate
002373  ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
002374  */
002375  static void walLimitSize(Wal *pWal, i64 nMax){
002376    i64 sz;
002377    int rx;
002378    sqlite3BeginBenignMalloc();
002379    rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
002380    if( rx==SQLITE_OK && (sz > nMax ) ){
002381      rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
002382    }
002383    sqlite3EndBenignMalloc();
002384    if( rx ){
002385      sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
002386    }
002387  }
002388  
002389  #ifdef SQLITE_USE_SEH
002390  /*
002391  ** This is the "standard" exception handler used in a few places to handle 
002392  ** an exception thrown by reading from the *-shm mapping after it has become
002393  ** invalid in SQLITE_USE_SEH builds. It is used as follows:
002394  **
002395  **   SEH_TRY { ... }
002396  **   SEH_EXCEPT( rc = walHandleException(pWal); )
002397  **
002398  ** This function does three things:
002399  **
002400  **   1) Determines the locks that should be held, based on the contents of
002401  **      the Wal.readLock, Wal.writeLock and Wal.ckptLock variables. All other
002402  **      held locks are assumed to be transient locks that would have been
002403  **      released had the exception not been thrown and are dropped.
002404  **
002405  **   2) Frees the pointer at Wal.pFree, if any, using sqlite3_free().
002406  **
002407  **   3) Set pWal->apWiData[pWal->iWiPg] to pWal->pWiValue if not NULL
002408  **
002409  **   4) Returns SQLITE_IOERR.
002410  */
002411  static int walHandleException(Wal *pWal){
002412    if( pWal->exclusiveMode==0 ){
002413      static const int S = 1;
002414      static const int E = (1<<SQLITE_SHM_NLOCK);
002415      int ii;
002416      u32 mUnlock = pWal->lockMask & ~(
002417          (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
002418          | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
002419          | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
002420          );
002421      for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
002422        if( (S<<ii) & mUnlock ) walUnlockShared(pWal, ii);
002423        if( (E<<ii) & mUnlock ) walUnlockExclusive(pWal, ii, 1);
002424      }
002425    }
002426    sqlite3_free(pWal->pFree);
002427    pWal->pFree = 0;
002428    if( pWal->pWiValue ){
002429      pWal->apWiData[pWal->iWiPg] = pWal->pWiValue;
002430      pWal->pWiValue = 0;
002431    }
002432    return SQLITE_IOERR_IN_PAGE;
002433  }
002434  
002435  /*
002436  ** Assert that the Wal.lockMask mask, which indicates the locks held
002437  ** by the connection, is consistent with the Wal.readLock, Wal.writeLock
002438  ** and Wal.ckptLock variables. To be used as:
002439  **
002440  **   assert( walAssertLockmask(pWal) );
002441  */
002442  static int walAssertLockmask(Wal *pWal){
002443    if( pWal->exclusiveMode==0 ){
002444      static const int S = 1;
002445      static const int E = (1<<SQLITE_SHM_NLOCK);
002446      u32 mExpect = (
002447          (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
002448        | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
002449        | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
002450  #ifdef SQLITE_ENABLE_SNAPSHOT
002451        | (pWal->pSnapshot ? (pWal->lockMask & (1 << WAL_CKPT_LOCK)) : 0)
002452  #endif
002453      );
002454      assert( mExpect==pWal->lockMask );
002455    }
002456    return 1;
002457  }
002458  
002459  /*
002460  ** Return and zero the "system error" field set when an 
002461  ** EXCEPTION_IN_PAGE_ERROR exception is caught.
002462  */
002463  int sqlite3WalSystemErrno(Wal *pWal){
002464    int iRet = 0;
002465    if( pWal ){
002466      iRet = pWal->iSysErrno;
002467      pWal->iSysErrno = 0;
002468    }
002469    return iRet;
002470  }
002471  
002472  #else
002473  # define walAssertLockmask(x) 1
002474  #endif /* ifdef SQLITE_USE_SEH */
002475  
002476  /*
002477  ** Close a connection to a log file.
002478  */
002479  int sqlite3WalClose(
002480    Wal *pWal,                      /* Wal to close */
002481    sqlite3 *db,                    /* For interrupt flag */
002482    int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
002483    int nBuf,
002484    u8 *zBuf                        /* Buffer of at least nBuf bytes */
002485  ){
002486    int rc = SQLITE_OK;
002487    if( pWal ){
002488      int isDelete = 0;             /* True to unlink wal and wal-index files */
002489  
002490      assert( walAssertLockmask(pWal) );
002491  
002492      /* If an EXCLUSIVE lock can be obtained on the database file (using the
002493      ** ordinary, rollback-mode locking methods, this guarantees that the
002494      ** connection associated with this log file is the only connection to
002495      ** the database. In this case checkpoint the database and unlink both
002496      ** the wal and wal-index files.
002497      **
002498      ** The EXCLUSIVE lock is not released before returning.
002499      */
002500      if( zBuf!=0
002501       && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
002502      ){
002503        if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
002504          pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
002505        }
002506        rc = sqlite3WalCheckpoint(pWal, db,
002507            SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
002508        );
002509        if( rc==SQLITE_OK ){
002510          int bPersist = -1;
002511          sqlite3OsFileControlHint(
002512              pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
002513          );
002514          if( bPersist!=1 ){
002515            /* Try to delete the WAL file if the checkpoint completed and
002516            ** fsynced (rc==SQLITE_OK) and if we are not in persistent-wal
002517            ** mode (!bPersist) */
002518            isDelete = 1;
002519          }else if( pWal->mxWalSize>=0 ){
002520            /* Try to truncate the WAL file to zero bytes if the checkpoint
002521            ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
002522            ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
002523            ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
002524            ** to zero bytes as truncating to the journal_size_limit might
002525            ** leave a corrupt WAL file on disk. */
002526            walLimitSize(pWal, 0);
002527          }
002528        }
002529      }
002530  
002531      walIndexClose(pWal, isDelete);
002532      sqlite3OsClose(pWal->pWalFd);
002533      if( isDelete ){
002534        sqlite3BeginBenignMalloc();
002535        sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
002536        sqlite3EndBenignMalloc();
002537      }
002538      WALTRACE(("WAL%p: closed\n", pWal));
002539      sqlite3_free((void *)pWal->apWiData);
002540      sqlite3_free(pWal);
002541    }
002542    return rc;
002543  }
002544  
002545  /*
002546  ** Try to read the wal-index header.  Return 0 on success and 1 if
002547  ** there is a problem.
002548  **
002549  ** The wal-index is in shared memory.  Another thread or process might
002550  ** be writing the header at the same time this procedure is trying to
002551  ** read it, which might result in inconsistency.  A dirty read is detected
002552  ** by verifying that both copies of the header are the same and also by
002553  ** a checksum on the header.
002554  **
002555  ** If and only if the read is consistent and the header is different from
002556  ** pWal->hdr, then pWal->hdr is updated to the content of the new header
002557  ** and *pChanged is set to 1.
002558  **
002559  ** If the checksum cannot be verified return non-zero. If the header
002560  ** is read successfully and the checksum verified, return zero.
002561  */
002562  static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
002563    u32 aCksum[2];                  /* Checksum on the header content */
002564    WalIndexHdr h1, h2;             /* Two copies of the header content */
002565    WalIndexHdr volatile *aHdr;     /* Header in shared memory */
002566  
002567    /* The first page of the wal-index must be mapped at this point. */
002568    assert( pWal->nWiData>0 && pWal->apWiData[0] );
002569  
002570    /* Read the header. This might happen concurrently with a write to the
002571    ** same area of shared memory on a different CPU in a SMP,
002572    ** meaning it is possible that an inconsistent snapshot is read
002573    ** from the file. If this happens, return non-zero.
002574    **
002575    ** tag-20200519-1:
002576    ** There are two copies of the header at the beginning of the wal-index.
002577    ** When reading, read [0] first then [1].  Writes are in the reverse order.
002578    ** Memory barriers are used to prevent the compiler or the hardware from
002579    ** reordering the reads and writes.  TSAN and similar tools can sometimes
002580    ** give false-positive warnings about these accesses because the tools do not
002581    ** account for the double-read and the memory barrier. The use of mutexes
002582    ** here would be problematic as the memory being accessed is potentially
002583    ** shared among multiple processes and not all mutex implementations work
002584    ** reliably in that environment.
002585    */
002586    aHdr = walIndexHdr(pWal);
002587    memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
002588    walShmBarrier(pWal);
002589    memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
002590  
002591    if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
002592      return 1;   /* Dirty read */
002593    }
002594    if( h1.isInit==0 ){
002595      return 1;   /* Malformed header - probably all zeros */
002596    }
002597    walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
002598    if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
002599      return 1;   /* Checksum does not match */
002600    }
002601  
002602    if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
002603      *pChanged = 1;
002604      memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
002605      pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
002606      testcase( pWal->szPage<=32768 );
002607      testcase( pWal->szPage>=65536 );
002608    }
002609  
002610    /* The header was successfully read. Return zero. */
002611    return 0;
002612  }
002613  
002614  /*
002615  ** This is the value that walTryBeginRead returns when it needs to
002616  ** be retried.
002617  */
002618  #define WAL_RETRY  (-1)
002619  
002620  /*
002621  ** Read the wal-index header from the wal-index and into pWal->hdr.
002622  ** If the wal-header appears to be corrupt, try to reconstruct the
002623  ** wal-index from the WAL before returning.
002624  **
002625  ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
002626  ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
002627  ** to 0.
002628  **
002629  ** If the wal-index header is successfully read, return SQLITE_OK.
002630  ** Otherwise an SQLite error code.
002631  */
002632  static int walIndexReadHdr(Wal *pWal, int *pChanged){
002633    int rc;                         /* Return code */
002634    int badHdr;                     /* True if a header read failed */
002635    volatile u32 *page0;            /* Chunk of wal-index containing header */
002636  
002637    /* Ensure that page 0 of the wal-index (the page that contains the
002638    ** wal-index header) is mapped. Return early if an error occurs here.
002639    */
002640    assert( pChanged );
002641    rc = walIndexPage(pWal, 0, &page0);
002642    if( rc!=SQLITE_OK ){
002643      assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
002644      if( rc==SQLITE_READONLY_CANTINIT ){
002645        /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
002646        ** was openable but is not writable, and this thread is unable to
002647        ** confirm that another write-capable connection has the shared-memory
002648        ** open, and hence the content of the shared-memory is unreliable,
002649        ** since the shared-memory might be inconsistent with the WAL file
002650        ** and there is no writer on hand to fix it. */
002651        assert( page0==0 );
002652        assert( pWal->writeLock==0 );
002653        assert( pWal->readOnly & WAL_SHM_RDONLY );
002654        pWal->bShmUnreliable = 1;
002655        pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
002656        *pChanged = 1;
002657      }else{
002658        return rc; /* Any other non-OK return is just an error */
002659      }
002660    }else{
002661      /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
002662      ** is zero, which prevents the SHM from growing */
002663      testcase( page0!=0 );
002664    }
002665    assert( page0!=0 || pWal->writeLock==0 );
002666  
002667    /* If the first page of the wal-index has been mapped, try to read the
002668    ** wal-index header immediately, without holding any lock. This usually
002669    ** works, but may fail if the wal-index header is corrupt or currently
002670    ** being modified by another thread or process.
002671    */
002672    badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
002673  
002674    /* If the first attempt failed, it might have been due to a race
002675    ** with a writer.  So get a WRITE lock and try again.
002676    */
002677    if( badHdr ){
002678      if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
002679        if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
002680          walUnlockShared(pWal, WAL_WRITE_LOCK);
002681          rc = SQLITE_READONLY_RECOVERY;
002682        }
002683      }else{
002684        int bWriteLock = pWal->writeLock;
002685        if( bWriteLock 
002686         || SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) 
002687        ){
002688          pWal->writeLock = 1;
002689          if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
002690            badHdr = walIndexTryHdr(pWal, pChanged);
002691            if( badHdr ){
002692              /* If the wal-index header is still malformed even while holding
002693              ** a WRITE lock, it can only mean that the header is corrupted and
002694              ** needs to be reconstructed.  So run recovery to do exactly that.
002695              ** Disable blocking locks first.  */
002696              walDisableBlocking(pWal);
002697              rc = walIndexRecover(pWal);
002698              *pChanged = 1;
002699            }
002700          }
002701          if( bWriteLock==0 ){
002702            pWal->writeLock = 0;
002703            walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
002704          }
002705        }
002706      }
002707    }
002708  
002709    /* If the header is read successfully, check the version number to make
002710    ** sure the wal-index was not constructed with some future format that
002711    ** this version of SQLite cannot understand.
002712    */
002713    if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
002714      rc = SQLITE_CANTOPEN_BKPT;
002715    }
002716    if( pWal->bShmUnreliable ){
002717      if( rc!=SQLITE_OK ){
002718        walIndexClose(pWal, 0);
002719        pWal->bShmUnreliable = 0;
002720        assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
002721        /* walIndexRecover() might have returned SHORT_READ if a concurrent
002722        ** writer truncated the WAL out from under it.  If that happens, it
002723        ** indicates that a writer has fixed the SHM file for us, so retry */
002724        if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
002725      }
002726      pWal->exclusiveMode = WAL_NORMAL_MODE;
002727    }
002728  
002729    return rc;
002730  }
002731  
002732  /*
002733  ** Open a transaction in a connection where the shared-memory is read-only
002734  ** and where we cannot verify that there is a separate write-capable connection
002735  ** on hand to keep the shared-memory up-to-date with the WAL file.
002736  **
002737  ** This can happen, for example, when the shared-memory is implemented by
002738  ** memory-mapping a *-shm file, where a prior writer has shut down and
002739  ** left the *-shm file on disk, and now the present connection is trying
002740  ** to use that database but lacks write permission on the *-shm file.
002741  ** Other scenarios are also possible, depending on the VFS implementation.
002742  **
002743  ** Precondition:
002744  **
002745  **    The *-wal file has been read and an appropriate wal-index has been
002746  **    constructed in pWal->apWiData[] using heap memory instead of shared
002747  **    memory.
002748  **
002749  ** If this function returns SQLITE_OK, then the read transaction has
002750  ** been successfully opened. In this case output variable (*pChanged)
002751  ** is set to true before returning if the caller should discard the
002752  ** contents of the page cache before proceeding. Or, if it returns
002753  ** WAL_RETRY, then the heap memory wal-index has been discarded and
002754  ** the caller should retry opening the read transaction from the
002755  ** beginning (including attempting to map the *-shm file).
002756  **
002757  ** If an error occurs, an SQLite error code is returned.
002758  */
002759  static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
002760    i64 szWal;                      /* Size of wal file on disk in bytes */
002761    i64 iOffset;                    /* Current offset when reading wal file */
002762    u8 aBuf[WAL_HDRSIZE];           /* Buffer to load WAL header into */
002763    u8 *aFrame = 0;                 /* Malloc'd buffer to load entire frame */
002764    int szFrame;                    /* Number of bytes in buffer aFrame[] */
002765    u8 *aData;                      /* Pointer to data part of aFrame buffer */
002766    volatile void *pDummy;          /* Dummy argument for xShmMap */
002767    int rc;                         /* Return code */
002768    u32 aSaveCksum[2];              /* Saved copy of pWal->hdr.aFrameCksum */
002769  
002770    assert( pWal->bShmUnreliable );
002771    assert( pWal->readOnly & WAL_SHM_RDONLY );
002772    assert( pWal->nWiData>0 && pWal->apWiData[0] );
002773  
002774    /* Take WAL_READ_LOCK(0). This has the effect of preventing any
002775    ** writers from running a checkpoint, but does not stop them
002776    ** from running recovery.  */
002777    rc = walLockShared(pWal, WAL_READ_LOCK(0));
002778    if( rc!=SQLITE_OK ){
002779      if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
002780      goto begin_unreliable_shm_out;
002781    }
002782    pWal->readLock = 0;
002783  
002784    /* Check to see if a separate writer has attached to the shared-memory area,
002785    ** thus making the shared-memory "reliable" again.  Do this by invoking
002786    ** the xShmMap() routine of the VFS and looking to see if the return
002787    ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
002788    **
002789    ** If the shared-memory is now "reliable" return WAL_RETRY, which will
002790    ** cause the heap-memory WAL-index to be discarded and the actual
002791    ** shared memory to be used in its place.
002792    **
002793    ** This step is important because, even though this connection is holding
002794    ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
002795    ** have already checkpointed the WAL file and, while the current
002796    ** is active, wrap the WAL and start overwriting frames that this
002797    ** process wants to use.
002798    **
002799    ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
002800    ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
002801    ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
002802    ** even if some external agent does a "chmod" to make the shared-memory
002803    ** writable by us, until sqlite3OsShmUnmap() has been called.
002804    ** This is a requirement on the VFS implementation.
002805     */
002806    rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
002807    assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
002808    if( rc!=SQLITE_READONLY_CANTINIT ){
002809      rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
002810      goto begin_unreliable_shm_out;
002811    }
002812  
002813    /* We reach this point only if the real shared-memory is still unreliable.
002814    ** Assume the in-memory WAL-index substitute is correct and load it
002815    ** into pWal->hdr.
002816    */
002817    memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
002818  
002819    /* Make sure some writer hasn't come in and changed the WAL file out
002820    ** from under us, then disconnected, while we were not looking.
002821    */
002822    rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
002823    if( rc!=SQLITE_OK ){
002824      goto begin_unreliable_shm_out;
002825    }
002826    if( szWal<WAL_HDRSIZE ){
002827      /* If the wal file is too small to contain a wal-header and the
002828      ** wal-index header has mxFrame==0, then it must be safe to proceed
002829      ** reading the database file only. However, the page cache cannot
002830      ** be trusted, as a read/write connection may have connected, written
002831      ** the db, run a checkpoint, truncated the wal file and disconnected
002832      ** since this client's last read transaction.  */
002833      *pChanged = 1;
002834      rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
002835      goto begin_unreliable_shm_out;
002836    }
002837  
002838    /* Check the salt keys at the start of the wal file still match. */
002839    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
002840    if( rc!=SQLITE_OK ){
002841      goto begin_unreliable_shm_out;
002842    }
002843    if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
002844      /* Some writer has wrapped the WAL file while we were not looking.
002845      ** Return WAL_RETRY which will cause the in-memory WAL-index to be
002846      ** rebuilt. */
002847      rc = WAL_RETRY;
002848      goto begin_unreliable_shm_out;
002849    }
002850  
002851    /* Allocate a buffer to read frames into */
002852    assert( (pWal->szPage & (pWal->szPage-1))==0 );
002853    assert( pWal->szPage>=512 && pWal->szPage<=65536 );
002854    szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
002855    aFrame = (u8 *)sqlite3_malloc64(szFrame);
002856    if( aFrame==0 ){
002857      rc = SQLITE_NOMEM_BKPT;
002858      goto begin_unreliable_shm_out;
002859    }
002860    aData = &aFrame[WAL_FRAME_HDRSIZE];
002861  
002862    /* Check to see if a complete transaction has been appended to the
002863    ** wal file since the heap-memory wal-index was created. If so, the
002864    ** heap-memory wal-index is discarded and WAL_RETRY returned to
002865    ** the caller.  */
002866    aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
002867    aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
002868    for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
002869        iOffset+szFrame<=szWal;
002870        iOffset+=szFrame
002871    ){
002872      u32 pgno;                   /* Database page number for frame */
002873      u32 nTruncate;              /* dbsize field from frame header */
002874  
002875      /* Read and decode the next log frame. */
002876      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
002877      if( rc!=SQLITE_OK ) break;
002878      if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
002879  
002880      /* If nTruncate is non-zero, then a complete transaction has been
002881      ** appended to this wal file. Set rc to WAL_RETRY and break out of
002882      ** the loop.  */
002883      if( nTruncate ){
002884        rc = WAL_RETRY;
002885        break;
002886      }
002887    }
002888    pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
002889    pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
002890  
002891   begin_unreliable_shm_out:
002892    sqlite3_free(aFrame);
002893    if( rc!=SQLITE_OK ){
002894      int i;
002895      for(i=0; i<pWal->nWiData; i++){
002896        sqlite3_free((void*)pWal->apWiData[i]);
002897        pWal->apWiData[i] = 0;
002898      }
002899      pWal->bShmUnreliable = 0;
002900      sqlite3WalEndReadTransaction(pWal);
002901      *pChanged = 1;
002902    }
002903    return rc;
002904  }
002905  
002906  /*
002907  ** The final argument passed to walTryBeginRead() is of type (int*). The
002908  ** caller should invoke walTryBeginRead as follows:
002909  **
002910  **   int cnt = 0;
002911  **   do {
002912  **     rc = walTryBeginRead(..., &cnt);
002913  **   }while( rc==WAL_RETRY );
002914  **
002915  ** The final value of "cnt" is of no use to the caller. It is used by
002916  ** the implementation of walTryBeginRead() as follows:
002917  **
002918  **   + Each time walTryBeginRead() is called, it is incremented. Once
002919  **     it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead()
002920  **     has many times been invoked and failed with WAL_RETRY - walTryBeginRead()
002921  **     returns SQLITE_PROTOCOL.
002922  **
002923  **   + If SQLITE_ENABLE_SETLK_TIMEOUT is defined and walTryBeginRead() failed
002924  **     because a blocking lock timed out (SQLITE_BUSY_TIMEOUT from the OS
002925  **     layer), the WAL_RETRY_BLOCKED_MASK bit is set in "cnt". In this case
002926  **     the next invocation of walTryBeginRead() may omit an expected call to 
002927  **     sqlite3OsSleep(). There has already been a delay when the previous call
002928  **     waited on a lock.
002929  */
002930  #define WAL_RETRY_PROTOCOL_LIMIT 100
002931  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
002932  # define WAL_RETRY_BLOCKED_MASK    0x10000000
002933  #else
002934  # define WAL_RETRY_BLOCKED_MASK    0
002935  #endif
002936  
002937  /*
002938  ** Attempt to start a read transaction.  This might fail due to a race or
002939  ** other transient condition.  When that happens, it returns WAL_RETRY to
002940  ** indicate to the caller that it is safe to retry immediately.
002941  **
002942  ** On success return SQLITE_OK.  On a permanent failure (such an
002943  ** I/O error or an SQLITE_BUSY because another process is running
002944  ** recovery) return a positive error code.
002945  **
002946  ** The useWal parameter is true to force the use of the WAL and disable
002947  ** the case where the WAL is bypassed because it has been completely
002948  ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
002949  ** to make a copy of the wal-index header into pWal->hdr.  If the
002950  ** wal-index header has changed, *pChanged is set to 1 (as an indication
002951  ** to the caller that the local page cache is obsolete and needs to be
002952  ** flushed.)  When useWal==1, the wal-index header is assumed to already
002953  ** be loaded and the pChanged parameter is unused.
002954  **
002955  ** The caller must set the cnt parameter to the number of prior calls to
002956  ** this routine during the current read attempt that returned WAL_RETRY.
002957  ** This routine will start taking more aggressive measures to clear the
002958  ** race conditions after multiple WAL_RETRY returns, and after an excessive
002959  ** number of errors will ultimately return SQLITE_PROTOCOL.  The
002960  ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
002961  ** and is not honoring the locking protocol.  There is a vanishingly small
002962  ** chance that SQLITE_PROTOCOL could be returned because of a run of really
002963  ** bad luck when there is lots of contention for the wal-index, but that
002964  ** possibility is so small that it can be safely neglected, we believe.
002965  **
002966  ** On success, this routine obtains a read lock on
002967  ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
002968  ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
002969  ** that means the Wal does not hold any read lock.  The reader must not
002970  ** access any database page that is modified by a WAL frame up to and
002971  ** including frame number aReadMark[pWal->readLock].  The reader will
002972  ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
002973  ** Or if pWal->readLock==0, then the reader will ignore the WAL
002974  ** completely and get all content directly from the database file.
002975  ** If the useWal parameter is 1 then the WAL will never be ignored and
002976  ** this routine will always set pWal->readLock>0 on success.
002977  ** When the read transaction is completed, the caller must release the
002978  ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
002979  **
002980  ** This routine uses the nBackfill and aReadMark[] fields of the header
002981  ** to select a particular WAL_READ_LOCK() that strives to let the
002982  ** checkpoint process do as much work as possible.  This routine might
002983  ** update values of the aReadMark[] array in the header, but if it does
002984  ** so it takes care to hold an exclusive lock on the corresponding
002985  ** WAL_READ_LOCK() while changing values.
002986  */
002987  static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){
002988    volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
002989    u32 mxReadMark;                 /* Largest aReadMark[] value */
002990    int mxI;                        /* Index of largest aReadMark[] value */
002991    int i;                          /* Loop counter */
002992    int rc = SQLITE_OK;             /* Return code  */
002993    u32 mxFrame;                    /* Wal frame to lock to */
002994  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
002995    int nBlockTmout = 0;
002996  #endif
002997  
002998    assert( pWal->readLock<0 );     /* Not currently locked */
002999  
003000    /* useWal may only be set for read/write connections */
003001    assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
003002  
003003    /* Take steps to avoid spinning forever if there is a protocol error.
003004    **
003005    ** Circumstances that cause a RETRY should only last for the briefest
003006    ** instances of time.  No I/O or other system calls are done while the
003007    ** locks are held, so the locks should not be held for very long. But
003008    ** if we are unlucky, another process that is holding a lock might get
003009    ** paged out or take a page-fault that is time-consuming to resolve,
003010    ** during the few nanoseconds that it is holding the lock.  In that case,
003011    ** it might take longer than normal for the lock to free.
003012    **
003013    ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
003014    ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
003015    ** is more of a scheduler yield than an actual delay.  But on the 10th
003016    ** an subsequent retries, the delays start becoming longer and longer,
003017    ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
003018    ** The total delay time before giving up is less than 10 seconds.
003019    */
003020    (*pCnt)++;
003021    if( *pCnt>5 ){
003022      int nDelay = 1;                      /* Pause time in microseconds */
003023      int cnt = (*pCnt & ~WAL_RETRY_BLOCKED_MASK);
003024      if( cnt>WAL_RETRY_PROTOCOL_LIMIT ){
003025        VVA_ONLY( pWal->lockError = 1; )
003026        return SQLITE_PROTOCOL;
003027      }
003028      if( *pCnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
003029  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
003030      /* In SQLITE_ENABLE_SETLK_TIMEOUT builds, configure the file-descriptor
003031      ** to block for locks for approximately nDelay us. This affects three
003032      ** locks: (a) the shared lock taken on the DMS slot in os_unix.c (if
003033      ** using os_unix.c), (b) the WRITER lock taken in walIndexReadHdr() if the
003034      ** first attempted read fails, and (c) the shared lock taken on the 
003035      ** read-mark.  
003036      **
003037      ** If the previous call failed due to an SQLITE_BUSY_TIMEOUT error,
003038      ** then sleep for the minimum of 1us. The previous call already provided 
003039      ** an extra delay while it was blocking on the lock.
003040      */
003041      nBlockTmout = (nDelay+998) / 1000;
003042      if( !useWal && walEnableBlockingMs(pWal, nBlockTmout) ){
003043        if( *pCnt & WAL_RETRY_BLOCKED_MASK ) nDelay = 1;
003044      }
003045  #endif
003046      sqlite3OsSleep(pWal->pVfs, nDelay);
003047      *pCnt &= ~WAL_RETRY_BLOCKED_MASK;
003048    }
003049  
003050    if( !useWal ){
003051      assert( rc==SQLITE_OK );
003052      if( pWal->bShmUnreliable==0 ){
003053        rc = walIndexReadHdr(pWal, pChanged);
003054      }
003055  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
003056      walDisableBlocking(pWal);
003057      if( rc==SQLITE_BUSY_TIMEOUT ){
003058        rc = SQLITE_BUSY;
003059        *pCnt |= WAL_RETRY_BLOCKED_MASK;
003060      }
003061  #endif
003062      if( rc==SQLITE_BUSY ){
003063        /* If there is not a recovery running in another thread or process
003064        ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
003065        ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
003066        ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
003067        ** would be technically correct.  But the race is benign since with
003068        ** WAL_RETRY this routine will be called again and will probably be
003069        ** right on the second iteration.
003070        */
003071        if( pWal->apWiData[0]==0 ){
003072          /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
003073          ** We assume this is a transient condition, so return WAL_RETRY. The
003074          ** xShmMap() implementation used by the default unix and win32 VFS
003075          ** modules may return SQLITE_BUSY due to a race condition in the
003076          ** code that determines whether or not the shared-memory region
003077          ** must be zeroed before the requested page is returned.
003078          */
003079          rc = WAL_RETRY;
003080        }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
003081          walUnlockShared(pWal, WAL_RECOVER_LOCK);
003082          rc = WAL_RETRY;
003083        }else if( rc==SQLITE_BUSY ){
003084          rc = SQLITE_BUSY_RECOVERY;
003085        }
003086      }
003087      if( rc!=SQLITE_OK ){
003088        return rc;
003089      }
003090      else if( pWal->bShmUnreliable ){
003091        return walBeginShmUnreliable(pWal, pChanged);
003092      }
003093    }
003094  
003095    assert( pWal->nWiData>0 );
003096    assert( pWal->apWiData[0]!=0 );
003097    pInfo = walCkptInfo(pWal);
003098    SEH_INJECT_FAULT;
003099    if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
003100  #ifdef SQLITE_ENABLE_SNAPSHOT
003101     && ((pWal->bGetSnapshot==0 && pWal->pSnapshot==0) || pWal->hdr.mxFrame==0)
003102  #endif
003103    ){
003104      /* The WAL has been completely backfilled (or it is empty).
003105      ** and can be safely ignored.
003106      */
003107      rc = walLockShared(pWal, WAL_READ_LOCK(0));
003108      walShmBarrier(pWal);
003109      if( rc==SQLITE_OK ){
003110        if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
003111          /* It is not safe to allow the reader to continue here if frames
003112          ** may have been appended to the log before READ_LOCK(0) was obtained.
003113          ** When holding READ_LOCK(0), the reader ignores the entire log file,
003114          ** which implies that the database file contains a trustworthy
003115          ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
003116          ** happening, this is usually correct.
003117          **
003118          ** However, if frames have been appended to the log (or if the log
003119          ** is wrapped and written for that matter) before the READ_LOCK(0)
003120          ** is obtained, that is not necessarily true. A checkpointer may
003121          ** have started to backfill the appended frames but crashed before
003122          ** it finished. Leaving a corrupt image in the database file.
003123          */
003124          walUnlockShared(pWal, WAL_READ_LOCK(0));
003125          return WAL_RETRY;
003126        }
003127        pWal->readLock = 0;
003128        return SQLITE_OK;
003129      }else if( rc!=SQLITE_BUSY ){
003130        return rc;
003131      }
003132    }
003133  
003134    /* If we get this far, it means that the reader will want to use
003135    ** the WAL to get at content from recent commits.  The job now is
003136    ** to select one of the aReadMark[] entries that is closest to
003137    ** but not exceeding pWal->hdr.mxFrame and lock that entry.
003138    */
003139    mxReadMark = 0;
003140    mxI = 0;
003141    mxFrame = pWal->hdr.mxFrame;
003142  #ifdef SQLITE_ENABLE_SNAPSHOT
003143    if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
003144      mxFrame = pWal->pSnapshot->mxFrame;
003145    }
003146  #endif
003147    for(i=1; i<WAL_NREADER; i++){
003148      u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
003149      if( mxReadMark<=thisMark && thisMark<=mxFrame ){
003150        assert( thisMark!=READMARK_NOT_USED );
003151        mxReadMark = thisMark;
003152        mxI = i;
003153      }
003154    }
003155    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
003156     && (mxReadMark<mxFrame || mxI==0)
003157    ){
003158      for(i=1; i<WAL_NREADER; i++){
003159        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
003160        if( rc==SQLITE_OK ){
003161          AtomicStore(pInfo->aReadMark+i,mxFrame);
003162          mxReadMark = mxFrame;
003163          mxI = i;
003164          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
003165          break;
003166        }else if( rc!=SQLITE_BUSY ){
003167          return rc;
003168        }
003169      }
003170    }
003171    if( mxI==0 ){
003172      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
003173      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
003174    }
003175  
003176    (void)walEnableBlockingMs(pWal, nBlockTmout);
003177    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
003178    walDisableBlocking(pWal);
003179    if( rc ){
003180  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
003181      if( rc==SQLITE_BUSY_TIMEOUT ){
003182        *pCnt |= WAL_RETRY_BLOCKED_MASK;
003183      }
003184  #else
003185      assert( rc!=SQLITE_BUSY_TIMEOUT );
003186  #endif
003187      assert( (rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT );
003188      return (rc&0xFF)==SQLITE_BUSY ? WAL_RETRY : rc;
003189    }
003190    /* Now that the read-lock has been obtained, check that neither the
003191    ** value in the aReadMark[] array or the contents of the wal-index
003192    ** header have changed.
003193    **
003194    ** It is necessary to check that the wal-index header did not change
003195    ** between the time it was read and when the shared-lock was obtained
003196    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
003197    ** that the log file may have been wrapped by a writer, or that frames
003198    ** that occur later in the log than pWal->hdr.mxFrame may have been
003199    ** copied into the database by a checkpointer. If either of these things
003200    ** happened, then reading the database with the current value of
003201    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
003202    ** instead.
003203    **
003204    ** Before checking that the live wal-index header has not changed
003205    ** since it was read, set Wal.minFrame to the first frame in the wal
003206    ** file that has not yet been checkpointed. This client will not need
003207    ** to read any frames earlier than minFrame from the wal file - they
003208    ** can be safely read directly from the database file.
003209    **
003210    ** Because a ShmBarrier() call is made between taking the copy of
003211    ** nBackfill and checking that the wal-header in shared-memory still
003212    ** matches the one cached in pWal->hdr, it is guaranteed that the
003213    ** checkpointer that set nBackfill was not working with a wal-index
003214    ** header newer than that cached in pWal->hdr. If it were, that could
003215    ** cause a problem. The checkpointer could omit to checkpoint
003216    ** a version of page X that lies before pWal->minFrame (call that version
003217    ** A) on the basis that there is a newer version (version B) of the same
003218    ** page later in the wal file. But if version B happens to like past
003219    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
003220    ** that it can read version A from the database file. However, since
003221    ** we can guarantee that the checkpointer that set nBackfill could not
003222    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
003223    */
003224    pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT;
003225    walShmBarrier(pWal);
003226    if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
003227     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
003228    ){
003229      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
003230      return WAL_RETRY;
003231    }else{
003232      assert( mxReadMark<=pWal->hdr.mxFrame );
003233      pWal->readLock = (i16)mxI;
003234    }
003235    return rc;
003236  }
003237  
003238  #ifdef SQLITE_ENABLE_SNAPSHOT
003239  /*
003240  ** This function does the work of sqlite3WalSnapshotRecover().
003241  */
003242  static int walSnapshotRecover(
003243    Wal *pWal,                      /* WAL handle */
003244    void *pBuf1,                    /* Temp buffer pWal->szPage bytes in size */
003245    void *pBuf2                     /* Temp buffer pWal->szPage bytes in size */
003246  ){
003247    int szPage = (int)pWal->szPage;
003248    int rc;
003249    i64 szDb;                       /* Size of db file in bytes */
003250  
003251    rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
003252    if( rc==SQLITE_OK ){
003253      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
003254      u32 i = pInfo->nBackfillAttempted;
003255      for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
003256        WalHashLoc sLoc;          /* Hash table location */
003257        u32 pgno;                 /* Page number in db file */
003258        i64 iDbOff;               /* Offset of db file entry */
003259        i64 iWalOff;              /* Offset of wal file entry */
003260  
003261        rc = walHashGet(pWal, walFramePage(i), &sLoc);
003262        if( rc!=SQLITE_OK ) break;
003263        assert( i - sLoc.iZero - 1 >=0 );
003264        pgno = sLoc.aPgno[i-sLoc.iZero-1];
003265        iDbOff = (i64)(pgno-1) * szPage;
003266  
003267        if( iDbOff+szPage<=szDb ){
003268          iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
003269          rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
003270  
003271          if( rc==SQLITE_OK ){
003272            rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
003273          }
003274  
003275          if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
003276            break;
003277          }
003278        }
003279  
003280        pInfo->nBackfillAttempted = i-1;
003281      }
003282    }
003283  
003284    return rc;
003285  }
003286  
003287  /*
003288  ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
003289  ** variable so that older snapshots can be accessed. To do this, loop
003290  ** through all wal frames from nBackfillAttempted to (nBackfill+1),
003291  ** comparing their content to the corresponding page with the database
003292  ** file, if any. Set nBackfillAttempted to the frame number of the
003293  ** first frame for which the wal file content matches the db file.
003294  **
003295  ** This is only really safe if the file-system is such that any page
003296  ** writes made by earlier checkpointers were atomic operations, which
003297  ** is not always true. It is also possible that nBackfillAttempted
003298  ** may be left set to a value larger than expected, if a wal frame
003299  ** contains content that duplicate of an earlier version of the same
003300  ** page.
003301  **
003302  ** SQLITE_OK is returned if successful, or an SQLite error code if an
003303  ** error occurs. It is not an error if nBackfillAttempted cannot be
003304  ** decreased at all.
003305  */
003306  int sqlite3WalSnapshotRecover(Wal *pWal){
003307    int rc;
003308  
003309    assert( pWal->readLock>=0 );
003310    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
003311    if( rc==SQLITE_OK ){
003312      void *pBuf1 = sqlite3_malloc(pWal->szPage);
003313      void *pBuf2 = sqlite3_malloc(pWal->szPage);
003314      if( pBuf1==0 || pBuf2==0 ){
003315        rc = SQLITE_NOMEM;
003316      }else{
003317        pWal->ckptLock = 1;
003318        SEH_TRY {
003319          rc = walSnapshotRecover(pWal, pBuf1, pBuf2);
003320        }
003321        SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003322        pWal->ckptLock = 0;
003323      }
003324  
003325      sqlite3_free(pBuf1);
003326      sqlite3_free(pBuf2);
003327      walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
003328    }
003329  
003330    return rc;
003331  }
003332  #endif /* SQLITE_ENABLE_SNAPSHOT */
003333  
003334  /*
003335  ** This function does the work of sqlite3WalBeginReadTransaction() (see 
003336  ** below). That function simply calls this one inside an SEH_TRY{...} block.
003337  */
003338  static int walBeginReadTransaction(Wal *pWal, int *pChanged){
003339    int rc;                         /* Return code */
003340    int cnt = 0;                    /* Number of TryBeginRead attempts */
003341  #ifdef SQLITE_ENABLE_SNAPSHOT
003342    int ckptLock = 0;
003343    int bChanged = 0;
003344    WalIndexHdr *pSnapshot = pWal->pSnapshot;
003345  #endif
003346  
003347    assert( pWal->ckptLock==0 );
003348    assert( pWal->nSehTry>0 );
003349  
003350  #ifdef SQLITE_ENABLE_SNAPSHOT
003351    if( pSnapshot ){
003352      if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
003353        bChanged = 1;
003354      }
003355  
003356      /* It is possible that there is a checkpointer thread running
003357      ** concurrent with this code. If this is the case, it may be that the
003358      ** checkpointer has already determined that it will checkpoint
003359      ** snapshot X, where X is later in the wal file than pSnapshot, but
003360      ** has not yet set the pInfo->nBackfillAttempted variable to indicate
003361      ** its intent. To avoid the race condition this leads to, ensure that
003362      ** there is no checkpointer process by taking a shared CKPT lock
003363      ** before checking pInfo->nBackfillAttempted.  */
003364      (void)walEnableBlocking(pWal);
003365      rc = walLockShared(pWal, WAL_CKPT_LOCK);
003366      walDisableBlocking(pWal);
003367  
003368      if( rc!=SQLITE_OK ){
003369        return rc;
003370      }
003371      ckptLock = 1;
003372    }
003373  #endif
003374  
003375    do{
003376      rc = walTryBeginRead(pWal, pChanged, 0, &cnt);
003377    }while( rc==WAL_RETRY );
003378    testcase( (rc&0xff)==SQLITE_BUSY );
003379    testcase( (rc&0xff)==SQLITE_IOERR );
003380    testcase( rc==SQLITE_PROTOCOL );
003381    testcase( rc==SQLITE_OK );
003382  
003383  #ifdef SQLITE_ENABLE_SNAPSHOT
003384    if( rc==SQLITE_OK ){
003385      if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
003386        /* At this point the client has a lock on an aReadMark[] slot holding
003387        ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
003388        ** is populated with the wal-index header corresponding to the head
003389        ** of the wal file. Verify that pSnapshot is still valid before
003390        ** continuing.  Reasons why pSnapshot might no longer be valid:
003391        **
003392        **    (1)  The WAL file has been reset since the snapshot was taken.
003393        **         In this case, the salt will have changed.
003394        **
003395        **    (2)  A checkpoint as been attempted that wrote frames past
003396        **         pSnapshot->mxFrame into the database file.  Note that the
003397        **         checkpoint need not have completed for this to cause problems.
003398        */
003399        volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
003400  
003401        assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
003402        assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
003403  
003404        /* Check that the wal file has not been wrapped. Assuming that it has
003405        ** not, also check that no checkpointer has attempted to checkpoint any
003406        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
003407        ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
003408        ** with *pSnapshot and set *pChanged as appropriate for opening the
003409        ** snapshot.  */
003410        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
003411         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
003412        ){
003413          assert( pWal->readLock>0 );
003414          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
003415          *pChanged = bChanged;
003416        }else{
003417          rc = SQLITE_ERROR_SNAPSHOT;
003418        }
003419  
003420        /* A client using a non-current snapshot may not ignore any frames
003421        ** from the start of the wal file. This is because, for a system
003422        ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
003423        ** have omitted to checkpoint a frame earlier than minFrame in
003424        ** the file because there exists a frame after iSnapshot that
003425        ** is the same database page.  */
003426        pWal->minFrame = 1;
003427  
003428        if( rc!=SQLITE_OK ){
003429          sqlite3WalEndReadTransaction(pWal);
003430        }
003431      }
003432    }
003433  
003434    /* Release the shared CKPT lock obtained above. */
003435    if( ckptLock ){
003436      assert( pSnapshot );
003437      walUnlockShared(pWal, WAL_CKPT_LOCK);
003438    }
003439  #endif
003440    return rc;
003441  }
003442  
003443  /*
003444  ** Begin a read transaction on the database.
003445  **
003446  ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
003447  ** it takes a snapshot of the state of the WAL and wal-index for the current
003448  ** instant in time.  The current thread will continue to use this snapshot.
003449  ** Other threads might append new content to the WAL and wal-index but
003450  ** that extra content is ignored by the current thread.
003451  **
003452  ** If the database contents have changes since the previous read
003453  ** transaction, then *pChanged is set to 1 before returning.  The
003454  ** Pager layer will use this to know that its cache is stale and
003455  ** needs to be flushed.
003456  */
003457  int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
003458    int rc;
003459    SEH_TRY {
003460      rc = walBeginReadTransaction(pWal, pChanged);
003461    }
003462    SEH_EXCEPT( rc = walHandleException(pWal); )
003463    return rc;
003464  }
003465  
003466  /*
003467  ** Finish with a read transaction.  All this does is release the
003468  ** read-lock.
003469  */
003470  void sqlite3WalEndReadTransaction(Wal *pWal){
003471    sqlite3WalEndWriteTransaction(pWal);
003472    if( pWal->readLock>=0 ){
003473      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
003474      pWal->readLock = -1;
003475    }
003476  }
003477  
003478  /*
003479  ** Search the wal file for page pgno. If found, set *piRead to the frame that
003480  ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
003481  ** to zero.
003482  **
003483  ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
003484  ** error does occur, the final value of *piRead is undefined.
003485  */
003486  static int walFindFrame(
003487    Wal *pWal,                      /* WAL handle */
003488    Pgno pgno,                      /* Database page number to read data for */
003489    u32 *piRead                     /* OUT: Frame number (or zero) */
003490  ){
003491    u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
003492    u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
003493    int iHash;                      /* Used to loop through N hash tables */
003494    int iMinHash;
003495  
003496    /* This routine is only be called from within a read transaction. */
003497    assert( pWal->readLock>=0 || pWal->lockError );
003498  
003499    /* If the "last page" field of the wal-index header snapshot is 0, then
003500    ** no data will be read from the wal under any circumstances. Return early
003501    ** in this case as an optimization.  Likewise, if pWal->readLock==0,
003502    ** then the WAL is ignored by the reader so return early, as if the
003503    ** WAL were empty.
003504    */
003505    if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
003506      *piRead = 0;
003507      return SQLITE_OK;
003508    }
003509  
003510    /* Search the hash table or tables for an entry matching page number
003511    ** pgno. Each iteration of the following for() loop searches one
003512    ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
003513    **
003514    ** This code might run concurrently to the code in walIndexAppend()
003515    ** that adds entries to the wal-index (and possibly to this hash
003516    ** table). This means the value just read from the hash
003517    ** slot (aHash[iKey]) may have been added before or after the
003518    ** current read transaction was opened. Values added after the
003519    ** read transaction was opened may have been written incorrectly -
003520    ** i.e. these slots may contain garbage data. However, we assume
003521    ** that any slots written before the current read transaction was
003522    ** opened remain unmodified.
003523    **
003524    ** For the reasons above, the if(...) condition featured in the inner
003525    ** loop of the following block is more stringent that would be required
003526    ** if we had exclusive access to the hash-table:
003527    **
003528    **   (aPgno[iFrame]==pgno):
003529    **     This condition filters out normal hash-table collisions.
003530    **
003531    **   (iFrame<=iLast):
003532    **     This condition filters out entries that were added to the hash
003533    **     table after the current read-transaction had started.
003534    */
003535    iMinHash = walFramePage(pWal->minFrame);
003536    for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
003537      WalHashLoc sLoc;              /* Hash table location */
003538      int iKey;                     /* Hash slot index */
003539      int nCollide;                 /* Number of hash collisions remaining */
003540      int rc;                       /* Error code */
003541      u32 iH;
003542  
003543      rc = walHashGet(pWal, iHash, &sLoc);
003544      if( rc!=SQLITE_OK ){
003545        return rc;
003546      }
003547      nCollide = HASHTABLE_NSLOT;
003548      iKey = walHash(pgno);
003549      SEH_INJECT_FAULT;
003550      while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
003551        u32 iFrame = iH + sLoc.iZero;
003552        if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
003553          assert( iFrame>iRead || CORRUPT_DB );
003554          iRead = iFrame;
003555        }
003556        if( (nCollide--)==0 ){
003557          *piRead = 0;
003558          return SQLITE_CORRUPT_BKPT;
003559        }
003560        iKey = walNextHash(iKey);
003561      }
003562      if( iRead ) break;
003563    }
003564  
003565  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
003566    /* If expensive assert() statements are available, do a linear search
003567    ** of the wal-index file content. Make sure the results agree with the
003568    ** result obtained using the hash indexes above.  */
003569    {
003570      u32 iRead2 = 0;
003571      u32 iTest;
003572      assert( pWal->bShmUnreliable || pWal->minFrame>0 );
003573      for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
003574        if( walFramePgno(pWal, iTest)==pgno ){
003575          iRead2 = iTest;
003576          break;
003577        }
003578      }
003579      assert( iRead==iRead2 );
003580    }
003581  #endif
003582  
003583    *piRead = iRead;
003584    return SQLITE_OK;
003585  }
003586  
003587  /*
003588  ** Search the wal file for page pgno. If found, set *piRead to the frame that
003589  ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
003590  ** to zero.
003591  **
003592  ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
003593  ** error does occur, the final value of *piRead is undefined.
003594  **
003595  ** The difference between this function and walFindFrame() is that this
003596  ** function wraps walFindFrame() in an SEH_TRY{...} block.
003597  */
003598  int sqlite3WalFindFrame(
003599    Wal *pWal,                      /* WAL handle */
003600    Pgno pgno,                      /* Database page number to read data for */
003601    u32 *piRead                     /* OUT: Frame number (or zero) */
003602  ){
003603    int rc;
003604    SEH_TRY {
003605      rc = walFindFrame(pWal, pgno, piRead);
003606    }
003607    SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003608    return rc;
003609  }
003610  
003611  /*
003612  ** Read the contents of frame iRead from the wal file into buffer pOut
003613  ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
003614  ** error code otherwise.
003615  */
003616  int sqlite3WalReadFrame(
003617    Wal *pWal,                      /* WAL handle */
003618    u32 iRead,                      /* Frame to read */
003619    int nOut,                       /* Size of buffer pOut in bytes */
003620    u8 *pOut                        /* Buffer to write page data to */
003621  ){
003622    int sz;
003623    i64 iOffset;
003624    sz = pWal->hdr.szPage;
003625    sz = (sz&0xfe00) + ((sz&0x0001)<<16);
003626    testcase( sz<=32768 );
003627    testcase( sz>=65536 );
003628    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
003629    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
003630    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
003631  }
003632  
003633  /*
003634  ** Return the size of the database in pages (or zero, if unknown).
003635  */
003636  Pgno sqlite3WalDbsize(Wal *pWal){
003637    if( pWal && ALWAYS(pWal->readLock>=0) ){
003638      return pWal->hdr.nPage;
003639    }
003640    return 0;
003641  }
003642  
003643  
003644  /*
003645  ** This function starts a write transaction on the WAL.
003646  **
003647  ** A read transaction must have already been started by a prior call
003648  ** to sqlite3WalBeginReadTransaction().
003649  **
003650  ** If another thread or process has written into the database since
003651  ** the read transaction was started, then it is not possible for this
003652  ** thread to write as doing so would cause a fork.  So this routine
003653  ** returns SQLITE_BUSY in that case and no write transaction is started.
003654  **
003655  ** There can only be a single writer active at a time.
003656  */
003657  int sqlite3WalBeginWriteTransaction(Wal *pWal){
003658    int rc;
003659  
003660  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
003661    /* If the write-lock is already held, then it was obtained before the
003662    ** read-transaction was even opened, making this call a no-op.
003663    ** Return early. */
003664    if( pWal->writeLock ){
003665      assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
003666      return SQLITE_OK;
003667    }
003668  #endif
003669  
003670    /* Cannot start a write transaction without first holding a read
003671    ** transaction. */
003672    assert( pWal->readLock>=0 );
003673    assert( pWal->writeLock==0 && pWal->iReCksum==0 );
003674  
003675    if( pWal->readOnly ){
003676      return SQLITE_READONLY;
003677    }
003678  
003679    /* Only one writer allowed at a time.  Get the write lock.  Return
003680    ** SQLITE_BUSY if unable.
003681    */
003682    rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
003683    if( rc ){
003684      return rc;
003685    }
003686    pWal->writeLock = 1;
003687  
003688    /* If another connection has written to the database file since the
003689    ** time the read transaction on this connection was started, then
003690    ** the write is disallowed.
003691    */
003692    SEH_TRY {
003693      if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
003694        rc = SQLITE_BUSY_SNAPSHOT;
003695      }
003696    }
003697    SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003698  
003699    if( rc!=SQLITE_OK ){
003700      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
003701      pWal->writeLock = 0;
003702    }
003703    return rc;
003704  }
003705  
003706  /*
003707  ** End a write transaction.  The commit has already been done.  This
003708  ** routine merely releases the lock.
003709  */
003710  int sqlite3WalEndWriteTransaction(Wal *pWal){
003711    if( pWal->writeLock ){
003712      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
003713      pWal->writeLock = 0;
003714      pWal->iReCksum = 0;
003715      pWal->truncateOnCommit = 0;
003716    }
003717    return SQLITE_OK;
003718  }
003719  
003720  /*
003721  ** If any data has been written (but not committed) to the log file, this
003722  ** function moves the write-pointer back to the start of the transaction.
003723  **
003724  ** Additionally, the callback function is invoked for each frame written
003725  ** to the WAL since the start of the transaction. If the callback returns
003726  ** other than SQLITE_OK, it is not invoked again and the error code is
003727  ** returned to the caller.
003728  **
003729  ** Otherwise, if the callback function does not return an error, this
003730  ** function returns SQLITE_OK.
003731  */
003732  int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
003733    int rc = SQLITE_OK;
003734    if( ALWAYS(pWal->writeLock) ){
003735      Pgno iMax = pWal->hdr.mxFrame;
003736      Pgno iFrame;
003737  
003738      SEH_TRY {
003739        /* Restore the clients cache of the wal-index header to the state it
003740        ** was in before the client began writing to the database. 
003741        */
003742        memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
003743    
003744        for(iFrame=pWal->hdr.mxFrame+1; 
003745            ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
003746            iFrame++
003747        ){
003748          /* This call cannot fail. Unless the page for which the page number
003749          ** is passed as the second argument is (a) in the cache and
003750          ** (b) has an outstanding reference, then xUndo is either a no-op
003751          ** (if (a) is false) or simply expels the page from the cache (if (b)
003752          ** is false).
003753          **
003754          ** If the upper layer is doing a rollback, it is guaranteed that there
003755          ** are no outstanding references to any page other than page 1. And
003756          ** page 1 is never written to the log until the transaction is
003757          ** committed. As a result, the call to xUndo may not fail.
003758          */
003759          assert( walFramePgno(pWal, iFrame)!=1 );
003760          rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
003761        }
003762        if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
003763      }
003764      SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003765    }
003766    return rc;
003767  }
003768  
003769  /*
003770  ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
003771  ** values. This function populates the array with values required to
003772  ** "rollback" the write position of the WAL handle back to the current
003773  ** point in the event of a savepoint rollback (via WalSavepointUndo()).
003774  */
003775  void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
003776    assert( pWal->writeLock );
003777    aWalData[0] = pWal->hdr.mxFrame;
003778    aWalData[1] = pWal->hdr.aFrameCksum[0];
003779    aWalData[2] = pWal->hdr.aFrameCksum[1];
003780    aWalData[3] = pWal->nCkpt;
003781  }
003782  
003783  /*
003784  ** Move the write position of the WAL back to the point identified by
003785  ** the values in the aWalData[] array. aWalData must point to an array
003786  ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
003787  ** by a call to WalSavepoint().
003788  */
003789  int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
003790    int rc = SQLITE_OK;
003791  
003792    assert( pWal->writeLock );
003793    assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
003794  
003795    if( aWalData[3]!=pWal->nCkpt ){
003796      /* This savepoint was opened immediately after the write-transaction
003797      ** was started. Right after that, the writer decided to wrap around
003798      ** to the start of the log. Update the savepoint values to match.
003799      */
003800      aWalData[0] = 0;
003801      aWalData[3] = pWal->nCkpt;
003802    }
003803  
003804    if( aWalData[0]<pWal->hdr.mxFrame ){
003805      pWal->hdr.mxFrame = aWalData[0];
003806      pWal->hdr.aFrameCksum[0] = aWalData[1];
003807      pWal->hdr.aFrameCksum[1] = aWalData[2];
003808      SEH_TRY {
003809        walCleanupHash(pWal);
003810      }
003811      SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003812    }
003813  
003814    return rc;
003815  }
003816  
003817  /*
003818  ** This function is called just before writing a set of frames to the log
003819  ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
003820  ** to the current log file, it is possible to overwrite the start of the
003821  ** existing log file with the new frames (i.e. "reset" the log). If so,
003822  ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
003823  ** unchanged.
003824  **
003825  ** SQLITE_OK is returned if no error is encountered (regardless of whether
003826  ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
003827  ** if an error occurs.
003828  */
003829  static int walRestartLog(Wal *pWal){
003830    int rc = SQLITE_OK;
003831    int cnt;
003832  
003833    if( pWal->readLock==0 ){
003834      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
003835      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
003836      if( pInfo->nBackfill>0 ){
003837        u32 salt1;
003838        sqlite3_randomness(4, &salt1);
003839        rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
003840        if( rc==SQLITE_OK ){
003841          /* If all readers are using WAL_READ_LOCK(0) (in other words if no
003842          ** readers are currently using the WAL), then the transactions
003843          ** frames will overwrite the start of the existing log. Update the
003844          ** wal-index header to reflect this.
003845          **
003846          ** In theory it would be Ok to update the cache of the header only
003847          ** at this point. But updating the actual wal-index header is also
003848          ** safe and means there is no special case for sqlite3WalUndo()
003849          ** to handle if this transaction is rolled back.  */
003850          walRestartHdr(pWal, salt1);
003851          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
003852        }else if( rc!=SQLITE_BUSY ){
003853          return rc;
003854        }
003855      }
003856      walUnlockShared(pWal, WAL_READ_LOCK(0));
003857      pWal->readLock = -1;
003858      cnt = 0;
003859      do{
003860        int notUsed;
003861        rc = walTryBeginRead(pWal, &notUsed, 1, &cnt);
003862      }while( rc==WAL_RETRY );
003863      assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
003864      testcase( (rc&0xff)==SQLITE_IOERR );
003865      testcase( rc==SQLITE_PROTOCOL );
003866      testcase( rc==SQLITE_OK );
003867    }
003868    return rc;
003869  }
003870  
003871  /*
003872  ** Information about the current state of the WAL file and where
003873  ** the next fsync should occur - passed from sqlite3WalFrames() into
003874  ** walWriteToLog().
003875  */
003876  typedef struct WalWriter {
003877    Wal *pWal;                   /* The complete WAL information */
003878    sqlite3_file *pFd;           /* The WAL file to which we write */
003879    sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
003880    int syncFlags;               /* Flags for the fsync */
003881    int szPage;                  /* Size of one page */
003882  } WalWriter;
003883  
003884  /*
003885  ** Write iAmt bytes of content into the WAL file beginning at iOffset.
003886  ** Do a sync when crossing the p->iSyncPoint boundary.
003887  **
003888  ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
003889  ** first write the part before iSyncPoint, then sync, then write the
003890  ** rest.
003891  */
003892  static int walWriteToLog(
003893    WalWriter *p,              /* WAL to write to */
003894    void *pContent,            /* Content to be written */
003895    int iAmt,                  /* Number of bytes to write */
003896    sqlite3_int64 iOffset      /* Start writing at this offset */
003897  ){
003898    int rc;
003899    if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
003900      int iFirstAmt = (int)(p->iSyncPoint - iOffset);
003901      rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
003902      if( rc ) return rc;
003903      iOffset += iFirstAmt;
003904      iAmt -= iFirstAmt;
003905      pContent = (void*)(iFirstAmt + (char*)pContent);
003906      assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
003907      rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
003908      if( iAmt==0 || rc ) return rc;
003909    }
003910    rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
003911    return rc;
003912  }
003913  
003914  /*
003915  ** Write out a single frame of the WAL
003916  */
003917  static int walWriteOneFrame(
003918    WalWriter *p,               /* Where to write the frame */
003919    PgHdr *pPage,               /* The page of the frame to be written */
003920    int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
003921    sqlite3_int64 iOffset       /* Byte offset at which to write */
003922  ){
003923    int rc;                         /* Result code from subfunctions */
003924    void *pData;                    /* Data actually written */
003925    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
003926    pData = pPage->pData;
003927    walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
003928    rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
003929    if( rc ) return rc;
003930    /* Write the page data */
003931    rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
003932    return rc;
003933  }
003934  
003935  /*
003936  ** This function is called as part of committing a transaction within which
003937  ** one or more frames have been overwritten. It updates the checksums for
003938  ** all frames written to the wal file by the current transaction starting
003939  ** with the earliest to have been overwritten.
003940  **
003941  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
003942  */
003943  static int walRewriteChecksums(Wal *pWal, u32 iLast){
003944    const int szPage = pWal->szPage;/* Database page size */
003945    int rc = SQLITE_OK;             /* Return code */
003946    u8 *aBuf;                       /* Buffer to load data from wal file into */
003947    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
003948    u32 iRead;                      /* Next frame to read from wal file */
003949    i64 iCksumOff;
003950  
003951    aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
003952    if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
003953  
003954    /* Find the checksum values to use as input for the recalculating the
003955    ** first checksum. If the first frame is frame 1 (implying that the current
003956    ** transaction restarted the wal file), these values must be read from the
003957    ** wal-file header. Otherwise, read them from the frame header of the
003958    ** previous frame.  */
003959    assert( pWal->iReCksum>0 );
003960    if( pWal->iReCksum==1 ){
003961      iCksumOff = 24;
003962    }else{
003963      iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
003964    }
003965    rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
003966    pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
003967    pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
003968  
003969    iRead = pWal->iReCksum;
003970    pWal->iReCksum = 0;
003971    for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
003972      i64 iOff = walFrameOffset(iRead, szPage);
003973      rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
003974      if( rc==SQLITE_OK ){
003975        u32 iPgno, nDbSize;
003976        iPgno = sqlite3Get4byte(aBuf);
003977        nDbSize = sqlite3Get4byte(&aBuf[4]);
003978  
003979        walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
003980        rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
003981      }
003982    }
003983  
003984    sqlite3_free(aBuf);
003985    return rc;
003986  }
003987  
003988  /*
003989  ** Write a set of frames to the log. The caller must hold the write-lock
003990  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
003991  */
003992  static int walFrames(
003993    Wal *pWal,                      /* Wal handle to write to */
003994    int szPage,                     /* Database page-size in bytes */
003995    PgHdr *pList,                   /* List of dirty pages to write */
003996    Pgno nTruncate,                 /* Database size after this commit */
003997    int isCommit,                   /* True if this is a commit */
003998    int sync_flags                  /* Flags to pass to OsSync() (or 0) */
003999  ){
004000    int rc;                         /* Used to catch return codes */
004001    u32 iFrame;                     /* Next frame address */
004002    PgHdr *p;                       /* Iterator to run through pList with. */
004003    PgHdr *pLast = 0;               /* Last frame in list */
004004    int nExtra = 0;                 /* Number of extra copies of last page */
004005    int szFrame;                    /* The size of a single frame */
004006    i64 iOffset;                    /* Next byte to write in WAL file */
004007    WalWriter w;                    /* The writer */
004008    u32 iFirst = 0;                 /* First frame that may be overwritten */
004009    WalIndexHdr *pLive;             /* Pointer to shared header */
004010  
004011    assert( pList );
004012    assert( pWal->writeLock );
004013  
004014    /* If this frame set completes a transaction, then nTruncate>0.  If
004015    ** nTruncate==0 then this frame set does not complete the transaction. */
004016    assert( (isCommit!=0)==(nTruncate!=0) );
004017  
004018  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
004019    { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
004020      WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
004021                pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
004022    }
004023  #endif
004024  
004025    pLive = (WalIndexHdr*)walIndexHdr(pWal);
004026    if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
004027      iFirst = pLive->mxFrame+1;
004028    }
004029  
004030    /* See if it is possible to write these frames into the start of the
004031    ** log file, instead of appending to it at pWal->hdr.mxFrame.
004032    */
004033    if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
004034      return rc;
004035    }
004036  
004037    /* If this is the first frame written into the log, write the WAL
004038    ** header to the start of the WAL file. See comments at the top of
004039    ** this source file for a description of the WAL header format.
004040    */
004041    iFrame = pWal->hdr.mxFrame;
004042    if( iFrame==0 ){
004043      u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
004044      u32 aCksum[2];                /* Checksum for wal-header */
004045  
004046      sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
004047      sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
004048      sqlite3Put4byte(&aWalHdr[8], szPage);
004049      sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
004050      if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
004051      memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
004052      walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
004053      sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
004054      sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
004055  
004056      pWal->szPage = szPage;
004057      pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
004058      pWal->hdr.aFrameCksum[0] = aCksum[0];
004059      pWal->hdr.aFrameCksum[1] = aCksum[1];
004060      pWal->truncateOnCommit = 1;
004061  
004062      rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
004063      WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
004064      if( rc!=SQLITE_OK ){
004065        return rc;
004066      }
004067  
004068      /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
004069      ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
004070      ** an out-of-order write following a WAL restart could result in
004071      ** database corruption.  See the ticket:
004072      **
004073      **     https://sqlite.org/src/info/ff5be73dee
004074      */
004075      if( pWal->syncHeader ){
004076        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
004077        if( rc ) return rc;
004078      }
004079    }
004080    if( (int)pWal->szPage!=szPage ){
004081      return SQLITE_CORRUPT_BKPT;  /* TH3 test case: cov1/corrupt155.test */
004082    }
004083  
004084    /* Setup information needed to write frames into the WAL */
004085    w.pWal = pWal;
004086    w.pFd = pWal->pWalFd;
004087    w.iSyncPoint = 0;
004088    w.syncFlags = sync_flags;
004089    w.szPage = szPage;
004090    iOffset = walFrameOffset(iFrame+1, szPage);
004091    szFrame = szPage + WAL_FRAME_HDRSIZE;
004092  
004093    /* Write all frames into the log file exactly once */
004094    for(p=pList; p; p=p->pDirty){
004095      int nDbSize;   /* 0 normally.  Positive == commit flag */
004096  
004097      /* Check if this page has already been written into the wal file by
004098      ** the current transaction. If so, overwrite the existing frame and
004099      ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
004100      ** checksums must be recomputed when the transaction is committed.  */
004101      if( iFirst && (p->pDirty || isCommit==0) ){
004102        u32 iWrite = 0;
004103        VVA_ONLY(rc =) walFindFrame(pWal, p->pgno, &iWrite);
004104        assert( rc==SQLITE_OK || iWrite==0 );
004105        if( iWrite>=iFirst ){
004106          i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
004107          void *pData;
004108          if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
004109            pWal->iReCksum = iWrite;
004110          }
004111          pData = p->pData;
004112          rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
004113          if( rc ) return rc;
004114          p->flags &= ~PGHDR_WAL_APPEND;
004115          continue;
004116        }
004117      }
004118  
004119      iFrame++;
004120      assert( iOffset==walFrameOffset(iFrame, szPage) );
004121      nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
004122      rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
004123      if( rc ) return rc;
004124      pLast = p;
004125      iOffset += szFrame;
004126      p->flags |= PGHDR_WAL_APPEND;
004127    }
004128  
004129    /* Recalculate checksums within the wal file if required. */
004130    if( isCommit && pWal->iReCksum ){
004131      rc = walRewriteChecksums(pWal, iFrame);
004132      if( rc ) return rc;
004133    }
004134  
004135    /* If this is the end of a transaction, then we might need to pad
004136    ** the transaction and/or sync the WAL file.
004137    **
004138    ** Padding and syncing only occur if this set of frames complete a
004139    ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
004140    ** or synchronous==OFF, then no padding or syncing are needed.
004141    **
004142    ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
004143    ** needed and only the sync is done.  If padding is needed, then the
004144    ** final frame is repeated (with its commit mark) until the next sector
004145    ** boundary is crossed.  Only the part of the WAL prior to the last
004146    ** sector boundary is synced; the part of the last frame that extends
004147    ** past the sector boundary is written after the sync.
004148    */
004149    if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
004150      int bSync = 1;
004151      if( pWal->padToSectorBoundary ){
004152        int sectorSize = sqlite3SectorSize(pWal->pWalFd);
004153        w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
004154        bSync = (w.iSyncPoint==iOffset);
004155        testcase( bSync );
004156        while( iOffset<w.iSyncPoint ){
004157          rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
004158          if( rc ) return rc;
004159          iOffset += szFrame;
004160          nExtra++;
004161          assert( pLast!=0 );
004162        }
004163      }
004164      if( bSync ){
004165        assert( rc==SQLITE_OK );
004166        rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
004167      }
004168    }
004169  
004170    /* If this frame set completes the first transaction in the WAL and
004171    ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
004172    ** journal size limit, if possible.
004173    */
004174    if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
004175      i64 sz = pWal->mxWalSize;
004176      if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
004177        sz = walFrameOffset(iFrame+nExtra+1, szPage);
004178      }
004179      walLimitSize(pWal, sz);
004180      pWal->truncateOnCommit = 0;
004181    }
004182  
004183    /* Append data to the wal-index. It is not necessary to lock the
004184    ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
004185    ** guarantees that there are no other writers, and no data that may
004186    ** be in use by existing readers is being overwritten.
004187    */
004188    iFrame = pWal->hdr.mxFrame;
004189    for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
004190      if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
004191      iFrame++;
004192      rc = walIndexAppend(pWal, iFrame, p->pgno);
004193    }
004194    assert( pLast!=0 || nExtra==0 );
004195    while( rc==SQLITE_OK && nExtra>0 ){
004196      iFrame++;
004197      nExtra--;
004198      rc = walIndexAppend(pWal, iFrame, pLast->pgno);
004199    }
004200  
004201    if( rc==SQLITE_OK ){
004202      /* Update the private copy of the header. */
004203      pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
004204      testcase( szPage<=32768 );
004205      testcase( szPage>=65536 );
004206      pWal->hdr.mxFrame = iFrame;
004207      if( isCommit ){
004208        pWal->hdr.iChange++;
004209        pWal->hdr.nPage = nTruncate;
004210      }
004211      /* If this is a commit, update the wal-index header too. */
004212      if( isCommit ){
004213        walIndexWriteHdr(pWal);
004214        pWal->iCallback = iFrame;
004215      }
004216    }
004217  
004218    WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
004219    return rc;
004220  }
004221  
004222  /* 
004223  ** Write a set of frames to the log. The caller must hold the write-lock
004224  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
004225  **
004226  ** The difference between this function and walFrames() is that this
004227  ** function wraps walFrames() in an SEH_TRY{...} block.
004228  */
004229  int sqlite3WalFrames(
004230    Wal *pWal,                      /* Wal handle to write to */
004231    int szPage,                     /* Database page-size in bytes */
004232    PgHdr *pList,                   /* List of dirty pages to write */
004233    Pgno nTruncate,                 /* Database size after this commit */
004234    int isCommit,                   /* True if this is a commit */
004235    int sync_flags                  /* Flags to pass to OsSync() (or 0) */
004236  ){
004237    int rc;
004238    SEH_TRY {
004239      rc = walFrames(pWal, szPage, pList, nTruncate, isCommit, sync_flags);
004240    }
004241    SEH_EXCEPT( rc = walHandleException(pWal); )
004242    return rc;
004243  }
004244  
004245  /*
004246  ** This routine is called to implement sqlite3_wal_checkpoint() and
004247  ** related interfaces.
004248  **
004249  ** Obtain a CHECKPOINT lock and then backfill as much information as
004250  ** we can from WAL into the database.
004251  **
004252  ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
004253  ** callback. In this case this function runs a blocking checkpoint.
004254  */
004255  int sqlite3WalCheckpoint(
004256    Wal *pWal,                      /* Wal connection */
004257    sqlite3 *db,                    /* Check this handle's interrupt flag */
004258    int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
004259    int (*xBusy)(void*),            /* Function to call when busy */
004260    void *pBusyArg,                 /* Context argument for xBusyHandler */
004261    int sync_flags,                 /* Flags to sync db file with (or 0) */
004262    int nBuf,                       /* Size of temporary buffer */
004263    u8 *zBuf,                       /* Temporary buffer to use */
004264    int *pnLog,                     /* OUT: Number of frames in WAL */
004265    int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
004266  ){
004267    int rc;                         /* Return code */
004268    int isChanged = 0;              /* True if a new wal-index header is loaded */
004269    int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
004270    int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
004271  
004272    assert( pWal->ckptLock==0 );
004273    assert( pWal->writeLock==0 );
004274  
004275    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
004276    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
004277    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
004278  
004279    if( pWal->readOnly ) return SQLITE_READONLY;
004280    WALTRACE(("WAL%p: checkpoint begins\n", pWal));
004281  
004282    /* Enable blocking locks, if possible. */
004283    sqlite3WalDb(pWal, db);
004284    if( xBusy2 ) (void)walEnableBlocking(pWal);
004285  
004286    /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
004287    ** "checkpoint" lock on the database file.
004288    ** EVIDENCE-OF: R-10421-19736 If any other process is running a
004289    ** checkpoint operation at the same time, the lock cannot be obtained and
004290    ** SQLITE_BUSY is returned.
004291    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
004292    ** it will not be invoked in this case.
004293    */
004294    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
004295    testcase( rc==SQLITE_BUSY );
004296    testcase( rc!=SQLITE_OK && xBusy2!=0 );
004297    if( rc==SQLITE_OK ){
004298      pWal->ckptLock = 1;
004299  
004300      /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
004301      ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
004302      ** file.
004303      **
004304      ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
004305      ** immediately, and a busy-handler is configured, it is invoked and the
004306      ** writer lock retried until either the busy-handler returns 0 or the
004307      ** lock is successfully obtained.
004308      */
004309      if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
004310        rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
004311        if( rc==SQLITE_OK ){
004312          pWal->writeLock = 1;
004313        }else if( rc==SQLITE_BUSY ){
004314          eMode2 = SQLITE_CHECKPOINT_PASSIVE;
004315          xBusy2 = 0;
004316          rc = SQLITE_OK;
004317        }
004318      }
004319    }
004320  
004321  
004322    /* Read the wal-index header. */
004323    SEH_TRY {
004324      if( rc==SQLITE_OK ){
004325        /* For a passive checkpoint, do not re-enable blocking locks after
004326        ** reading the wal-index header. A passive checkpoint should not block 
004327        ** or invoke the busy handler. The only lock such a checkpoint may 
004328        ** attempt to obtain is a lock on a read-slot, and it should give up
004329        ** immediately and do a partial checkpoint if it cannot obtain it. */
004330        walDisableBlocking(pWal);
004331        rc = walIndexReadHdr(pWal, &isChanged);
004332        if( eMode2!=SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal);
004333        if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
004334          sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
004335        }
004336      }
004337    
004338      /* Copy data from the log to the database file. */
004339      if( rc==SQLITE_OK ){
004340        if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
004341          rc = SQLITE_CORRUPT_BKPT;
004342        }else{
004343          rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf);
004344        }
004345  
004346        /* If no error occurred, set the output variables. */
004347        if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
004348          if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
004349          SEH_INJECT_FAULT;
004350          if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
004351        }
004352      }
004353    }
004354    SEH_EXCEPT( rc = walHandleException(pWal); )
004355  
004356    if( isChanged ){
004357      /* If a new wal-index header was loaded before the checkpoint was
004358      ** performed, then the pager-cache associated with pWal is now
004359      ** out of date. So zero the cached wal-index header to ensure that
004360      ** next time the pager opens a snapshot on this database it knows that
004361      ** the cache needs to be reset.
004362      */
004363      memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
004364    }
004365  
004366    walDisableBlocking(pWal);
004367    sqlite3WalDb(pWal, 0);
004368  
004369    /* Release the locks. */
004370    sqlite3WalEndWriteTransaction(pWal);
004371    if( pWal->ckptLock ){
004372      walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
004373      pWal->ckptLock = 0;
004374    }
004375    WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
004376  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
004377    if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
004378  #endif
004379    return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
004380  }
004381  
004382  /* Return the value to pass to a sqlite3_wal_hook callback, the
004383  ** number of frames in the WAL at the point of the last commit since
004384  ** sqlite3WalCallback() was called.  If no commits have occurred since
004385  ** the last call, then return 0.
004386  */
004387  int sqlite3WalCallback(Wal *pWal){
004388    u32 ret = 0;
004389    if( pWal ){
004390      ret = pWal->iCallback;
004391      pWal->iCallback = 0;
004392    }
004393    return (int)ret;
004394  }
004395  
004396  /*
004397  ** This function is called to change the WAL subsystem into or out
004398  ** of locking_mode=EXCLUSIVE.
004399  **
004400  ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
004401  ** into locking_mode=NORMAL.  This means that we must acquire a lock
004402  ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
004403  ** or if the acquisition of the lock fails, then return 0.  If the
004404  ** transition out of exclusive-mode is successful, return 1.  This
004405  ** operation must occur while the pager is still holding the exclusive
004406  ** lock on the main database file.
004407  **
004408  ** If op is one, then change from locking_mode=NORMAL into
004409  ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
004410  ** be released.  Return 1 if the transition is made and 0 if the
004411  ** WAL is already in exclusive-locking mode - meaning that this
004412  ** routine is a no-op.  The pager must already hold the exclusive lock
004413  ** on the main database file before invoking this operation.
004414  **
004415  ** If op is negative, then do a dry-run of the op==1 case but do
004416  ** not actually change anything. The pager uses this to see if it
004417  ** should acquire the database exclusive lock prior to invoking
004418  ** the op==1 case.
004419  */
004420  int sqlite3WalExclusiveMode(Wal *pWal, int op){
004421    int rc;
004422    assert( pWal->writeLock==0 );
004423    assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
004424  
004425    /* pWal->readLock is usually set, but might be -1 if there was a
004426    ** prior error while attempting to acquire are read-lock. This cannot
004427    ** happen if the connection is actually in exclusive mode (as no xShmLock
004428    ** locks are taken in this case). Nor should the pager attempt to
004429    ** upgrade to exclusive-mode following such an error.
004430    */
004431  #ifndef SQLITE_USE_SEH
004432    assert( pWal->readLock>=0 || pWal->lockError );
004433  #endif
004434    assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
004435  
004436    if( op==0 ){
004437      if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
004438        pWal->exclusiveMode = WAL_NORMAL_MODE;
004439        if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
004440          pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
004441        }
004442        rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
004443      }else{
004444        /* Already in locking_mode=NORMAL */
004445        rc = 0;
004446      }
004447    }else if( op>0 ){
004448      assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
004449      assert( pWal->readLock>=0 );
004450      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
004451      pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
004452      rc = 1;
004453    }else{
004454      rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
004455    }
004456    return rc;
004457  }
004458  
004459  /*
004460  ** Return true if the argument is non-NULL and the WAL module is using
004461  ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
004462  ** WAL module is using shared-memory, return false.
004463  */
004464  int sqlite3WalHeapMemory(Wal *pWal){
004465    return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
004466  }
004467  
004468  #ifdef SQLITE_ENABLE_SNAPSHOT
004469  /* Create a snapshot object.  The content of a snapshot is opaque to
004470  ** every other subsystem, so the WAL module can put whatever it needs
004471  ** in the object.
004472  */
004473  int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
004474    int rc = SQLITE_OK;
004475    WalIndexHdr *pRet;
004476    static const u32 aZero[4] = { 0, 0, 0, 0 };
004477  
004478    assert( pWal->readLock>=0 && pWal->writeLock==0 );
004479  
004480    if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
004481      *ppSnapshot = 0;
004482      return SQLITE_ERROR;
004483    }
004484    pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
004485    if( pRet==0 ){
004486      rc = SQLITE_NOMEM_BKPT;
004487    }else{
004488      memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
004489      *ppSnapshot = (sqlite3_snapshot*)pRet;
004490    }
004491  
004492    return rc;
004493  }
004494  
004495  /* Try to open on pSnapshot when the next read-transaction starts
004496  */
004497  void sqlite3WalSnapshotOpen(
004498    Wal *pWal,
004499    sqlite3_snapshot *pSnapshot
004500  ){
004501    if( pSnapshot && ((WalIndexHdr*)pSnapshot)->iVersion==0 ){
004502      /* iVersion==0 means that this is a call to sqlite3_snapshot_get().  In
004503      ** this case set the bGetSnapshot flag so that if the call to
004504      ** sqlite3_snapshot_get() is about to read transaction on this wal 
004505      ** file, it does not take read-lock 0 if the wal file has been completely
004506      ** checkpointed. Taking read-lock 0 would work, but then it would be
004507      ** possible for a subsequent writer to destroy the snapshot even while 
004508      ** this connection is holding its read-transaction open. This is contrary
004509      ** to user expectations, so we avoid it by not taking read-lock 0. */
004510      pWal->bGetSnapshot = 1;
004511    }else{
004512      pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
004513      pWal->bGetSnapshot = 0;
004514    }
004515  }
004516  
004517  /*
004518  ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
004519  ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
004520  */
004521  int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
004522    WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
004523    WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
004524  
004525    /* aSalt[0] is a copy of the value stored in the wal file header. It
004526    ** is incremented each time the wal file is restarted.  */
004527    if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
004528    if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
004529    if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
004530    if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
004531    return 0;
004532  }
004533  
004534  /*
004535  ** The caller currently has a read transaction open on the database.
004536  ** This function takes a SHARED lock on the CHECKPOINTER slot and then
004537  ** checks if the snapshot passed as the second argument is still
004538  ** available. If so, SQLITE_OK is returned.
004539  **
004540  ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
004541  ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
004542  ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
004543  ** lock is released before returning.
004544  */
004545  int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
004546    int rc;
004547    SEH_TRY {
004548      rc = walLockShared(pWal, WAL_CKPT_LOCK);
004549      if( rc==SQLITE_OK ){
004550        WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
004551        if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
004552         || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
004553        ){
004554          rc = SQLITE_ERROR_SNAPSHOT;
004555          walUnlockShared(pWal, WAL_CKPT_LOCK);
004556        }
004557      }
004558    }
004559    SEH_EXCEPT( rc = walHandleException(pWal); )
004560    return rc;
004561  }
004562  
004563  /*
004564  ** Release a lock obtained by an earlier successful call to
004565  ** sqlite3WalSnapshotCheck().
004566  */
004567  void sqlite3WalSnapshotUnlock(Wal *pWal){
004568    assert( pWal );
004569    walUnlockShared(pWal, WAL_CKPT_LOCK);
004570  }
004571  
004572  
004573  #endif /* SQLITE_ENABLE_SNAPSHOT */
004574  
004575  #ifdef SQLITE_ENABLE_ZIPVFS
004576  /*
004577  ** If the argument is not NULL, it points to a Wal object that holds a
004578  ** read-lock. This function returns the database page-size if it is known,
004579  ** or zero if it is not (or if pWal is NULL).
004580  */
004581  int sqlite3WalFramesize(Wal *pWal){
004582    assert( pWal==0 || pWal->readLock>=0 );
004583    return (pWal ? pWal->szPage : 0);
004584  }
004585  #endif
004586  
004587  /* Return the sqlite3_file object for the WAL file
004588  */
004589  sqlite3_file *sqlite3WalFile(Wal *pWal){
004590    return pWal->pWalFd;
004591  }
004592  
004593  #endif /* #ifndef SQLITE_OMIT_WAL */