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 a <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  #endif
000545  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
000546    sqlite3 *db;
000547  #endif
000548  };
000549  
000550  /*
000551  ** Candidate values for Wal.exclusiveMode.
000552  */
000553  #define WAL_NORMAL_MODE     0
000554  #define WAL_EXCLUSIVE_MODE  1
000555  #define WAL_HEAPMEMORY_MODE 2
000556  
000557  /*
000558  ** Possible values for WAL.readOnly
000559  */
000560  #define WAL_RDWR        0    /* Normal read/write connection */
000561  #define WAL_RDONLY      1    /* The WAL file is readonly */
000562  #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
000563  
000564  /*
000565  ** Each page of the wal-index mapping contains a hash-table made up of
000566  ** an array of HASHTABLE_NSLOT elements of the following type.
000567  */
000568  typedef u16 ht_slot;
000569  
000570  /*
000571  ** This structure is used to implement an iterator that loops through
000572  ** all frames in the WAL in database page order. Where two or more frames
000573  ** correspond to the same database page, the iterator visits only the
000574  ** frame most recently written to the WAL (in other words, the frame with
000575  ** the largest index).
000576  **
000577  ** The internals of this structure are only accessed by:
000578  **
000579  **   walIteratorInit() - Create a new iterator,
000580  **   walIteratorNext() - Step an iterator,
000581  **   walIteratorFree() - Free an iterator.
000582  **
000583  ** This functionality is used by the checkpoint code (see walCheckpoint()).
000584  */
000585  struct WalIterator {
000586    u32 iPrior;                     /* Last result returned from the iterator */
000587    int nSegment;                   /* Number of entries in aSegment[] */
000588    struct WalSegment {
000589      int iNext;                    /* Next slot in aIndex[] not yet returned */
000590      ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
000591      u32 *aPgno;                   /* Array of page numbers. */
000592      int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
000593      int iZero;                    /* Frame number associated with aPgno[0] */
000594    } aSegment[1];                  /* One for every 32KB page in the wal-index */
000595  };
000596  
000597  /*
000598  ** Define the parameters of the hash tables in the wal-index file. There
000599  ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
000600  ** wal-index.
000601  **
000602  ** Changing any of these constants will alter the wal-index format and
000603  ** create incompatibilities.
000604  */
000605  #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
000606  #define HASHTABLE_HASH_1     383                  /* Should be prime */
000607  #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
000608  
000609  /*
000610  ** The block of page numbers associated with the first hash-table in a
000611  ** wal-index is smaller than usual. This is so that there is a complete
000612  ** hash-table on each aligned 32KB page of the wal-index.
000613  */
000614  #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
000615  
000616  /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
000617  #define WALINDEX_PGSZ   (                                         \
000618      sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
000619  )
000620  
000621  /*
000622  ** Structured Exception Handling (SEH) is a Windows-specific technique
000623  ** for catching exceptions raised while accessing memory-mapped files.
000624  **
000625  ** The -DSQLITE_USE_SEH compile-time option means to use SEH to catch and
000626  ** deal with system-level errors that arise during WAL -shm file processing.
000627  ** Without this compile-time option, any system-level faults that appear
000628  ** while accessing the memory-mapped -shm file will cause a process-wide
000629  ** signal to be deliver, which will more than likely cause the entire
000630  ** process to exit.
000631  */
000632  #ifdef SQLITE_USE_SEH
000633  #include <Windows.h>
000634  
000635  /* Beginning of a block of code in which an exception might occur */
000636  # define SEH_TRY    __try { \
000637     assert( walAssertLockmask(pWal) && pWal->nSehTry==0 ); \
000638     VVA_ONLY(pWal->nSehTry++);
000639  
000640  /* The end of a block of code in which an exception might occur */
000641  # define SEH_EXCEPT(X) \
000642     VVA_ONLY(pWal->nSehTry--); \
000643     assert( pWal->nSehTry==0 ); \
000644     } __except( sehExceptionFilter(pWal, GetExceptionCode(), GetExceptionInformation() ) ){ X }
000645  
000646  /* Simulate a memory-mapping fault in the -shm file for testing purposes */
000647  # define SEH_INJECT_FAULT sehInjectFault(pWal) 
000648  
000649  /*
000650  ** The second argument is the return value of GetExceptionCode() for the 
000651  ** current exception. Return EXCEPTION_EXECUTE_HANDLER if the exception code
000652  ** indicates that the exception may have been caused by accessing the *-shm 
000653  ** file mapping. Or EXCEPTION_CONTINUE_SEARCH otherwise.
000654  */
000655  static int sehExceptionFilter(Wal *pWal, int eCode, EXCEPTION_POINTERS *p){
000656    VVA_ONLY(pWal->nSehTry--);
000657    if( eCode==EXCEPTION_IN_PAGE_ERROR ){
000658      if( p && p->ExceptionRecord && p->ExceptionRecord->NumberParameters>=3 ){
000659        /* From MSDN: For this type of exception, the first element of the
000660        ** ExceptionInformation[] array is a read-write flag - 0 if the exception
000661        ** was thrown while reading, 1 if while writing. The second element is
000662        ** the virtual address being accessed. The "third array element specifies
000663        ** the underlying NTSTATUS code that resulted in the exception". */
000664        pWal->iSysErrno = (int)p->ExceptionRecord->ExceptionInformation[2];
000665      }
000666      return EXCEPTION_EXECUTE_HANDLER;
000667    }
000668    return EXCEPTION_CONTINUE_SEARCH;
000669  }
000670  
000671  /*
000672  ** If one is configured, invoke the xTestCallback callback with 650 as
000673  ** the argument. If it returns true, throw the same exception that is
000674  ** thrown by the system if the *-shm file mapping is accessed after it
000675  ** has been invalidated.
000676  */
000677  static void sehInjectFault(Wal *pWal){
000678    int res;
000679    assert( pWal->nSehTry>0 );
000680  
000681    res = sqlite3FaultSim(650);
000682    if( res!=0 ){
000683      ULONG_PTR aArg[3];
000684      aArg[0] = 0;
000685      aArg[1] = 0;
000686      aArg[2] = (ULONG_PTR)res;
000687      RaiseException(EXCEPTION_IN_PAGE_ERROR, 0, 3, (const ULONG_PTR*)aArg);
000688    }
000689  }
000690  
000691  /*
000692  ** There are two ways to use this macro. To set a pointer to be freed
000693  ** if an exception is thrown:
000694  **
000695  **   SEH_FREE_ON_ERROR(0, pPtr);
000696  **
000697  ** and to cancel the same:
000698  **
000699  **   SEH_FREE_ON_ERROR(pPtr, 0);
000700  **
000701  ** In the first case, there must not already be a pointer registered to
000702  ** be freed. In the second case, pPtr must be the registered pointer.
000703  */
000704  #define SEH_FREE_ON_ERROR(X,Y) \
000705    assert( (X==0 || Y==0) && pWal->pFree==X ); pWal->pFree = Y
000706  
000707  /*
000708  ** There are two ways to use this macro. To arrange for pWal->apWiData[iPg]
000709  ** to be set to pValue if an exception is thrown:
000710  **
000711  **   SEH_SET_ON_ERROR(iPg, pValue);
000712  **
000713  ** and to cancel the same:
000714  **
000715  **   SEH_SET_ON_ERROR(0, 0);
000716  */
000717  #define SEH_SET_ON_ERROR(X,Y)  pWal->iWiPg = X; pWal->pWiValue = Y
000718  
000719  #else
000720  # define SEH_TRY          VVA_ONLY(pWal->nSehTry++);
000721  # define SEH_EXCEPT(X)    VVA_ONLY(pWal->nSehTry--); assert( pWal->nSehTry==0 );
000722  # define SEH_INJECT_FAULT assert( pWal->nSehTry>0 );
000723  # define SEH_FREE_ON_ERROR(X,Y)
000724  # define SEH_SET_ON_ERROR(X,Y)
000725  #endif /* ifdef SQLITE_USE_SEH */
000726  
000727  
000728  /*
000729  ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
000730  ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
000731  ** numbered from zero.
000732  **
000733  ** If the wal-index is currently smaller the iPage pages then the size
000734  ** of the wal-index might be increased, but only if it is safe to do
000735  ** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
000736  ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
000737  **
000738  ** Three possible result scenarios:
000739  **
000740  **   (1)  rc==SQLITE_OK    and *ppPage==Requested-Wal-Index-Page
000741  **   (2)  rc>=SQLITE_ERROR and *ppPage==NULL
000742  **   (3)  rc==SQLITE_OK    and *ppPage==NULL  // only if iPage==0
000743  **
000744  ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
000745  */
000746  static SQLITE_NOINLINE int walIndexPageRealloc(
000747    Wal *pWal,               /* The WAL context */
000748    int iPage,               /* The page we seek */
000749    volatile u32 **ppPage    /* Write the page pointer here */
000750  ){
000751    int rc = SQLITE_OK;
000752  
000753    /* Enlarge the pWal->apWiData[] array if required */
000754    if( pWal->nWiData<=iPage ){
000755      sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
000756      volatile u32 **apNew;
000757      apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
000758      if( !apNew ){
000759        *ppPage = 0;
000760        return SQLITE_NOMEM_BKPT;
000761      }
000762      memset((void*)&apNew[pWal->nWiData], 0,
000763             sizeof(u32*)*(iPage+1-pWal->nWiData));
000764      pWal->apWiData = apNew;
000765      pWal->nWiData = iPage+1;
000766    }
000767  
000768    /* Request a pointer to the required page from the VFS */
000769    assert( pWal->apWiData[iPage]==0 );
000770    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
000771      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
000772      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
000773    }else{
000774      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
000775          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
000776      );
000777      assert( pWal->apWiData[iPage]!=0
000778           || rc!=SQLITE_OK
000779           || (pWal->writeLock==0 && iPage==0) );
000780      testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
000781      if( rc==SQLITE_OK ){
000782        if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
000783      }else if( (rc&0xff)==SQLITE_READONLY ){
000784        pWal->readOnly |= WAL_SHM_RDONLY;
000785        if( rc==SQLITE_READONLY ){
000786          rc = SQLITE_OK;
000787        }
000788      }
000789    }
000790  
000791    *ppPage = pWal->apWiData[iPage];
000792    assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
000793    return rc;
000794  }
000795  static int walIndexPage(
000796    Wal *pWal,               /* The WAL context */
000797    int iPage,               /* The page we seek */
000798    volatile u32 **ppPage    /* Write the page pointer here */
000799  ){
000800    SEH_INJECT_FAULT;
000801    if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
000802      return walIndexPageRealloc(pWal, iPage, ppPage);
000803    }
000804    return SQLITE_OK;
000805  }
000806  
000807  /*
000808  ** Return a pointer to the WalCkptInfo structure in the wal-index.
000809  */
000810  static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
000811    assert( pWal->nWiData>0 && pWal->apWiData[0] );
000812    SEH_INJECT_FAULT;
000813    return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
000814  }
000815  
000816  /*
000817  ** Return a pointer to the WalIndexHdr structure in the wal-index.
000818  */
000819  static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
000820    assert( pWal->nWiData>0 && pWal->apWiData[0] );
000821    SEH_INJECT_FAULT;
000822    return (volatile WalIndexHdr*)pWal->apWiData[0];
000823  }
000824  
000825  /*
000826  ** The argument to this macro must be of type u32. On a little-endian
000827  ** architecture, it returns the u32 value that results from interpreting
000828  ** the 4 bytes as a big-endian value. On a big-endian architecture, it
000829  ** returns the value that would be produced by interpreting the 4 bytes
000830  ** of the input value as a little-endian integer.
000831  */
000832  #define BYTESWAP32(x) ( \
000833      (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
000834    + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
000835  )
000836  
000837  /*
000838  ** Generate or extend an 8 byte checksum based on the data in
000839  ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
000840  ** initial values of 0 and 0 if aIn==NULL).
000841  **
000842  ** The checksum is written back into aOut[] before returning.
000843  **
000844  ** nByte must be a positive multiple of 8.
000845  */
000846  static void walChecksumBytes(
000847    int nativeCksum, /* True for native byte-order, false for non-native */
000848    u8 *a,           /* Content to be checksummed */
000849    int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
000850    const u32 *aIn,  /* Initial checksum value input */
000851    u32 *aOut        /* OUT: Final checksum value output */
000852  ){
000853    u32 s1, s2;
000854    u32 *aData = (u32 *)a;
000855    u32 *aEnd = (u32 *)&a[nByte];
000856  
000857    if( aIn ){
000858      s1 = aIn[0];
000859      s2 = aIn[1];
000860    }else{
000861      s1 = s2 = 0;
000862    }
000863  
000864    assert( nByte>=8 );
000865    assert( (nByte&0x00000007)==0 );
000866    assert( nByte<=65536 );
000867    assert( nByte%4==0 );
000868  
000869    if( !nativeCksum ){
000870      do {
000871        s1 += BYTESWAP32(aData[0]) + s2;
000872        s2 += BYTESWAP32(aData[1]) + s1;
000873        aData += 2;
000874      }while( aData<aEnd );
000875    }else if( nByte%64==0 ){
000876      do {
000877        s1 += *aData++ + s2;
000878        s2 += *aData++ + s1;
000879        s1 += *aData++ + s2;
000880        s2 += *aData++ + s1;
000881        s1 += *aData++ + s2;
000882        s2 += *aData++ + s1;
000883        s1 += *aData++ + s2;
000884        s2 += *aData++ + s1;
000885        s1 += *aData++ + s2;
000886        s2 += *aData++ + s1;
000887        s1 += *aData++ + s2;
000888        s2 += *aData++ + s1;
000889        s1 += *aData++ + s2;
000890        s2 += *aData++ + s1;
000891        s1 += *aData++ + s2;
000892        s2 += *aData++ + s1;
000893      }while( aData<aEnd );
000894    }else{
000895      do {
000896        s1 += *aData++ + s2;
000897        s2 += *aData++ + s1;
000898      }while( aData<aEnd );
000899    }
000900    assert( aData==aEnd );
000901  
000902    aOut[0] = s1;
000903    aOut[1] = s2;
000904  }
000905  
000906  /*
000907  ** If there is the possibility of concurrent access to the SHM file
000908  ** from multiple threads and/or processes, then do a memory barrier.
000909  */
000910  static void walShmBarrier(Wal *pWal){
000911    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
000912      sqlite3OsShmBarrier(pWal->pDbFd);
000913    }
000914  }
000915  
000916  /*
000917  ** Add the SQLITE_NO_TSAN as part of the return-type of a function
000918  ** definition as a hint that the function contains constructs that
000919  ** might give false-positive TSAN warnings.
000920  **
000921  ** See tag-20200519-1.
000922  */
000923  #if defined(__clang__) && !defined(SQLITE_NO_TSAN)
000924  # define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
000925  #else
000926  # define SQLITE_NO_TSAN
000927  #endif
000928  
000929  /*
000930  ** Write the header information in pWal->hdr into the wal-index.
000931  **
000932  ** The checksum on pWal->hdr is updated before it is written.
000933  */
000934  static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
000935    volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
000936    const int nCksum = offsetof(WalIndexHdr, aCksum);
000937  
000938    assert( pWal->writeLock );
000939    pWal->hdr.isInit = 1;
000940    pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
000941    walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
000942    /* Possible TSAN false-positive.  See tag-20200519-1 */
000943    memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
000944    walShmBarrier(pWal);
000945    memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
000946  }
000947  
000948  /*
000949  ** This function encodes a single frame header and writes it to a buffer
000950  ** supplied by the caller. A frame-header is made up of a series of
000951  ** 4-byte big-endian integers, as follows:
000952  **
000953  **     0: Page number.
000954  **     4: For commit records, the size of the database image in pages
000955  **        after the commit. For all other records, zero.
000956  **     8: Salt-1 (copied from the wal-header)
000957  **    12: Salt-2 (copied from the wal-header)
000958  **    16: Checksum-1.
000959  **    20: Checksum-2.
000960  */
000961  static void walEncodeFrame(
000962    Wal *pWal,                      /* The write-ahead log */
000963    u32 iPage,                      /* Database page number for frame */
000964    u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
000965    u8 *aData,                      /* Pointer to page data */
000966    u8 *aFrame                      /* OUT: Write encoded frame here */
000967  ){
000968    int nativeCksum;                /* True for native byte-order checksums */
000969    u32 *aCksum = pWal->hdr.aFrameCksum;
000970    assert( WAL_FRAME_HDRSIZE==24 );
000971    sqlite3Put4byte(&aFrame[0], iPage);
000972    sqlite3Put4byte(&aFrame[4], nTruncate);
000973    if( pWal->iReCksum==0 ){
000974      memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
000975  
000976      nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
000977      walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
000978      walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
000979  
000980      sqlite3Put4byte(&aFrame[16], aCksum[0]);
000981      sqlite3Put4byte(&aFrame[20], aCksum[1]);
000982    }else{
000983      memset(&aFrame[8], 0, 16);
000984    }
000985  }
000986  
000987  /*
000988  ** Check to see if the frame with header in aFrame[] and content
000989  ** in aData[] is valid.  If it is a valid frame, fill *piPage and
000990  ** *pnTruncate and return true.  Return if the frame is not valid.
000991  */
000992  static int walDecodeFrame(
000993    Wal *pWal,                      /* The write-ahead log */
000994    u32 *piPage,                    /* OUT: Database page number for frame */
000995    u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
000996    u8 *aData,                      /* Pointer to page data (for checksum) */
000997    u8 *aFrame                      /* Frame data */
000998  ){
000999    int nativeCksum;                /* True for native byte-order checksums */
001000    u32 *aCksum = pWal->hdr.aFrameCksum;
001001    u32 pgno;                       /* Page number of the frame */
001002    assert( WAL_FRAME_HDRSIZE==24 );
001003  
001004    /* A frame is only valid if the salt values in the frame-header
001005    ** match the salt values in the wal-header.
001006    */
001007    if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
001008      return 0;
001009    }
001010  
001011    /* A frame is only valid if the page number is greater than zero.
001012    */
001013    pgno = sqlite3Get4byte(&aFrame[0]);
001014    if( pgno==0 ){
001015      return 0;
001016    }
001017  
001018    /* A frame is only valid if a checksum of the WAL header,
001019    ** all prior frames, the first 16 bytes of this frame-header,
001020    ** and the frame-data matches the checksum in the last 8
001021    ** bytes of this frame-header.
001022    */
001023    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
001024    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
001025    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
001026    if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
001027     || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
001028    ){
001029      /* Checksum failed. */
001030      return 0;
001031    }
001032  
001033    /* If we reach this point, the frame is valid.  Return the page number
001034    ** and the new database size.
001035    */
001036    *piPage = pgno;
001037    *pnTruncate = sqlite3Get4byte(&aFrame[4]);
001038    return 1;
001039  }
001040  
001041  
001042  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
001043  /*
001044  ** Names of locks.  This routine is used to provide debugging output and is not
001045  ** a part of an ordinary build.
001046  */
001047  static const char *walLockName(int lockIdx){
001048    if( lockIdx==WAL_WRITE_LOCK ){
001049      return "WRITE-LOCK";
001050    }else if( lockIdx==WAL_CKPT_LOCK ){
001051      return "CKPT-LOCK";
001052    }else if( lockIdx==WAL_RECOVER_LOCK ){
001053      return "RECOVER-LOCK";
001054    }else{
001055      static char zName[15];
001056      sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
001057                       lockIdx-WAL_READ_LOCK(0));
001058      return zName;
001059    }
001060  }
001061  #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
001062  
001063  
001064  /*
001065  ** Set or release locks on the WAL.  Locks are either shared or exclusive.
001066  ** A lock cannot be moved directly between shared and exclusive - it must go
001067  ** through the unlocked state first.
001068  **
001069  ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
001070  */
001071  static int walLockShared(Wal *pWal, int lockIdx){
001072    int rc;
001073    if( pWal->exclusiveMode ) return SQLITE_OK;
001074    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
001075                          SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
001076    WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
001077              walLockName(lockIdx), rc ? "failed" : "ok"));
001078    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
001079  #ifdef SQLITE_USE_SEH
001080    if( rc==SQLITE_OK ) pWal->lockMask |= (1 << lockIdx);
001081  #endif
001082    return rc;
001083  }
001084  static void walUnlockShared(Wal *pWal, int lockIdx){
001085    if( pWal->exclusiveMode ) return;
001086    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
001087                           SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
001088  #ifdef SQLITE_USE_SEH
001089    pWal->lockMask &= ~(1 << lockIdx);
001090  #endif
001091    WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
001092  }
001093  static int walLockExclusive(Wal *pWal, int lockIdx, int n){
001094    int rc;
001095    if( pWal->exclusiveMode ) return SQLITE_OK;
001096    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
001097                          SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
001098    WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
001099              walLockName(lockIdx), n, rc ? "failed" : "ok"));
001100    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
001101  #ifdef SQLITE_USE_SEH
001102    if( rc==SQLITE_OK ){
001103      pWal->lockMask |= (((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
001104    }
001105  #endif
001106    return rc;
001107  }
001108  static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
001109    if( pWal->exclusiveMode ) return;
001110    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
001111                           SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
001112  #ifdef SQLITE_USE_SEH
001113    pWal->lockMask &= ~(((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
001114  #endif
001115    WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
001116               walLockName(lockIdx), n));
001117  }
001118  
001119  /*
001120  ** Compute a hash on a page number.  The resulting hash value must land
001121  ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
001122  ** the hash to the next value in the event of a collision.
001123  */
001124  static int walHash(u32 iPage){
001125    assert( iPage>0 );
001126    assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
001127    return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
001128  }
001129  static int walNextHash(int iPriorHash){
001130    return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
001131  }
001132  
001133  /*
001134  ** An instance of the WalHashLoc object is used to describe the location
001135  ** of a page hash table in the wal-index.  This becomes the return value
001136  ** from walHashGet().
001137  */
001138  typedef struct WalHashLoc WalHashLoc;
001139  struct WalHashLoc {
001140    volatile ht_slot *aHash;  /* Start of the wal-index hash table */
001141    volatile u32 *aPgno;      /* aPgno[1] is the page of first frame indexed */
001142    u32 iZero;                /* One less than the frame number of first indexed*/
001143  };
001144  
001145  /*
001146  ** Return pointers to the hash table and page number array stored on
001147  ** page iHash of the wal-index. The wal-index is broken into 32KB pages
001148  ** numbered starting from 0.
001149  **
001150  ** Set output variable pLoc->aHash to point to the start of the hash table
001151  ** in the wal-index file. Set pLoc->iZero to one less than the frame
001152  ** number of the first frame indexed by this hash table. If a
001153  ** slot in the hash table is set to N, it refers to frame number
001154  ** (pLoc->iZero+N) in the log.
001155  **
001156  ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
001157  ** first frame indexed by the hash table, frame (pLoc->iZero).
001158  */
001159  static int walHashGet(
001160    Wal *pWal,                      /* WAL handle */
001161    int iHash,                      /* Find the iHash'th table */
001162    WalHashLoc *pLoc                /* OUT: Hash table location */
001163  ){
001164    int rc;                         /* Return code */
001165  
001166    rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
001167    assert( rc==SQLITE_OK || iHash>0 );
001168  
001169    if( pLoc->aPgno ){
001170      pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
001171      if( iHash==0 ){
001172        pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
001173        pLoc->iZero = 0;
001174      }else{
001175        pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
001176      }
001177    }else if( NEVER(rc==SQLITE_OK) ){
001178      rc = SQLITE_ERROR;
001179    }
001180    return rc;
001181  }
001182  
001183  /*
001184  ** Return the number of the wal-index page that contains the hash-table
001185  ** and page-number array that contain entries corresponding to WAL frame
001186  ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
001187  ** are numbered starting from 0.
001188  */
001189  static int walFramePage(u32 iFrame){
001190    int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
001191    assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
001192         && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
001193         && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
001194         && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
001195         && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
001196    );
001197    assert( iHash>=0 );
001198    return iHash;
001199  }
001200  
001201  /*
001202  ** Return the page number associated with frame iFrame in this WAL.
001203  */
001204  static u32 walFramePgno(Wal *pWal, u32 iFrame){
001205    int iHash = walFramePage(iFrame);
001206    SEH_INJECT_FAULT;
001207    if( iHash==0 ){
001208      return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
001209    }
001210    return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
001211  }
001212  
001213  /*
001214  ** Remove entries from the hash table that point to WAL slots greater
001215  ** than pWal->hdr.mxFrame.
001216  **
001217  ** This function is called whenever pWal->hdr.mxFrame is decreased due
001218  ** to a rollback or savepoint.
001219  **
001220  ** At most only the hash table containing pWal->hdr.mxFrame needs to be
001221  ** updated.  Any later hash tables will be automatically cleared when
001222  ** pWal->hdr.mxFrame advances to the point where those hash tables are
001223  ** actually needed.
001224  */
001225  static void walCleanupHash(Wal *pWal){
001226    WalHashLoc sLoc;                /* Hash table location */
001227    int iLimit = 0;                 /* Zero values greater than this */
001228    int nByte;                      /* Number of bytes to zero in aPgno[] */
001229    int i;                          /* Used to iterate through aHash[] */
001230  
001231    assert( pWal->writeLock );
001232    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
001233    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
001234    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
001235  
001236    if( pWal->hdr.mxFrame==0 ) return;
001237  
001238    /* Obtain pointers to the hash-table and page-number array containing
001239    ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
001240    ** that the page said hash-table and array reside on is already mapped.(1)
001241    */
001242    assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
001243    assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
001244    i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
001245    if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
001246  
001247    /* Zero all hash-table entries that correspond to frame numbers greater
001248    ** than pWal->hdr.mxFrame.
001249    */
001250    iLimit = pWal->hdr.mxFrame - sLoc.iZero;
001251    assert( iLimit>0 );
001252    for(i=0; i<HASHTABLE_NSLOT; i++){
001253      if( sLoc.aHash[i]>iLimit ){
001254        sLoc.aHash[i] = 0;
001255      }
001256    }
001257  
001258    /* Zero the entries in the aPgno array that correspond to frames with
001259    ** frame numbers greater than pWal->hdr.mxFrame.
001260    */
001261    nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
001262    assert( nByte>=0 );
001263    memset((void *)&sLoc.aPgno[iLimit], 0, nByte);
001264  
001265  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
001266    /* Verify that the every entry in the mapping region is still reachable
001267    ** via the hash table even after the cleanup.
001268    */
001269    if( iLimit ){
001270      int j;           /* Loop counter */
001271      int iKey;        /* Hash key */
001272      for(j=0; j<iLimit; j++){
001273        for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
001274          if( sLoc.aHash[iKey]==j+1 ) break;
001275        }
001276        assert( sLoc.aHash[iKey]==j+1 );
001277      }
001278    }
001279  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
001280  }
001281  
001282  
001283  /*
001284  ** Set an entry in the wal-index that will map database page number
001285  ** pPage into WAL frame iFrame.
001286  */
001287  static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
001288    int rc;                         /* Return code */
001289    WalHashLoc sLoc;                /* Wal-index hash table location */
001290  
001291    rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
001292  
001293    /* Assuming the wal-index file was successfully mapped, populate the
001294    ** page number array and hash table entry.
001295    */
001296    if( rc==SQLITE_OK ){
001297      int iKey;                     /* Hash table key */
001298      int idx;                      /* Value to write to hash-table slot */
001299      int nCollide;                 /* Number of hash collisions */
001300  
001301      idx = iFrame - sLoc.iZero;
001302      assert( idx <= HASHTABLE_NSLOT/2 + 1 );
001303  
001304      /* If this is the first entry to be added to this hash-table, zero the
001305      ** entire hash table and aPgno[] array before proceeding.
001306      */
001307      if( idx==1 ){
001308        int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
001309        assert( nByte>=0 );
001310        memset((void*)sLoc.aPgno, 0, nByte);
001311      }
001312  
001313      /* If the entry in aPgno[] is already set, then the previous writer
001314      ** must have exited unexpectedly in the middle of a transaction (after
001315      ** writing one or more dirty pages to the WAL to free up memory).
001316      ** Remove the remnants of that writers uncommitted transaction from
001317      ** the hash-table before writing any new entries.
001318      */
001319      if( sLoc.aPgno[idx-1] ){
001320        walCleanupHash(pWal);
001321        assert( !sLoc.aPgno[idx-1] );
001322      }
001323  
001324      /* Write the aPgno[] array entry and the hash-table slot. */
001325      nCollide = idx;
001326      for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
001327        if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
001328      }
001329      sLoc.aPgno[idx-1] = iPage;
001330      AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
001331  
001332  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
001333      /* Verify that the number of entries in the hash table exactly equals
001334      ** the number of entries in the mapping region.
001335      */
001336      {
001337        int i;           /* Loop counter */
001338        int nEntry = 0;  /* Number of entries in the hash table */
001339        for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
001340        assert( nEntry==idx );
001341      }
001342  
001343      /* Verify that the every entry in the mapping region is reachable
001344      ** via the hash table.  This turns out to be a really, really expensive
001345      ** thing to check, so only do this occasionally - not on every
001346      ** iteration.
001347      */
001348      if( (idx&0x3ff)==0 ){
001349        int i;           /* Loop counter */
001350        for(i=0; i<idx; i++){
001351          for(iKey=walHash(sLoc.aPgno[i]);
001352              sLoc.aHash[iKey];
001353              iKey=walNextHash(iKey)){
001354            if( sLoc.aHash[iKey]==i+1 ) break;
001355          }
001356          assert( sLoc.aHash[iKey]==i+1 );
001357        }
001358      }
001359  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
001360    }
001361  
001362    return rc;
001363  }
001364  
001365  
001366  /*
001367  ** Recover the wal-index by reading the write-ahead log file.
001368  **
001369  ** This routine first tries to establish an exclusive lock on the
001370  ** wal-index to prevent other threads/processes from doing anything
001371  ** with the WAL or wal-index while recovery is running.  The
001372  ** WAL_RECOVER_LOCK is also held so that other threads will know
001373  ** that this thread is running recovery.  If unable to establish
001374  ** the necessary locks, this routine returns SQLITE_BUSY.
001375  */
001376  static int walIndexRecover(Wal *pWal){
001377    int rc;                         /* Return Code */
001378    i64 nSize;                      /* Size of log file */
001379    u32 aFrameCksum[2] = {0, 0};
001380    int iLock;                      /* Lock offset to lock for checkpoint */
001381  
001382    /* Obtain an exclusive lock on all byte in the locking range not already
001383    ** locked by the caller. The caller is guaranteed to have locked the
001384    ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
001385    ** If successful, the same bytes that are locked here are unlocked before
001386    ** this function returns.
001387    */
001388    assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
001389    assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
001390    assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
001391    assert( pWal->writeLock );
001392    iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
001393    rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
001394    if( rc ){
001395      return rc;
001396    }
001397  
001398    WALTRACE(("WAL%p: recovery begin...\n", pWal));
001399  
001400    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
001401  
001402    rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
001403    if( rc!=SQLITE_OK ){
001404      goto recovery_error;
001405    }
001406  
001407    if( nSize>WAL_HDRSIZE ){
001408      u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
001409      u32 *aPrivate = 0;            /* Heap copy of *-shm hash being populated */
001410      u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
001411      int szFrame;                  /* Number of bytes in buffer aFrame[] */
001412      u8 *aData;                    /* Pointer to data part of aFrame buffer */
001413      int szPage;                   /* Page size according to the log */
001414      u32 magic;                    /* Magic value read from WAL header */
001415      u32 version;                  /* Magic value read from WAL header */
001416      int isValid;                  /* True if this frame is valid */
001417      u32 iPg;                      /* Current 32KB wal-index page */
001418      u32 iLastFrame;               /* Last frame in wal, based on nSize alone */
001419  
001420      /* Read in the WAL header. */
001421      rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
001422      if( rc!=SQLITE_OK ){
001423        goto recovery_error;
001424      }
001425  
001426      /* If the database page size is not a power of two, or is greater than
001427      ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
001428      ** data. Similarly, if the 'magic' value is invalid, ignore the whole
001429      ** WAL file.
001430      */
001431      magic = sqlite3Get4byte(&aBuf[0]);
001432      szPage = sqlite3Get4byte(&aBuf[8]);
001433      if( (magic&0xFFFFFFFE)!=WAL_MAGIC
001434       || szPage&(szPage-1)
001435       || szPage>SQLITE_MAX_PAGE_SIZE
001436       || szPage<512
001437      ){
001438        goto finished;
001439      }
001440      pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
001441      pWal->szPage = szPage;
001442      pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
001443      memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
001444  
001445      /* Verify that the WAL header checksum is correct */
001446      walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
001447          aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
001448      );
001449      if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
001450       || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
001451      ){
001452        goto finished;
001453      }
001454  
001455      /* Verify that the version number on the WAL format is one that
001456      ** are able to understand */
001457      version = sqlite3Get4byte(&aBuf[4]);
001458      if( version!=WAL_MAX_VERSION ){
001459        rc = SQLITE_CANTOPEN_BKPT;
001460        goto finished;
001461      }
001462  
001463      /* Malloc a buffer to read frames into. */
001464      szFrame = szPage + WAL_FRAME_HDRSIZE;
001465      aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ);
001466      SEH_FREE_ON_ERROR(0, aFrame);
001467      if( !aFrame ){
001468        rc = SQLITE_NOMEM_BKPT;
001469        goto recovery_error;
001470      }
001471      aData = &aFrame[WAL_FRAME_HDRSIZE];
001472      aPrivate = (u32*)&aData[szPage];
001473  
001474      /* Read all frames from the log file. */
001475      iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
001476      for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
001477        u32 *aShare;
001478        u32 iFrame;                 /* Index of last frame read */
001479        u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
001480        u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
001481        u32 nHdr, nHdr32;
001482        rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
001483        assert( aShare!=0 || rc!=SQLITE_OK );
001484        if( aShare==0 ) break;
001485        SEH_SET_ON_ERROR(iPg, aShare);
001486        pWal->apWiData[iPg] = aPrivate;
001487  
001488        for(iFrame=iFirst; iFrame<=iLast; iFrame++){
001489          i64 iOffset = walFrameOffset(iFrame, szPage);
001490          u32 pgno;                 /* Database page number for frame */
001491          u32 nTruncate;            /* dbsize field from frame header */
001492  
001493          /* Read and decode the next log frame. */
001494          rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
001495          if( rc!=SQLITE_OK ) break;
001496          isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
001497          if( !isValid ) break;
001498          rc = walIndexAppend(pWal, iFrame, pgno);
001499          if( NEVER(rc!=SQLITE_OK) ) break;
001500  
001501          /* If nTruncate is non-zero, this is a commit record. */
001502          if( nTruncate ){
001503            pWal->hdr.mxFrame = iFrame;
001504            pWal->hdr.nPage = nTruncate;
001505            pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
001506            testcase( szPage<=32768 );
001507            testcase( szPage>=65536 );
001508            aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
001509            aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
001510          }
001511        }
001512        pWal->apWiData[iPg] = aShare;
001513        SEH_SET_ON_ERROR(0,0);
001514        nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
001515        nHdr32 = nHdr / sizeof(u32);
001516  #ifndef SQLITE_SAFER_WALINDEX_RECOVERY
001517        /* Memcpy() should work fine here, on all reasonable implementations.
001518        ** Technically, memcpy() might change the destination to some
001519        ** intermediate value before setting to the final value, and that might
001520        ** cause a concurrent reader to malfunction.  Memcpy() is allowed to
001521        ** do that, according to the spec, but no memcpy() implementation that
001522        ** we know of actually does that, which is why we say that memcpy()
001523        ** is safe for this.  Memcpy() is certainly a lot faster.
001524        */
001525        memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
001526  #else
001527        /* In the event that some platform is found for which memcpy()
001528        ** changes the destination to some intermediate value before
001529        ** setting the final value, this alternative copy routine is
001530        ** provided.
001531        */
001532        {
001533          int i;
001534          for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
001535            if( aShare[i]!=aPrivate[i] ){
001536              /* Atomic memory operations are not required here because if
001537              ** the value needs to be changed, that means it is not being
001538              ** accessed concurrently. */
001539              aShare[i] = aPrivate[i];
001540            }
001541          }
001542        }
001543  #endif
001544        SEH_INJECT_FAULT;
001545        if( iFrame<=iLast ) break;
001546      }
001547  
001548      SEH_FREE_ON_ERROR(aFrame, 0);
001549      sqlite3_free(aFrame);
001550    }
001551  
001552  finished:
001553    if( rc==SQLITE_OK ){
001554      volatile WalCkptInfo *pInfo;
001555      int i;
001556      pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
001557      pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
001558      walIndexWriteHdr(pWal);
001559  
001560      /* Reset the checkpoint-header. This is safe because this thread is
001561      ** currently holding locks that exclude all other writers and
001562      ** checkpointers. Then set the values of read-mark slots 1 through N.
001563      */
001564      pInfo = walCkptInfo(pWal);
001565      pInfo->nBackfill = 0;
001566      pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
001567      pInfo->aReadMark[0] = 0;
001568      for(i=1; i<WAL_NREADER; i++){
001569        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
001570        if( rc==SQLITE_OK ){
001571          if( i==1 && pWal->hdr.mxFrame ){
001572            pInfo->aReadMark[i] = pWal->hdr.mxFrame;
001573          }else{
001574            pInfo->aReadMark[i] = READMARK_NOT_USED;
001575          }
001576          SEH_INJECT_FAULT;
001577          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
001578        }else if( rc!=SQLITE_BUSY ){
001579          goto recovery_error;
001580        }
001581      }
001582  
001583      /* If more than one frame was recovered from the log file, report an
001584      ** event via sqlite3_log(). This is to help with identifying performance
001585      ** problems caused by applications routinely shutting down without
001586      ** checkpointing the log file.
001587      */
001588      if( pWal->hdr.nPage ){
001589        sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
001590            "recovered %d frames from WAL file %s",
001591            pWal->hdr.mxFrame, pWal->zWalName
001592        );
001593      }
001594    }
001595  
001596  recovery_error:
001597    WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
001598    walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
001599    return rc;
001600  }
001601  
001602  /*
001603  ** Close an open wal-index.
001604  */
001605  static void walIndexClose(Wal *pWal, int isDelete){
001606    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
001607      int i;
001608      for(i=0; i<pWal->nWiData; i++){
001609        sqlite3_free((void *)pWal->apWiData[i]);
001610        pWal->apWiData[i] = 0;
001611      }
001612    }
001613    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
001614      sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
001615    }
001616  }
001617  
001618  /*
001619  ** Open a connection to the WAL file zWalName. The database file must
001620  ** already be opened on connection pDbFd. The buffer that zWalName points
001621  ** to must remain valid for the lifetime of the returned Wal* handle.
001622  **
001623  ** A SHARED lock should be held on the database file when this function
001624  ** is called. The purpose of this SHARED lock is to prevent any other
001625  ** client from unlinking the WAL or wal-index file. If another process
001626  ** were to do this just after this client opened one of these files, the
001627  ** system would be badly broken.
001628  **
001629  ** If the log file is successfully opened, SQLITE_OK is returned and
001630  ** *ppWal is set to point to a new WAL handle. If an error occurs,
001631  ** an SQLite error code is returned and *ppWal is left unmodified.
001632  */
001633  int sqlite3WalOpen(
001634    sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
001635    sqlite3_file *pDbFd,            /* The open database file */
001636    const char *zWalName,           /* Name of the WAL file */
001637    int bNoShm,                     /* True to run in heap-memory mode */
001638    i64 mxWalSize,                  /* Truncate WAL to this size on reset */
001639    Wal **ppWal                     /* OUT: Allocated Wal handle */
001640  ){
001641    int rc;                         /* Return Code */
001642    Wal *pRet;                      /* Object to allocate and return */
001643    int flags;                      /* Flags passed to OsOpen() */
001644  
001645    assert( zWalName && zWalName[0] );
001646    assert( pDbFd );
001647  
001648    /* Verify the values of various constants.  Any changes to the values
001649    ** of these constants would result in an incompatible on-disk format
001650    ** for the -shm file.  Any change that causes one of these asserts to
001651    ** fail is a backward compatibility problem, even if the change otherwise
001652    ** works.
001653    **
001654    ** This table also serves as a helpful cross-reference when trying to
001655    ** interpret hex dumps of the -shm file.
001656    */
001657    assert(    48 ==  sizeof(WalIndexHdr)  );
001658    assert(    40 ==  sizeof(WalCkptInfo)  );
001659    assert(   120 ==  WALINDEX_LOCK_OFFSET );
001660    assert(   136 ==  WALINDEX_HDR_SIZE    );
001661    assert(  4096 ==  HASHTABLE_NPAGE      );
001662    assert(  4062 ==  HASHTABLE_NPAGE_ONE  );
001663    assert(  8192 ==  HASHTABLE_NSLOT      );
001664    assert(   383 ==  HASHTABLE_HASH_1     );
001665    assert( 32768 ==  WALINDEX_PGSZ        );
001666    assert(     8 ==  SQLITE_SHM_NLOCK     );
001667    assert(     5 ==  WAL_NREADER          );
001668    assert(    24 ==  WAL_FRAME_HDRSIZE    );
001669    assert(    32 ==  WAL_HDRSIZE          );
001670    assert(   120 ==  WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK   );
001671    assert(   121 ==  WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK    );
001672    assert(   122 ==  WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK );
001673    assert(   123 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) );
001674    assert(   124 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) );
001675    assert(   125 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) );
001676    assert(   126 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) );
001677    assert(   127 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) );
001678  
001679    /* In the amalgamation, the os_unix.c and os_win.c source files come before
001680    ** this source file.  Verify that the #defines of the locking byte offsets
001681    ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
001682    ** For that matter, if the lock offset ever changes from its initial design
001683    ** value of 120, we need to know that so there is an assert() to check it.
001684    */
001685  #ifdef WIN_SHM_BASE
001686    assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
001687  #endif
001688  #ifdef UNIX_SHM_BASE
001689    assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
001690  #endif
001691  
001692  
001693    /* Allocate an instance of struct Wal to return. */
001694    *ppWal = 0;
001695    pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
001696    if( !pRet ){
001697      return SQLITE_NOMEM_BKPT;
001698    }
001699  
001700    pRet->pVfs = pVfs;
001701    pRet->pWalFd = (sqlite3_file *)&pRet[1];
001702    pRet->pDbFd = pDbFd;
001703    pRet->readLock = -1;
001704    pRet->mxWalSize = mxWalSize;
001705    pRet->zWalName = zWalName;
001706    pRet->syncHeader = 1;
001707    pRet->padToSectorBoundary = 1;
001708    pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
001709  
001710    /* Open file handle on the write-ahead log file. */
001711    flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
001712    rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
001713    if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
001714      pRet->readOnly = WAL_RDONLY;
001715    }
001716  
001717    if( rc!=SQLITE_OK ){
001718      walIndexClose(pRet, 0);
001719      sqlite3OsClose(pRet->pWalFd);
001720      sqlite3_free(pRet);
001721    }else{
001722      int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
001723      if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
001724      if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
001725        pRet->padToSectorBoundary = 0;
001726      }
001727      *ppWal = pRet;
001728      WALTRACE(("WAL%d: opened\n", pRet));
001729    }
001730    return rc;
001731  }
001732  
001733  /*
001734  ** Change the size to which the WAL file is truncated on each reset.
001735  */
001736  void sqlite3WalLimit(Wal *pWal, i64 iLimit){
001737    if( pWal ) pWal->mxWalSize = iLimit;
001738  }
001739  
001740  /*
001741  ** Find the smallest page number out of all pages held in the WAL that
001742  ** has not been returned by any prior invocation of this method on the
001743  ** same WalIterator object.   Write into *piFrame the frame index where
001744  ** that page was last written into the WAL.  Write into *piPage the page
001745  ** number.
001746  **
001747  ** Return 0 on success.  If there are no pages in the WAL with a page
001748  ** number larger than *piPage, then return 1.
001749  */
001750  static int walIteratorNext(
001751    WalIterator *p,               /* Iterator */
001752    u32 *piPage,                  /* OUT: The page number of the next page */
001753    u32 *piFrame                  /* OUT: Wal frame index of next page */
001754  ){
001755    u32 iMin;                     /* Result pgno must be greater than iMin */
001756    u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
001757    int i;                        /* For looping through segments */
001758  
001759    iMin = p->iPrior;
001760    assert( iMin<0xffffffff );
001761    for(i=p->nSegment-1; i>=0; i--){
001762      struct WalSegment *pSegment = &p->aSegment[i];
001763      while( pSegment->iNext<pSegment->nEntry ){
001764        u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
001765        if( iPg>iMin ){
001766          if( iPg<iRet ){
001767            iRet = iPg;
001768            *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
001769          }
001770          break;
001771        }
001772        pSegment->iNext++;
001773      }
001774    }
001775  
001776    *piPage = p->iPrior = iRet;
001777    return (iRet==0xFFFFFFFF);
001778  }
001779  
001780  /*
001781  ** This function merges two sorted lists into a single sorted list.
001782  **
001783  ** aLeft[] and aRight[] are arrays of indices.  The sort key is
001784  ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
001785  ** is guaranteed for all J<K:
001786  **
001787  **        aContent[aLeft[J]] < aContent[aLeft[K]]
001788  **        aContent[aRight[J]] < aContent[aRight[K]]
001789  **
001790  ** This routine overwrites aRight[] with a new (probably longer) sequence
001791  ** of indices such that the aRight[] contains every index that appears in
001792  ** either aLeft[] or the old aRight[] and such that the second condition
001793  ** above is still met.
001794  **
001795  ** The aContent[aLeft[X]] values will be unique for all X.  And the
001796  ** aContent[aRight[X]] values will be unique too.  But there might be
001797  ** one or more combinations of X and Y such that
001798  **
001799  **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
001800  **
001801  ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
001802  */
001803  static void walMerge(
001804    const u32 *aContent,            /* Pages in wal - keys for the sort */
001805    ht_slot *aLeft,                 /* IN: Left hand input list */
001806    int nLeft,                      /* IN: Elements in array *paLeft */
001807    ht_slot **paRight,              /* IN/OUT: Right hand input list */
001808    int *pnRight,                   /* IN/OUT: Elements in *paRight */
001809    ht_slot *aTmp                   /* Temporary buffer */
001810  ){
001811    int iLeft = 0;                  /* Current index in aLeft */
001812    int iRight = 0;                 /* Current index in aRight */
001813    int iOut = 0;                   /* Current index in output buffer */
001814    int nRight = *pnRight;
001815    ht_slot *aRight = *paRight;
001816  
001817    assert( nLeft>0 && nRight>0 );
001818    while( iRight<nRight || iLeft<nLeft ){
001819      ht_slot logpage;
001820      Pgno dbpage;
001821  
001822      if( (iLeft<nLeft)
001823       && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
001824      ){
001825        logpage = aLeft[iLeft++];
001826      }else{
001827        logpage = aRight[iRight++];
001828      }
001829      dbpage = aContent[logpage];
001830  
001831      aTmp[iOut++] = logpage;
001832      if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
001833  
001834      assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
001835      assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
001836    }
001837  
001838    *paRight = aLeft;
001839    *pnRight = iOut;
001840    memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
001841  }
001842  
001843  /*
001844  ** Sort the elements in list aList using aContent[] as the sort key.
001845  ** Remove elements with duplicate keys, preferring to keep the
001846  ** larger aList[] values.
001847  **
001848  ** The aList[] entries are indices into aContent[].  The values in
001849  ** aList[] are to be sorted so that for all J<K:
001850  **
001851  **      aContent[aList[J]] < aContent[aList[K]]
001852  **
001853  ** For any X and Y such that
001854  **
001855  **      aContent[aList[X]] == aContent[aList[Y]]
001856  **
001857  ** Keep the larger of the two values aList[X] and aList[Y] and discard
001858  ** the smaller.
001859  */
001860  static void walMergesort(
001861    const u32 *aContent,            /* Pages in wal */
001862    ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
001863    ht_slot *aList,                 /* IN/OUT: List to sort */
001864    int *pnList                     /* IN/OUT: Number of elements in aList[] */
001865  ){
001866    struct Sublist {
001867      int nList;                    /* Number of elements in aList */
001868      ht_slot *aList;               /* Pointer to sub-list content */
001869    };
001870  
001871    const int nList = *pnList;      /* Size of input list */
001872    int nMerge = 0;                 /* Number of elements in list aMerge */
001873    ht_slot *aMerge = 0;            /* List to be merged */
001874    int iList;                      /* Index into input list */
001875    u32 iSub = 0;                   /* Index into aSub array */
001876    struct Sublist aSub[13];        /* Array of sub-lists */
001877  
001878    memset(aSub, 0, sizeof(aSub));
001879    assert( nList<=HASHTABLE_NPAGE && nList>0 );
001880    assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
001881  
001882    for(iList=0; iList<nList; iList++){
001883      nMerge = 1;
001884      aMerge = &aList[iList];
001885      for(iSub=0; iList & (1<<iSub); iSub++){
001886        struct Sublist *p;
001887        assert( iSub<ArraySize(aSub) );
001888        p = &aSub[iSub];
001889        assert( p->aList && p->nList<=(1<<iSub) );
001890        assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
001891        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
001892      }
001893      aSub[iSub].aList = aMerge;
001894      aSub[iSub].nList = nMerge;
001895    }
001896  
001897    for(iSub++; iSub<ArraySize(aSub); iSub++){
001898      if( nList & (1<<iSub) ){
001899        struct Sublist *p;
001900        assert( iSub<ArraySize(aSub) );
001901        p = &aSub[iSub];
001902        assert( p->nList<=(1<<iSub) );
001903        assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
001904        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
001905      }
001906    }
001907    assert( aMerge==aList );
001908    *pnList = nMerge;
001909  
001910  #ifdef SQLITE_DEBUG
001911    {
001912      int i;
001913      for(i=1; i<*pnList; i++){
001914        assert( aContent[aList[i]] > aContent[aList[i-1]] );
001915      }
001916    }
001917  #endif
001918  }
001919  
001920  /*
001921  ** Free an iterator allocated by walIteratorInit().
001922  */
001923  static void walIteratorFree(WalIterator *p){
001924    sqlite3_free(p);
001925  }
001926  
001927  /*
001928  ** Construct a WalInterator object that can be used to loop over all
001929  ** pages in the WAL following frame nBackfill in ascending order. Frames
001930  ** nBackfill or earlier may be included - excluding them is an optimization
001931  ** only. The caller must hold the checkpoint lock.
001932  **
001933  ** On success, make *pp point to the newly allocated WalInterator object
001934  ** return SQLITE_OK. Otherwise, return an error code. If this routine
001935  ** returns an error, the value of *pp is undefined.
001936  **
001937  ** The calling routine should invoke walIteratorFree() to destroy the
001938  ** WalIterator object when it has finished with it.
001939  */
001940  static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
001941    WalIterator *p;                 /* Return value */
001942    int nSegment;                   /* Number of segments to merge */
001943    u32 iLast;                      /* Last frame in log */
001944    sqlite3_int64 nByte;            /* Number of bytes to allocate */
001945    int i;                          /* Iterator variable */
001946    ht_slot *aTmp;                  /* Temp space used by merge-sort */
001947    int rc = SQLITE_OK;             /* Return Code */
001948  
001949    /* This routine only runs while holding the checkpoint lock. And
001950    ** it only runs if there is actually content in the log (mxFrame>0).
001951    */
001952    assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
001953    iLast = pWal->hdr.mxFrame;
001954  
001955    /* Allocate space for the WalIterator object. */
001956    nSegment = walFramePage(iLast) + 1;
001957    nByte = sizeof(WalIterator)
001958          + (nSegment-1)*sizeof(struct WalSegment)
001959          + iLast*sizeof(ht_slot);
001960    p = (WalIterator *)sqlite3_malloc64(nByte
001961        + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
001962    );
001963    if( !p ){
001964      return SQLITE_NOMEM_BKPT;
001965    }
001966    memset(p, 0, nByte);
001967    p->nSegment = nSegment;
001968    aTmp = (ht_slot*)&(((u8*)p)[nByte]);
001969    SEH_FREE_ON_ERROR(0, p);
001970    for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
001971      WalHashLoc sLoc;
001972  
001973      rc = walHashGet(pWal, i, &sLoc);
001974      if( rc==SQLITE_OK ){
001975        int j;                      /* Counter variable */
001976        int nEntry;                 /* Number of entries in this segment */
001977        ht_slot *aIndex;            /* Sorted index for this segment */
001978  
001979        if( (i+1)==nSegment ){
001980          nEntry = (int)(iLast - sLoc.iZero);
001981        }else{
001982          nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
001983        }
001984        aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
001985        sLoc.iZero++;
001986  
001987        for(j=0; j<nEntry; j++){
001988          aIndex[j] = (ht_slot)j;
001989        }
001990        walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
001991        p->aSegment[i].iZero = sLoc.iZero;
001992        p->aSegment[i].nEntry = nEntry;
001993        p->aSegment[i].aIndex = aIndex;
001994        p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
001995      }
001996    }
001997    if( rc!=SQLITE_OK ){
001998      SEH_FREE_ON_ERROR(p, 0);
001999      walIteratorFree(p);
002000      p = 0;
002001    }
002002    *pp = p;
002003    return rc;
002004  }
002005  
002006  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
002007  /*
002008  ** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
002009  ** they are supported by the VFS, and (b) the database handle is configured
002010  ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
002011  ** or 0 otherwise.
002012  */
002013  static int walEnableBlocking(Wal *pWal){
002014    int res = 0;
002015    if( pWal->db ){
002016      int tmout = pWal->db->busyTimeout;
002017      if( tmout ){
002018        int rc;
002019        rc = sqlite3OsFileControl(
002020            pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
002021        );
002022        res = (rc==SQLITE_OK);
002023      }
002024    }
002025    return res;
002026  }
002027  
002028  /*
002029  ** Disable blocking locks.
002030  */
002031  static void walDisableBlocking(Wal *pWal){
002032    int tmout = 0;
002033    sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
002034  }
002035  
002036  /*
002037  ** If parameter bLock is true, attempt to enable blocking locks, take
002038  ** the WRITER lock, and then disable blocking locks. If blocking locks
002039  ** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
002040  ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
002041  ** an error if blocking locks can not be enabled.
002042  **
002043  ** If the bLock parameter is false and the WRITER lock is held, release it.
002044  */
002045  int sqlite3WalWriteLock(Wal *pWal, int bLock){
002046    int rc = SQLITE_OK;
002047    assert( pWal->readLock<0 || bLock==0 );
002048    if( bLock ){
002049      assert( pWal->db );
002050      if( walEnableBlocking(pWal) ){
002051        rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
002052        if( rc==SQLITE_OK ){
002053          pWal->writeLock = 1;
002054        }
002055        walDisableBlocking(pWal);
002056      }
002057    }else if( pWal->writeLock ){
002058      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
002059      pWal->writeLock = 0;
002060    }
002061    return rc;
002062  }
002063  
002064  /*
002065  ** Set the database handle used to determine if blocking locks are required.
002066  */
002067  void sqlite3WalDb(Wal *pWal, sqlite3 *db){
002068    pWal->db = db;
002069  }
002070  
002071  /*
002072  ** Take an exclusive WRITE lock. Blocking if so configured.
002073  */
002074  static int walLockWriter(Wal *pWal){
002075    int rc;
002076    walEnableBlocking(pWal);
002077    rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
002078    walDisableBlocking(pWal);
002079    return rc;
002080  }
002081  #else
002082  # define walEnableBlocking(x) 0
002083  # define walDisableBlocking(x)
002084  # define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)
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 connenction, 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 || SQLITE_OK==(rc = walLockWriter(pWal)) ){
002686          pWal->writeLock = 1;
002687          if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
002688            badHdr = walIndexTryHdr(pWal, pChanged);
002689            if( badHdr ){
002690              /* If the wal-index header is still malformed even while holding
002691              ** a WRITE lock, it can only mean that the header is corrupted and
002692              ** needs to be reconstructed.  So run recovery to do exactly that.
002693              */
002694              rc = walIndexRecover(pWal);
002695              *pChanged = 1;
002696            }
002697          }
002698          if( bWriteLock==0 ){
002699            pWal->writeLock = 0;
002700            walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
002701          }
002702        }
002703      }
002704    }
002705  
002706    /* If the header is read successfully, check the version number to make
002707    ** sure the wal-index was not constructed with some future format that
002708    ** this version of SQLite cannot understand.
002709    */
002710    if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
002711      rc = SQLITE_CANTOPEN_BKPT;
002712    }
002713    if( pWal->bShmUnreliable ){
002714      if( rc!=SQLITE_OK ){
002715        walIndexClose(pWal, 0);
002716        pWal->bShmUnreliable = 0;
002717        assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
002718        /* walIndexRecover() might have returned SHORT_READ if a concurrent
002719        ** writer truncated the WAL out from under it.  If that happens, it
002720        ** indicates that a writer has fixed the SHM file for us, so retry */
002721        if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
002722      }
002723      pWal->exclusiveMode = WAL_NORMAL_MODE;
002724    }
002725  
002726    return rc;
002727  }
002728  
002729  /*
002730  ** Open a transaction in a connection where the shared-memory is read-only
002731  ** and where we cannot verify that there is a separate write-capable connection
002732  ** on hand to keep the shared-memory up-to-date with the WAL file.
002733  **
002734  ** This can happen, for example, when the shared-memory is implemented by
002735  ** memory-mapping a *-shm file, where a prior writer has shut down and
002736  ** left the *-shm file on disk, and now the present connection is trying
002737  ** to use that database but lacks write permission on the *-shm file.
002738  ** Other scenarios are also possible, depending on the VFS implementation.
002739  **
002740  ** Precondition:
002741  **
002742  **    The *-wal file has been read and an appropriate wal-index has been
002743  **    constructed in pWal->apWiData[] using heap memory instead of shared
002744  **    memory.
002745  **
002746  ** If this function returns SQLITE_OK, then the read transaction has
002747  ** been successfully opened. In this case output variable (*pChanged)
002748  ** is set to true before returning if the caller should discard the
002749  ** contents of the page cache before proceeding. Or, if it returns
002750  ** WAL_RETRY, then the heap memory wal-index has been discarded and
002751  ** the caller should retry opening the read transaction from the
002752  ** beginning (including attempting to map the *-shm file).
002753  **
002754  ** If an error occurs, an SQLite error code is returned.
002755  */
002756  static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
002757    i64 szWal;                      /* Size of wal file on disk in bytes */
002758    i64 iOffset;                    /* Current offset when reading wal file */
002759    u8 aBuf[WAL_HDRSIZE];           /* Buffer to load WAL header into */
002760    u8 *aFrame = 0;                 /* Malloc'd buffer to load entire frame */
002761    int szFrame;                    /* Number of bytes in buffer aFrame[] */
002762    u8 *aData;                      /* Pointer to data part of aFrame buffer */
002763    volatile void *pDummy;          /* Dummy argument for xShmMap */
002764    int rc;                         /* Return code */
002765    u32 aSaveCksum[2];              /* Saved copy of pWal->hdr.aFrameCksum */
002766  
002767    assert( pWal->bShmUnreliable );
002768    assert( pWal->readOnly & WAL_SHM_RDONLY );
002769    assert( pWal->nWiData>0 && pWal->apWiData[0] );
002770  
002771    /* Take WAL_READ_LOCK(0). This has the effect of preventing any
002772    ** writers from running a checkpoint, but does not stop them
002773    ** from running recovery.  */
002774    rc = walLockShared(pWal, WAL_READ_LOCK(0));
002775    if( rc!=SQLITE_OK ){
002776      if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
002777      goto begin_unreliable_shm_out;
002778    }
002779    pWal->readLock = 0;
002780  
002781    /* Check to see if a separate writer has attached to the shared-memory area,
002782    ** thus making the shared-memory "reliable" again.  Do this by invoking
002783    ** the xShmMap() routine of the VFS and looking to see if the return
002784    ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
002785    **
002786    ** If the shared-memory is now "reliable" return WAL_RETRY, which will
002787    ** cause the heap-memory WAL-index to be discarded and the actual
002788    ** shared memory to be used in its place.
002789    **
002790    ** This step is important because, even though this connection is holding
002791    ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
002792    ** have already checkpointed the WAL file and, while the current
002793    ** is active, wrap the WAL and start overwriting frames that this
002794    ** process wants to use.
002795    **
002796    ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
002797    ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
002798    ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
002799    ** even if some external agent does a "chmod" to make the shared-memory
002800    ** writable by us, until sqlite3OsShmUnmap() has been called.
002801    ** This is a requirement on the VFS implementation.
002802     */
002803    rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
002804    assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
002805    if( rc!=SQLITE_READONLY_CANTINIT ){
002806      rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
002807      goto begin_unreliable_shm_out;
002808    }
002809  
002810    /* We reach this point only if the real shared-memory is still unreliable.
002811    ** Assume the in-memory WAL-index substitute is correct and load it
002812    ** into pWal->hdr.
002813    */
002814    memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
002815  
002816    /* Make sure some writer hasn't come in and changed the WAL file out
002817    ** from under us, then disconnected, while we were not looking.
002818    */
002819    rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
002820    if( rc!=SQLITE_OK ){
002821      goto begin_unreliable_shm_out;
002822    }
002823    if( szWal<WAL_HDRSIZE ){
002824      /* If the wal file is too small to contain a wal-header and the
002825      ** wal-index header has mxFrame==0, then it must be safe to proceed
002826      ** reading the database file only. However, the page cache cannot
002827      ** be trusted, as a read/write connection may have connected, written
002828      ** the db, run a checkpoint, truncated the wal file and disconnected
002829      ** since this client's last read transaction.  */
002830      *pChanged = 1;
002831      rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
002832      goto begin_unreliable_shm_out;
002833    }
002834  
002835    /* Check the salt keys at the start of the wal file still match. */
002836    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
002837    if( rc!=SQLITE_OK ){
002838      goto begin_unreliable_shm_out;
002839    }
002840    if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
002841      /* Some writer has wrapped the WAL file while we were not looking.
002842      ** Return WAL_RETRY which will cause the in-memory WAL-index to be
002843      ** rebuilt. */
002844      rc = WAL_RETRY;
002845      goto begin_unreliable_shm_out;
002846    }
002847  
002848    /* Allocate a buffer to read frames into */
002849    assert( (pWal->szPage & (pWal->szPage-1))==0 );
002850    assert( pWal->szPage>=512 && pWal->szPage<=65536 );
002851    szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
002852    aFrame = (u8 *)sqlite3_malloc64(szFrame);
002853    if( aFrame==0 ){
002854      rc = SQLITE_NOMEM_BKPT;
002855      goto begin_unreliable_shm_out;
002856    }
002857    aData = &aFrame[WAL_FRAME_HDRSIZE];
002858  
002859    /* Check to see if a complete transaction has been appended to the
002860    ** wal file since the heap-memory wal-index was created. If so, the
002861    ** heap-memory wal-index is discarded and WAL_RETRY returned to
002862    ** the caller.  */
002863    aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
002864    aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
002865    for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
002866        iOffset+szFrame<=szWal;
002867        iOffset+=szFrame
002868    ){
002869      u32 pgno;                   /* Database page number for frame */
002870      u32 nTruncate;              /* dbsize field from frame header */
002871  
002872      /* Read and decode the next log frame. */
002873      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
002874      if( rc!=SQLITE_OK ) break;
002875      if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
002876  
002877      /* If nTruncate is non-zero, then a complete transaction has been
002878      ** appended to this wal file. Set rc to WAL_RETRY and break out of
002879      ** the loop.  */
002880      if( nTruncate ){
002881        rc = WAL_RETRY;
002882        break;
002883      }
002884    }
002885    pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
002886    pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
002887  
002888   begin_unreliable_shm_out:
002889    sqlite3_free(aFrame);
002890    if( rc!=SQLITE_OK ){
002891      int i;
002892      for(i=0; i<pWal->nWiData; i++){
002893        sqlite3_free((void*)pWal->apWiData[i]);
002894        pWal->apWiData[i] = 0;
002895      }
002896      pWal->bShmUnreliable = 0;
002897      sqlite3WalEndReadTransaction(pWal);
002898      *pChanged = 1;
002899    }
002900    return rc;
002901  }
002902  
002903  /*
002904  ** Attempt to start a read transaction.  This might fail due to a race or
002905  ** other transient condition.  When that happens, it returns WAL_RETRY to
002906  ** indicate to the caller that it is safe to retry immediately.
002907  **
002908  ** On success return SQLITE_OK.  On a permanent failure (such an
002909  ** I/O error or an SQLITE_BUSY because another process is running
002910  ** recovery) return a positive error code.
002911  **
002912  ** The useWal parameter is true to force the use of the WAL and disable
002913  ** the case where the WAL is bypassed because it has been completely
002914  ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
002915  ** to make a copy of the wal-index header into pWal->hdr.  If the
002916  ** wal-index header has changed, *pChanged is set to 1 (as an indication
002917  ** to the caller that the local page cache is obsolete and needs to be
002918  ** flushed.)  When useWal==1, the wal-index header is assumed to already
002919  ** be loaded and the pChanged parameter is unused.
002920  **
002921  ** The caller must set the cnt parameter to the number of prior calls to
002922  ** this routine during the current read attempt that returned WAL_RETRY.
002923  ** This routine will start taking more aggressive measures to clear the
002924  ** race conditions after multiple WAL_RETRY returns, and after an excessive
002925  ** number of errors will ultimately return SQLITE_PROTOCOL.  The
002926  ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
002927  ** and is not honoring the locking protocol.  There is a vanishingly small
002928  ** chance that SQLITE_PROTOCOL could be returned because of a run of really
002929  ** bad luck when there is lots of contention for the wal-index, but that
002930  ** possibility is so small that it can be safely neglected, we believe.
002931  **
002932  ** On success, this routine obtains a read lock on
002933  ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
002934  ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
002935  ** that means the Wal does not hold any read lock.  The reader must not
002936  ** access any database page that is modified by a WAL frame up to and
002937  ** including frame number aReadMark[pWal->readLock].  The reader will
002938  ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
002939  ** Or if pWal->readLock==0, then the reader will ignore the WAL
002940  ** completely and get all content directly from the database file.
002941  ** If the useWal parameter is 1 then the WAL will never be ignored and
002942  ** this routine will always set pWal->readLock>0 on success.
002943  ** When the read transaction is completed, the caller must release the
002944  ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
002945  **
002946  ** This routine uses the nBackfill and aReadMark[] fields of the header
002947  ** to select a particular WAL_READ_LOCK() that strives to let the
002948  ** checkpoint process do as much work as possible.  This routine might
002949  ** update values of the aReadMark[] array in the header, but if it does
002950  ** so it takes care to hold an exclusive lock on the corresponding
002951  ** WAL_READ_LOCK() while changing values.
002952  */
002953  static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
002954    volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
002955    u32 mxReadMark;                 /* Largest aReadMark[] value */
002956    int mxI;                        /* Index of largest aReadMark[] value */
002957    int i;                          /* Loop counter */
002958    int rc = SQLITE_OK;             /* Return code  */
002959    u32 mxFrame;                    /* Wal frame to lock to */
002960  
002961    assert( pWal->readLock<0 );     /* Not currently locked */
002962  
002963    /* useWal may only be set for read/write connections */
002964    assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
002965  
002966    /* Take steps to avoid spinning forever if there is a protocol error.
002967    **
002968    ** Circumstances that cause a RETRY should only last for the briefest
002969    ** instances of time.  No I/O or other system calls are done while the
002970    ** locks are held, so the locks should not be held for very long. But
002971    ** if we are unlucky, another process that is holding a lock might get
002972    ** paged out or take a page-fault that is time-consuming to resolve,
002973    ** during the few nanoseconds that it is holding the lock.  In that case,
002974    ** it might take longer than normal for the lock to free.
002975    **
002976    ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
002977    ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
002978    ** is more of a scheduler yield than an actual delay.  But on the 10th
002979    ** an subsequent retries, the delays start becoming longer and longer,
002980    ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
002981    ** The total delay time before giving up is less than 10 seconds.
002982    */
002983    if( cnt>5 ){
002984      int nDelay = 1;                      /* Pause time in microseconds */
002985      if( cnt>100 ){
002986        VVA_ONLY( pWal->lockError = 1; )
002987        return SQLITE_PROTOCOL;
002988      }
002989      if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
002990      sqlite3OsSleep(pWal->pVfs, nDelay);
002991    }
002992  
002993    if( !useWal ){
002994      assert( rc==SQLITE_OK );
002995      if( pWal->bShmUnreliable==0 ){
002996        rc = walIndexReadHdr(pWal, pChanged);
002997      }
002998      if( rc==SQLITE_BUSY ){
002999        /* If there is not a recovery running in another thread or process
003000        ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
003001        ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
003002        ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
003003        ** would be technically correct.  But the race is benign since with
003004        ** WAL_RETRY this routine will be called again and will probably be
003005        ** right on the second iteration.
003006        */
003007        if( pWal->apWiData[0]==0 ){
003008          /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
003009          ** We assume this is a transient condition, so return WAL_RETRY. The
003010          ** xShmMap() implementation used by the default unix and win32 VFS
003011          ** modules may return SQLITE_BUSY due to a race condition in the
003012          ** code that determines whether or not the shared-memory region
003013          ** must be zeroed before the requested page is returned.
003014          */
003015          rc = WAL_RETRY;
003016        }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
003017          walUnlockShared(pWal, WAL_RECOVER_LOCK);
003018          rc = WAL_RETRY;
003019        }else if( rc==SQLITE_BUSY ){
003020          rc = SQLITE_BUSY_RECOVERY;
003021        }
003022      }
003023      if( rc!=SQLITE_OK ){
003024        return rc;
003025      }
003026      else if( pWal->bShmUnreliable ){
003027        return walBeginShmUnreliable(pWal, pChanged);
003028      }
003029    }
003030  
003031    assert( pWal->nWiData>0 );
003032    assert( pWal->apWiData[0]!=0 );
003033    pInfo = walCkptInfo(pWal);
003034    SEH_INJECT_FAULT;
003035    if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
003036  #ifdef SQLITE_ENABLE_SNAPSHOT
003037     && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
003038  #endif
003039    ){
003040      /* The WAL has been completely backfilled (or it is empty).
003041      ** and can be safely ignored.
003042      */
003043      rc = walLockShared(pWal, WAL_READ_LOCK(0));
003044      walShmBarrier(pWal);
003045      if( rc==SQLITE_OK ){
003046        if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
003047          /* It is not safe to allow the reader to continue here if frames
003048          ** may have been appended to the log before READ_LOCK(0) was obtained.
003049          ** When holding READ_LOCK(0), the reader ignores the entire log file,
003050          ** which implies that the database file contains a trustworthy
003051          ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
003052          ** happening, this is usually correct.
003053          **
003054          ** However, if frames have been appended to the log (or if the log
003055          ** is wrapped and written for that matter) before the READ_LOCK(0)
003056          ** is obtained, that is not necessarily true. A checkpointer may
003057          ** have started to backfill the appended frames but crashed before
003058          ** it finished. Leaving a corrupt image in the database file.
003059          */
003060          walUnlockShared(pWal, WAL_READ_LOCK(0));
003061          return WAL_RETRY;
003062        }
003063        pWal->readLock = 0;
003064        return SQLITE_OK;
003065      }else if( rc!=SQLITE_BUSY ){
003066        return rc;
003067      }
003068    }
003069  
003070    /* If we get this far, it means that the reader will want to use
003071    ** the WAL to get at content from recent commits.  The job now is
003072    ** to select one of the aReadMark[] entries that is closest to
003073    ** but not exceeding pWal->hdr.mxFrame and lock that entry.
003074    */
003075    mxReadMark = 0;
003076    mxI = 0;
003077    mxFrame = pWal->hdr.mxFrame;
003078  #ifdef SQLITE_ENABLE_SNAPSHOT
003079    if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
003080      mxFrame = pWal->pSnapshot->mxFrame;
003081    }
003082  #endif
003083    for(i=1; i<WAL_NREADER; i++){
003084      u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
003085      if( mxReadMark<=thisMark && thisMark<=mxFrame ){
003086        assert( thisMark!=READMARK_NOT_USED );
003087        mxReadMark = thisMark;
003088        mxI = i;
003089      }
003090    }
003091    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
003092     && (mxReadMark<mxFrame || mxI==0)
003093    ){
003094      for(i=1; i<WAL_NREADER; i++){
003095        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
003096        if( rc==SQLITE_OK ){
003097          AtomicStore(pInfo->aReadMark+i,mxFrame);
003098          mxReadMark = mxFrame;
003099          mxI = i;
003100          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
003101          break;
003102        }else if( rc!=SQLITE_BUSY ){
003103          return rc;
003104        }
003105      }
003106    }
003107    if( mxI==0 ){
003108      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
003109      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
003110    }
003111  
003112    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
003113    if( rc ){
003114      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
003115    }
003116    /* Now that the read-lock has been obtained, check that neither the
003117    ** value in the aReadMark[] array or the contents of the wal-index
003118    ** header have changed.
003119    **
003120    ** It is necessary to check that the wal-index header did not change
003121    ** between the time it was read and when the shared-lock was obtained
003122    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
003123    ** that the log file may have been wrapped by a writer, or that frames
003124    ** that occur later in the log than pWal->hdr.mxFrame may have been
003125    ** copied into the database by a checkpointer. If either of these things
003126    ** happened, then reading the database with the current value of
003127    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
003128    ** instead.
003129    **
003130    ** Before checking that the live wal-index header has not changed
003131    ** since it was read, set Wal.minFrame to the first frame in the wal
003132    ** file that has not yet been checkpointed. This client will not need
003133    ** to read any frames earlier than minFrame from the wal file - they
003134    ** can be safely read directly from the database file.
003135    **
003136    ** Because a ShmBarrier() call is made between taking the copy of
003137    ** nBackfill and checking that the wal-header in shared-memory still
003138    ** matches the one cached in pWal->hdr, it is guaranteed that the
003139    ** checkpointer that set nBackfill was not working with a wal-index
003140    ** header newer than that cached in pWal->hdr. If it were, that could
003141    ** cause a problem. The checkpointer could omit to checkpoint
003142    ** a version of page X that lies before pWal->minFrame (call that version
003143    ** A) on the basis that there is a newer version (version B) of the same
003144    ** page later in the wal file. But if version B happens to like past
003145    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
003146    ** that it can read version A from the database file. However, since
003147    ** we can guarantee that the checkpointer that set nBackfill could not
003148    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
003149    */
003150    pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT;
003151    walShmBarrier(pWal);
003152    if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
003153     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
003154    ){
003155      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
003156      return WAL_RETRY;
003157    }else{
003158      assert( mxReadMark<=pWal->hdr.mxFrame );
003159      pWal->readLock = (i16)mxI;
003160    }
003161    return rc;
003162  }
003163  
003164  #ifdef SQLITE_ENABLE_SNAPSHOT
003165  /*
003166  ** This function does the work of sqlite3WalSnapshotRecover().
003167  */
003168  static int walSnapshotRecover(
003169    Wal *pWal,                      /* WAL handle */
003170    void *pBuf1,                    /* Temp buffer pWal->szPage bytes in size */
003171    void *pBuf2                     /* Temp buffer pWal->szPage bytes in size */
003172  ){
003173    int szPage = (int)pWal->szPage;
003174    int rc;
003175    i64 szDb;                       /* Size of db file in bytes */
003176  
003177    rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
003178    if( rc==SQLITE_OK ){
003179      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
003180      u32 i = pInfo->nBackfillAttempted;
003181      for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
003182        WalHashLoc sLoc;          /* Hash table location */
003183        u32 pgno;                 /* Page number in db file */
003184        i64 iDbOff;               /* Offset of db file entry */
003185        i64 iWalOff;              /* Offset of wal file entry */
003186  
003187        rc = walHashGet(pWal, walFramePage(i), &sLoc);
003188        if( rc!=SQLITE_OK ) break;
003189        assert( i - sLoc.iZero - 1 >=0 );
003190        pgno = sLoc.aPgno[i-sLoc.iZero-1];
003191        iDbOff = (i64)(pgno-1) * szPage;
003192  
003193        if( iDbOff+szPage<=szDb ){
003194          iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
003195          rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
003196  
003197          if( rc==SQLITE_OK ){
003198            rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
003199          }
003200  
003201          if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
003202            break;
003203          }
003204        }
003205  
003206        pInfo->nBackfillAttempted = i-1;
003207      }
003208    }
003209  
003210    return rc;
003211  }
003212  
003213  /*
003214  ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
003215  ** variable so that older snapshots can be accessed. To do this, loop
003216  ** through all wal frames from nBackfillAttempted to (nBackfill+1),
003217  ** comparing their content to the corresponding page with the database
003218  ** file, if any. Set nBackfillAttempted to the frame number of the
003219  ** first frame for which the wal file content matches the db file.
003220  **
003221  ** This is only really safe if the file-system is such that any page
003222  ** writes made by earlier checkpointers were atomic operations, which
003223  ** is not always true. It is also possible that nBackfillAttempted
003224  ** may be left set to a value larger than expected, if a wal frame
003225  ** contains content that duplicate of an earlier version of the same
003226  ** page.
003227  **
003228  ** SQLITE_OK is returned if successful, or an SQLite error code if an
003229  ** error occurs. It is not an error if nBackfillAttempted cannot be
003230  ** decreased at all.
003231  */
003232  int sqlite3WalSnapshotRecover(Wal *pWal){
003233    int rc;
003234  
003235    assert( pWal->readLock>=0 );
003236    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
003237    if( rc==SQLITE_OK ){
003238      void *pBuf1 = sqlite3_malloc(pWal->szPage);
003239      void *pBuf2 = sqlite3_malloc(pWal->szPage);
003240      if( pBuf1==0 || pBuf2==0 ){
003241        rc = SQLITE_NOMEM;
003242      }else{
003243        pWal->ckptLock = 1;
003244        SEH_TRY {
003245          rc = walSnapshotRecover(pWal, pBuf1, pBuf2);
003246        }
003247        SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003248        pWal->ckptLock = 0;
003249      }
003250  
003251      sqlite3_free(pBuf1);
003252      sqlite3_free(pBuf2);
003253      walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
003254    }
003255  
003256    return rc;
003257  }
003258  #endif /* SQLITE_ENABLE_SNAPSHOT */
003259  
003260  /*
003261  ** This function does the work of sqlite3WalBeginReadTransaction() (see 
003262  ** below). That function simply calls this one inside an SEH_TRY{...} block.
003263  */
003264  static int walBeginReadTransaction(Wal *pWal, int *pChanged){
003265    int rc;                         /* Return code */
003266    int cnt = 0;                    /* Number of TryBeginRead attempts */
003267  #ifdef SQLITE_ENABLE_SNAPSHOT
003268    int ckptLock = 0;
003269    int bChanged = 0;
003270    WalIndexHdr *pSnapshot = pWal->pSnapshot;
003271  #endif
003272  
003273    assert( pWal->ckptLock==0 );
003274    assert( pWal->nSehTry>0 );
003275  
003276  #ifdef SQLITE_ENABLE_SNAPSHOT
003277    if( pSnapshot ){
003278      if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
003279        bChanged = 1;
003280      }
003281  
003282      /* It is possible that there is a checkpointer thread running
003283      ** concurrent with this code. If this is the case, it may be that the
003284      ** checkpointer has already determined that it will checkpoint
003285      ** snapshot X, where X is later in the wal file than pSnapshot, but
003286      ** has not yet set the pInfo->nBackfillAttempted variable to indicate
003287      ** its intent. To avoid the race condition this leads to, ensure that
003288      ** there is no checkpointer process by taking a shared CKPT lock
003289      ** before checking pInfo->nBackfillAttempted.  */
003290      (void)walEnableBlocking(pWal);
003291      rc = walLockShared(pWal, WAL_CKPT_LOCK);
003292      walDisableBlocking(pWal);
003293  
003294      if( rc!=SQLITE_OK ){
003295        return rc;
003296      }
003297      ckptLock = 1;
003298    }
003299  #endif
003300  
003301    do{
003302      rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
003303    }while( rc==WAL_RETRY );
003304    testcase( (rc&0xff)==SQLITE_BUSY );
003305    testcase( (rc&0xff)==SQLITE_IOERR );
003306    testcase( rc==SQLITE_PROTOCOL );
003307    testcase( rc==SQLITE_OK );
003308  
003309  #ifdef SQLITE_ENABLE_SNAPSHOT
003310    if( rc==SQLITE_OK ){
003311      if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
003312        /* At this point the client has a lock on an aReadMark[] slot holding
003313        ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
003314        ** is populated with the wal-index header corresponding to the head
003315        ** of the wal file. Verify that pSnapshot is still valid before
003316        ** continuing.  Reasons why pSnapshot might no longer be valid:
003317        **
003318        **    (1)  The WAL file has been reset since the snapshot was taken.
003319        **         In this case, the salt will have changed.
003320        **
003321        **    (2)  A checkpoint as been attempted that wrote frames past
003322        **         pSnapshot->mxFrame into the database file.  Note that the
003323        **         checkpoint need not have completed for this to cause problems.
003324        */
003325        volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
003326  
003327        assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
003328        assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
003329  
003330        /* Check that the wal file has not been wrapped. Assuming that it has
003331        ** not, also check that no checkpointer has attempted to checkpoint any
003332        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
003333        ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
003334        ** with *pSnapshot and set *pChanged as appropriate for opening the
003335        ** snapshot.  */
003336        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
003337         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
003338        ){
003339          assert( pWal->readLock>0 );
003340          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
003341          *pChanged = bChanged;
003342        }else{
003343          rc = SQLITE_ERROR_SNAPSHOT;
003344        }
003345  
003346        /* A client using a non-current snapshot may not ignore any frames
003347        ** from the start of the wal file. This is because, for a system
003348        ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
003349        ** have omitted to checkpoint a frame earlier than minFrame in
003350        ** the file because there exists a frame after iSnapshot that
003351        ** is the same database page.  */
003352        pWal->minFrame = 1;
003353  
003354        if( rc!=SQLITE_OK ){
003355          sqlite3WalEndReadTransaction(pWal);
003356        }
003357      }
003358    }
003359  
003360    /* Release the shared CKPT lock obtained above. */
003361    if( ckptLock ){
003362      assert( pSnapshot );
003363      walUnlockShared(pWal, WAL_CKPT_LOCK);
003364    }
003365  #endif
003366    return rc;
003367  }
003368  
003369  /*
003370  ** Begin a read transaction on the database.
003371  **
003372  ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
003373  ** it takes a snapshot of the state of the WAL and wal-index for the current
003374  ** instant in time.  The current thread will continue to use this snapshot.
003375  ** Other threads might append new content to the WAL and wal-index but
003376  ** that extra content is ignored by the current thread.
003377  **
003378  ** If the database contents have changes since the previous read
003379  ** transaction, then *pChanged is set to 1 before returning.  The
003380  ** Pager layer will use this to know that its cache is stale and
003381  ** needs to be flushed.
003382  */
003383  int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
003384    int rc;
003385    SEH_TRY {
003386      rc = walBeginReadTransaction(pWal, pChanged);
003387    }
003388    SEH_EXCEPT( rc = walHandleException(pWal); )
003389    return rc;
003390  }
003391  
003392  /*
003393  ** Finish with a read transaction.  All this does is release the
003394  ** read-lock.
003395  */
003396  void sqlite3WalEndReadTransaction(Wal *pWal){
003397    sqlite3WalEndWriteTransaction(pWal);
003398    if( pWal->readLock>=0 ){
003399      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
003400      pWal->readLock = -1;
003401    }
003402  }
003403  
003404  /*
003405  ** Search the wal file for page pgno. If found, set *piRead to the frame that
003406  ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
003407  ** to zero.
003408  **
003409  ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
003410  ** error does occur, the final value of *piRead is undefined.
003411  */
003412  static int walFindFrame(
003413    Wal *pWal,                      /* WAL handle */
003414    Pgno pgno,                      /* Database page number to read data for */
003415    u32 *piRead                     /* OUT: Frame number (or zero) */
003416  ){
003417    u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
003418    u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
003419    int iHash;                      /* Used to loop through N hash tables */
003420    int iMinHash;
003421  
003422    /* This routine is only be called from within a read transaction. */
003423    assert( pWal->readLock>=0 || pWal->lockError );
003424  
003425    /* If the "last page" field of the wal-index header snapshot is 0, then
003426    ** no data will be read from the wal under any circumstances. Return early
003427    ** in this case as an optimization.  Likewise, if pWal->readLock==0,
003428    ** then the WAL is ignored by the reader so return early, as if the
003429    ** WAL were empty.
003430    */
003431    if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
003432      *piRead = 0;
003433      return SQLITE_OK;
003434    }
003435  
003436    /* Search the hash table or tables for an entry matching page number
003437    ** pgno. Each iteration of the following for() loop searches one
003438    ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
003439    **
003440    ** This code might run concurrently to the code in walIndexAppend()
003441    ** that adds entries to the wal-index (and possibly to this hash
003442    ** table). This means the value just read from the hash
003443    ** slot (aHash[iKey]) may have been added before or after the
003444    ** current read transaction was opened. Values added after the
003445    ** read transaction was opened may have been written incorrectly -
003446    ** i.e. these slots may contain garbage data. However, we assume
003447    ** that any slots written before the current read transaction was
003448    ** opened remain unmodified.
003449    **
003450    ** For the reasons above, the if(...) condition featured in the inner
003451    ** loop of the following block is more stringent that would be required
003452    ** if we had exclusive access to the hash-table:
003453    **
003454    **   (aPgno[iFrame]==pgno):
003455    **     This condition filters out normal hash-table collisions.
003456    **
003457    **   (iFrame<=iLast):
003458    **     This condition filters out entries that were added to the hash
003459    **     table after the current read-transaction had started.
003460    */
003461    iMinHash = walFramePage(pWal->minFrame);
003462    for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
003463      WalHashLoc sLoc;              /* Hash table location */
003464      int iKey;                     /* Hash slot index */
003465      int nCollide;                 /* Number of hash collisions remaining */
003466      int rc;                       /* Error code */
003467      u32 iH;
003468  
003469      rc = walHashGet(pWal, iHash, &sLoc);
003470      if( rc!=SQLITE_OK ){
003471        return rc;
003472      }
003473      nCollide = HASHTABLE_NSLOT;
003474      iKey = walHash(pgno);
003475      SEH_INJECT_FAULT;
003476      while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
003477        u32 iFrame = iH + sLoc.iZero;
003478        if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
003479          assert( iFrame>iRead || CORRUPT_DB );
003480          iRead = iFrame;
003481        }
003482        if( (nCollide--)==0 ){
003483          return SQLITE_CORRUPT_BKPT;
003484        }
003485        iKey = walNextHash(iKey);
003486      }
003487      if( iRead ) break;
003488    }
003489  
003490  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
003491    /* If expensive assert() statements are available, do a linear search
003492    ** of the wal-index file content. Make sure the results agree with the
003493    ** result obtained using the hash indexes above.  */
003494    {
003495      u32 iRead2 = 0;
003496      u32 iTest;
003497      assert( pWal->bShmUnreliable || pWal->minFrame>0 );
003498      for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
003499        if( walFramePgno(pWal, iTest)==pgno ){
003500          iRead2 = iTest;
003501          break;
003502        }
003503      }
003504      assert( iRead==iRead2 );
003505    }
003506  #endif
003507  
003508    *piRead = iRead;
003509    return SQLITE_OK;
003510  }
003511  
003512  /*
003513  ** Search the wal file for page pgno. If found, set *piRead to the frame that
003514  ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
003515  ** to zero.
003516  **
003517  ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
003518  ** error does occur, the final value of *piRead is undefined.
003519  **
003520  ** The difference between this function and walFindFrame() is that this
003521  ** function wraps walFindFrame() in an SEH_TRY{...} block.
003522  */
003523  int sqlite3WalFindFrame(
003524    Wal *pWal,                      /* WAL handle */
003525    Pgno pgno,                      /* Database page number to read data for */
003526    u32 *piRead                     /* OUT: Frame number (or zero) */
003527  ){
003528    int rc;
003529    SEH_TRY {
003530      rc = walFindFrame(pWal, pgno, piRead);
003531    }
003532    SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003533    return rc;
003534  }
003535  
003536  /*
003537  ** Read the contents of frame iRead from the wal file into buffer pOut
003538  ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
003539  ** error code otherwise.
003540  */
003541  int sqlite3WalReadFrame(
003542    Wal *pWal,                      /* WAL handle */
003543    u32 iRead,                      /* Frame to read */
003544    int nOut,                       /* Size of buffer pOut in bytes */
003545    u8 *pOut                        /* Buffer to write page data to */
003546  ){
003547    int sz;
003548    i64 iOffset;
003549    sz = pWal->hdr.szPage;
003550    sz = (sz&0xfe00) + ((sz&0x0001)<<16);
003551    testcase( sz<=32768 );
003552    testcase( sz>=65536 );
003553    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
003554    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
003555    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
003556  }
003557  
003558  /*
003559  ** Return the size of the database in pages (or zero, if unknown).
003560  */
003561  Pgno sqlite3WalDbsize(Wal *pWal){
003562    if( pWal && ALWAYS(pWal->readLock>=0) ){
003563      return pWal->hdr.nPage;
003564    }
003565    return 0;
003566  }
003567  
003568  
003569  /*
003570  ** This function starts a write transaction on the WAL.
003571  **
003572  ** A read transaction must have already been started by a prior call
003573  ** to sqlite3WalBeginReadTransaction().
003574  **
003575  ** If another thread or process has written into the database since
003576  ** the read transaction was started, then it is not possible for this
003577  ** thread to write as doing so would cause a fork.  So this routine
003578  ** returns SQLITE_BUSY in that case and no write transaction is started.
003579  **
003580  ** There can only be a single writer active at a time.
003581  */
003582  int sqlite3WalBeginWriteTransaction(Wal *pWal){
003583    int rc;
003584  
003585  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
003586    /* If the write-lock is already held, then it was obtained before the
003587    ** read-transaction was even opened, making this call a no-op.
003588    ** Return early. */
003589    if( pWal->writeLock ){
003590      assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
003591      return SQLITE_OK;
003592    }
003593  #endif
003594  
003595    /* Cannot start a write transaction without first holding a read
003596    ** transaction. */
003597    assert( pWal->readLock>=0 );
003598    assert( pWal->writeLock==0 && pWal->iReCksum==0 );
003599  
003600    if( pWal->readOnly ){
003601      return SQLITE_READONLY;
003602    }
003603  
003604    /* Only one writer allowed at a time.  Get the write lock.  Return
003605    ** SQLITE_BUSY if unable.
003606    */
003607    rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
003608    if( rc ){
003609      return rc;
003610    }
003611    pWal->writeLock = 1;
003612  
003613    /* If another connection has written to the database file since the
003614    ** time the read transaction on this connection was started, then
003615    ** the write is disallowed.
003616    */
003617    SEH_TRY {
003618      if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
003619        rc = SQLITE_BUSY_SNAPSHOT;
003620      }
003621    }
003622    SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003623  
003624    if( rc!=SQLITE_OK ){
003625      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
003626      pWal->writeLock = 0;
003627    }
003628    return rc;
003629  }
003630  
003631  /*
003632  ** End a write transaction.  The commit has already been done.  This
003633  ** routine merely releases the lock.
003634  */
003635  int sqlite3WalEndWriteTransaction(Wal *pWal){
003636    if( pWal->writeLock ){
003637      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
003638      pWal->writeLock = 0;
003639      pWal->iReCksum = 0;
003640      pWal->truncateOnCommit = 0;
003641    }
003642    return SQLITE_OK;
003643  }
003644  
003645  /*
003646  ** If any data has been written (but not committed) to the log file, this
003647  ** function moves the write-pointer back to the start of the transaction.
003648  **
003649  ** Additionally, the callback function is invoked for each frame written
003650  ** to the WAL since the start of the transaction. If the callback returns
003651  ** other than SQLITE_OK, it is not invoked again and the error code is
003652  ** returned to the caller.
003653  **
003654  ** Otherwise, if the callback function does not return an error, this
003655  ** function returns SQLITE_OK.
003656  */
003657  int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
003658    int rc = SQLITE_OK;
003659    if( ALWAYS(pWal->writeLock) ){
003660      Pgno iMax = pWal->hdr.mxFrame;
003661      Pgno iFrame;
003662  
003663      SEH_TRY {
003664        /* Restore the clients cache of the wal-index header to the state it
003665        ** was in before the client began writing to the database. 
003666        */
003667        memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
003668    
003669        for(iFrame=pWal->hdr.mxFrame+1; 
003670            ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
003671            iFrame++
003672        ){
003673          /* This call cannot fail. Unless the page for which the page number
003674          ** is passed as the second argument is (a) in the cache and
003675          ** (b) has an outstanding reference, then xUndo is either a no-op
003676          ** (if (a) is false) or simply expels the page from the cache (if (b)
003677          ** is false).
003678          **
003679          ** If the upper layer is doing a rollback, it is guaranteed that there
003680          ** are no outstanding references to any page other than page 1. And
003681          ** page 1 is never written to the log until the transaction is
003682          ** committed. As a result, the call to xUndo may not fail.
003683          */
003684          assert( walFramePgno(pWal, iFrame)!=1 );
003685          rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
003686        }
003687        if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
003688      }
003689      SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003690    }
003691    return rc;
003692  }
003693  
003694  /*
003695  ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
003696  ** values. This function populates the array with values required to
003697  ** "rollback" the write position of the WAL handle back to the current
003698  ** point in the event of a savepoint rollback (via WalSavepointUndo()).
003699  */
003700  void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
003701    assert( pWal->writeLock );
003702    aWalData[0] = pWal->hdr.mxFrame;
003703    aWalData[1] = pWal->hdr.aFrameCksum[0];
003704    aWalData[2] = pWal->hdr.aFrameCksum[1];
003705    aWalData[3] = pWal->nCkpt;
003706  }
003707  
003708  /*
003709  ** Move the write position of the WAL back to the point identified by
003710  ** the values in the aWalData[] array. aWalData must point to an array
003711  ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
003712  ** by a call to WalSavepoint().
003713  */
003714  int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
003715    int rc = SQLITE_OK;
003716  
003717    assert( pWal->writeLock );
003718    assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
003719  
003720    if( aWalData[3]!=pWal->nCkpt ){
003721      /* This savepoint was opened immediately after the write-transaction
003722      ** was started. Right after that, the writer decided to wrap around
003723      ** to the start of the log. Update the savepoint values to match.
003724      */
003725      aWalData[0] = 0;
003726      aWalData[3] = pWal->nCkpt;
003727    }
003728  
003729    if( aWalData[0]<pWal->hdr.mxFrame ){
003730      pWal->hdr.mxFrame = aWalData[0];
003731      pWal->hdr.aFrameCksum[0] = aWalData[1];
003732      pWal->hdr.aFrameCksum[1] = aWalData[2];
003733      SEH_TRY {
003734        walCleanupHash(pWal);
003735      }
003736      SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )
003737    }
003738  
003739    return rc;
003740  }
003741  
003742  /*
003743  ** This function is called just before writing a set of frames to the log
003744  ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
003745  ** to the current log file, it is possible to overwrite the start of the
003746  ** existing log file with the new frames (i.e. "reset" the log). If so,
003747  ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
003748  ** unchanged.
003749  **
003750  ** SQLITE_OK is returned if no error is encountered (regardless of whether
003751  ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
003752  ** if an error occurs.
003753  */
003754  static int walRestartLog(Wal *pWal){
003755    int rc = SQLITE_OK;
003756    int cnt;
003757  
003758    if( pWal->readLock==0 ){
003759      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
003760      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
003761      if( pInfo->nBackfill>0 ){
003762        u32 salt1;
003763        sqlite3_randomness(4, &salt1);
003764        rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
003765        if( rc==SQLITE_OK ){
003766          /* If all readers are using WAL_READ_LOCK(0) (in other words if no
003767          ** readers are currently using the WAL), then the transactions
003768          ** frames will overwrite the start of the existing log. Update the
003769          ** wal-index header to reflect this.
003770          **
003771          ** In theory it would be Ok to update the cache of the header only
003772          ** at this point. But updating the actual wal-index header is also
003773          ** safe and means there is no special case for sqlite3WalUndo()
003774          ** to handle if this transaction is rolled back.  */
003775          walRestartHdr(pWal, salt1);
003776          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
003777        }else if( rc!=SQLITE_BUSY ){
003778          return rc;
003779        }
003780      }
003781      walUnlockShared(pWal, WAL_READ_LOCK(0));
003782      pWal->readLock = -1;
003783      cnt = 0;
003784      do{
003785        int notUsed;
003786        rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
003787      }while( rc==WAL_RETRY );
003788      assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
003789      testcase( (rc&0xff)==SQLITE_IOERR );
003790      testcase( rc==SQLITE_PROTOCOL );
003791      testcase( rc==SQLITE_OK );
003792    }
003793    return rc;
003794  }
003795  
003796  /*
003797  ** Information about the current state of the WAL file and where
003798  ** the next fsync should occur - passed from sqlite3WalFrames() into
003799  ** walWriteToLog().
003800  */
003801  typedef struct WalWriter {
003802    Wal *pWal;                   /* The complete WAL information */
003803    sqlite3_file *pFd;           /* The WAL file to which we write */
003804    sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
003805    int syncFlags;               /* Flags for the fsync */
003806    int szPage;                  /* Size of one page */
003807  } WalWriter;
003808  
003809  /*
003810  ** Write iAmt bytes of content into the WAL file beginning at iOffset.
003811  ** Do a sync when crossing the p->iSyncPoint boundary.
003812  **
003813  ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
003814  ** first write the part before iSyncPoint, then sync, then write the
003815  ** rest.
003816  */
003817  static int walWriteToLog(
003818    WalWriter *p,              /* WAL to write to */
003819    void *pContent,            /* Content to be written */
003820    int iAmt,                  /* Number of bytes to write */
003821    sqlite3_int64 iOffset      /* Start writing at this offset */
003822  ){
003823    int rc;
003824    if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
003825      int iFirstAmt = (int)(p->iSyncPoint - iOffset);
003826      rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
003827      if( rc ) return rc;
003828      iOffset += iFirstAmt;
003829      iAmt -= iFirstAmt;
003830      pContent = (void*)(iFirstAmt + (char*)pContent);
003831      assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
003832      rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
003833      if( iAmt==0 || rc ) return rc;
003834    }
003835    rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
003836    return rc;
003837  }
003838  
003839  /*
003840  ** Write out a single frame of the WAL
003841  */
003842  static int walWriteOneFrame(
003843    WalWriter *p,               /* Where to write the frame */
003844    PgHdr *pPage,               /* The page of the frame to be written */
003845    int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
003846    sqlite3_int64 iOffset       /* Byte offset at which to write */
003847  ){
003848    int rc;                         /* Result code from subfunctions */
003849    void *pData;                    /* Data actually written */
003850    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
003851    pData = pPage->pData;
003852    walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
003853    rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
003854    if( rc ) return rc;
003855    /* Write the page data */
003856    rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
003857    return rc;
003858  }
003859  
003860  /*
003861  ** This function is called as part of committing a transaction within which
003862  ** one or more frames have been overwritten. It updates the checksums for
003863  ** all frames written to the wal file by the current transaction starting
003864  ** with the earliest to have been overwritten.
003865  **
003866  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
003867  */
003868  static int walRewriteChecksums(Wal *pWal, u32 iLast){
003869    const int szPage = pWal->szPage;/* Database page size */
003870    int rc = SQLITE_OK;             /* Return code */
003871    u8 *aBuf;                       /* Buffer to load data from wal file into */
003872    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
003873    u32 iRead;                      /* Next frame to read from wal file */
003874    i64 iCksumOff;
003875  
003876    aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
003877    if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
003878  
003879    /* Find the checksum values to use as input for the recalculating the
003880    ** first checksum. If the first frame is frame 1 (implying that the current
003881    ** transaction restarted the wal file), these values must be read from the
003882    ** wal-file header. Otherwise, read them from the frame header of the
003883    ** previous frame.  */
003884    assert( pWal->iReCksum>0 );
003885    if( pWal->iReCksum==1 ){
003886      iCksumOff = 24;
003887    }else{
003888      iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
003889    }
003890    rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
003891    pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
003892    pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
003893  
003894    iRead = pWal->iReCksum;
003895    pWal->iReCksum = 0;
003896    for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
003897      i64 iOff = walFrameOffset(iRead, szPage);
003898      rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
003899      if( rc==SQLITE_OK ){
003900        u32 iPgno, nDbSize;
003901        iPgno = sqlite3Get4byte(aBuf);
003902        nDbSize = sqlite3Get4byte(&aBuf[4]);
003903  
003904        walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
003905        rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
003906      }
003907    }
003908  
003909    sqlite3_free(aBuf);
003910    return rc;
003911  }
003912  
003913  /*
003914  ** Write a set of frames to the log. The caller must hold the write-lock
003915  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
003916  */
003917  static int walFrames(
003918    Wal *pWal,                      /* Wal handle to write to */
003919    int szPage,                     /* Database page-size in bytes */
003920    PgHdr *pList,                   /* List of dirty pages to write */
003921    Pgno nTruncate,                 /* Database size after this commit */
003922    int isCommit,                   /* True if this is a commit */
003923    int sync_flags                  /* Flags to pass to OsSync() (or 0) */
003924  ){
003925    int rc;                         /* Used to catch return codes */
003926    u32 iFrame;                     /* Next frame address */
003927    PgHdr *p;                       /* Iterator to run through pList with. */
003928    PgHdr *pLast = 0;               /* Last frame in list */
003929    int nExtra = 0;                 /* Number of extra copies of last page */
003930    int szFrame;                    /* The size of a single frame */
003931    i64 iOffset;                    /* Next byte to write in WAL file */
003932    WalWriter w;                    /* The writer */
003933    u32 iFirst = 0;                 /* First frame that may be overwritten */
003934    WalIndexHdr *pLive;             /* Pointer to shared header */
003935  
003936    assert( pList );
003937    assert( pWal->writeLock );
003938  
003939    /* If this frame set completes a transaction, then nTruncate>0.  If
003940    ** nTruncate==0 then this frame set does not complete the transaction. */
003941    assert( (isCommit!=0)==(nTruncate!=0) );
003942  
003943  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
003944    { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
003945      WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
003946                pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
003947    }
003948  #endif
003949  
003950    pLive = (WalIndexHdr*)walIndexHdr(pWal);
003951    if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
003952      iFirst = pLive->mxFrame+1;
003953    }
003954  
003955    /* See if it is possible to write these frames into the start of the
003956    ** log file, instead of appending to it at pWal->hdr.mxFrame.
003957    */
003958    if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
003959      return rc;
003960    }
003961  
003962    /* If this is the first frame written into the log, write the WAL
003963    ** header to the start of the WAL file. See comments at the top of
003964    ** this source file for a description of the WAL header format.
003965    */
003966    iFrame = pWal->hdr.mxFrame;
003967    if( iFrame==0 ){
003968      u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
003969      u32 aCksum[2];                /* Checksum for wal-header */
003970  
003971      sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
003972      sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
003973      sqlite3Put4byte(&aWalHdr[8], szPage);
003974      sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
003975      if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
003976      memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
003977      walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
003978      sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
003979      sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
003980  
003981      pWal->szPage = szPage;
003982      pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
003983      pWal->hdr.aFrameCksum[0] = aCksum[0];
003984      pWal->hdr.aFrameCksum[1] = aCksum[1];
003985      pWal->truncateOnCommit = 1;
003986  
003987      rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
003988      WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
003989      if( rc!=SQLITE_OK ){
003990        return rc;
003991      }
003992  
003993      /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
003994      ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
003995      ** an out-of-order write following a WAL restart could result in
003996      ** database corruption.  See the ticket:
003997      **
003998      **     https://sqlite.org/src/info/ff5be73dee
003999      */
004000      if( pWal->syncHeader ){
004001        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
004002        if( rc ) return rc;
004003      }
004004    }
004005    if( (int)pWal->szPage!=szPage ){
004006      return SQLITE_CORRUPT_BKPT;  /* TH3 test case: cov1/corrupt155.test */
004007    }
004008  
004009    /* Setup information needed to write frames into the WAL */
004010    w.pWal = pWal;
004011    w.pFd = pWal->pWalFd;
004012    w.iSyncPoint = 0;
004013    w.syncFlags = sync_flags;
004014    w.szPage = szPage;
004015    iOffset = walFrameOffset(iFrame+1, szPage);
004016    szFrame = szPage + WAL_FRAME_HDRSIZE;
004017  
004018    /* Write all frames into the log file exactly once */
004019    for(p=pList; p; p=p->pDirty){
004020      int nDbSize;   /* 0 normally.  Positive == commit flag */
004021  
004022      /* Check if this page has already been written into the wal file by
004023      ** the current transaction. If so, overwrite the existing frame and
004024      ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
004025      ** checksums must be recomputed when the transaction is committed.  */
004026      if( iFirst && (p->pDirty || isCommit==0) ){
004027        u32 iWrite = 0;
004028        VVA_ONLY(rc =) walFindFrame(pWal, p->pgno, &iWrite);
004029        assert( rc==SQLITE_OK || iWrite==0 );
004030        if( iWrite>=iFirst ){
004031          i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
004032          void *pData;
004033          if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
004034            pWal->iReCksum = iWrite;
004035          }
004036          pData = p->pData;
004037          rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
004038          if( rc ) return rc;
004039          p->flags &= ~PGHDR_WAL_APPEND;
004040          continue;
004041        }
004042      }
004043  
004044      iFrame++;
004045      assert( iOffset==walFrameOffset(iFrame, szPage) );
004046      nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
004047      rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
004048      if( rc ) return rc;
004049      pLast = p;
004050      iOffset += szFrame;
004051      p->flags |= PGHDR_WAL_APPEND;
004052    }
004053  
004054    /* Recalculate checksums within the wal file if required. */
004055    if( isCommit && pWal->iReCksum ){
004056      rc = walRewriteChecksums(pWal, iFrame);
004057      if( rc ) return rc;
004058    }
004059  
004060    /* If this is the end of a transaction, then we might need to pad
004061    ** the transaction and/or sync the WAL file.
004062    **
004063    ** Padding and syncing only occur if this set of frames complete a
004064    ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
004065    ** or synchronous==OFF, then no padding or syncing are needed.
004066    **
004067    ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
004068    ** needed and only the sync is done.  If padding is needed, then the
004069    ** final frame is repeated (with its commit mark) until the next sector
004070    ** boundary is crossed.  Only the part of the WAL prior to the last
004071    ** sector boundary is synced; the part of the last frame that extends
004072    ** past the sector boundary is written after the sync.
004073    */
004074    if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
004075      int bSync = 1;
004076      if( pWal->padToSectorBoundary ){
004077        int sectorSize = sqlite3SectorSize(pWal->pWalFd);
004078        w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
004079        bSync = (w.iSyncPoint==iOffset);
004080        testcase( bSync );
004081        while( iOffset<w.iSyncPoint ){
004082          rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
004083          if( rc ) return rc;
004084          iOffset += szFrame;
004085          nExtra++;
004086          assert( pLast!=0 );
004087        }
004088      }
004089      if( bSync ){
004090        assert( rc==SQLITE_OK );
004091        rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
004092      }
004093    }
004094  
004095    /* If this frame set completes the first transaction in the WAL and
004096    ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
004097    ** journal size limit, if possible.
004098    */
004099    if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
004100      i64 sz = pWal->mxWalSize;
004101      if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
004102        sz = walFrameOffset(iFrame+nExtra+1, szPage);
004103      }
004104      walLimitSize(pWal, sz);
004105      pWal->truncateOnCommit = 0;
004106    }
004107  
004108    /* Append data to the wal-index. It is not necessary to lock the
004109    ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
004110    ** guarantees that there are no other writers, and no data that may
004111    ** be in use by existing readers is being overwritten.
004112    */
004113    iFrame = pWal->hdr.mxFrame;
004114    for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
004115      if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
004116      iFrame++;
004117      rc = walIndexAppend(pWal, iFrame, p->pgno);
004118    }
004119    assert( pLast!=0 || nExtra==0 );
004120    while( rc==SQLITE_OK && nExtra>0 ){
004121      iFrame++;
004122      nExtra--;
004123      rc = walIndexAppend(pWal, iFrame, pLast->pgno);
004124    }
004125  
004126    if( rc==SQLITE_OK ){
004127      /* Update the private copy of the header. */
004128      pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
004129      testcase( szPage<=32768 );
004130      testcase( szPage>=65536 );
004131      pWal->hdr.mxFrame = iFrame;
004132      if( isCommit ){
004133        pWal->hdr.iChange++;
004134        pWal->hdr.nPage = nTruncate;
004135      }
004136      /* If this is a commit, update the wal-index header too. */
004137      if( isCommit ){
004138        walIndexWriteHdr(pWal);
004139        pWal->iCallback = iFrame;
004140      }
004141    }
004142  
004143    WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
004144    return rc;
004145  }
004146  
004147  /* 
004148  ** Write a set of frames to the log. The caller must hold the write-lock
004149  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
004150  **
004151  ** The difference between this function and walFrames() is that this
004152  ** function wraps walFrames() in an SEH_TRY{...} block.
004153  */
004154  int sqlite3WalFrames(
004155    Wal *pWal,                      /* Wal handle to write to */
004156    int szPage,                     /* Database page-size in bytes */
004157    PgHdr *pList,                   /* List of dirty pages to write */
004158    Pgno nTruncate,                 /* Database size after this commit */
004159    int isCommit,                   /* True if this is a commit */
004160    int sync_flags                  /* Flags to pass to OsSync() (or 0) */
004161  ){
004162    int rc;
004163    SEH_TRY {
004164      rc = walFrames(pWal, szPage, pList, nTruncate, isCommit, sync_flags);
004165    }
004166    SEH_EXCEPT( rc = walHandleException(pWal); )
004167    return rc;
004168  }
004169  
004170  /*
004171  ** This routine is called to implement sqlite3_wal_checkpoint() and
004172  ** related interfaces.
004173  **
004174  ** Obtain a CHECKPOINT lock and then backfill as much information as
004175  ** we can from WAL into the database.
004176  **
004177  ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
004178  ** callback. In this case this function runs a blocking checkpoint.
004179  */
004180  int sqlite3WalCheckpoint(
004181    Wal *pWal,                      /* Wal connection */
004182    sqlite3 *db,                    /* Check this handle's interrupt flag */
004183    int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
004184    int (*xBusy)(void*),            /* Function to call when busy */
004185    void *pBusyArg,                 /* Context argument for xBusyHandler */
004186    int sync_flags,                 /* Flags to sync db file with (or 0) */
004187    int nBuf,                       /* Size of temporary buffer */
004188    u8 *zBuf,                       /* Temporary buffer to use */
004189    int *pnLog,                     /* OUT: Number of frames in WAL */
004190    int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
004191  ){
004192    int rc;                         /* Return code */
004193    int isChanged = 0;              /* True if a new wal-index header is loaded */
004194    int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
004195    int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
004196  
004197    assert( pWal->ckptLock==0 );
004198    assert( pWal->writeLock==0 );
004199  
004200    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
004201    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
004202    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
004203  
004204    if( pWal->readOnly ) return SQLITE_READONLY;
004205    WALTRACE(("WAL%p: checkpoint begins\n", pWal));
004206  
004207    /* Enable blocking locks, if possible. If blocking locks are successfully
004208    ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
004209    sqlite3WalDb(pWal, db);
004210    (void)walEnableBlocking(pWal);
004211  
004212    /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
004213    ** "checkpoint" lock on the database file.
004214    ** EVIDENCE-OF: R-10421-19736 If any other process is running a
004215    ** checkpoint operation at the same time, the lock cannot be obtained and
004216    ** SQLITE_BUSY is returned.
004217    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
004218    ** it will not be invoked in this case.
004219    */
004220    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
004221    testcase( rc==SQLITE_BUSY );
004222    testcase( rc!=SQLITE_OK && xBusy2!=0 );
004223    if( rc==SQLITE_OK ){
004224      pWal->ckptLock = 1;
004225  
004226      /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
004227      ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
004228      ** file.
004229      **
004230      ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
004231      ** immediately, and a busy-handler is configured, it is invoked and the
004232      ** writer lock retried until either the busy-handler returns 0 or the
004233      ** lock is successfully obtained.
004234      */
004235      if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
004236        rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
004237        if( rc==SQLITE_OK ){
004238          pWal->writeLock = 1;
004239        }else if( rc==SQLITE_BUSY ){
004240          eMode2 = SQLITE_CHECKPOINT_PASSIVE;
004241          xBusy2 = 0;
004242          rc = SQLITE_OK;
004243        }
004244      }
004245    }
004246  
004247  
004248    /* Read the wal-index header. */
004249    SEH_TRY {
004250      if( rc==SQLITE_OK ){
004251        walDisableBlocking(pWal);
004252        rc = walIndexReadHdr(pWal, &isChanged);
004253        (void)walEnableBlocking(pWal);
004254        if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
004255          sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
004256        }
004257      }
004258    
004259      /* Copy data from the log to the database file. */
004260      if( rc==SQLITE_OK ){
004261        if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
004262          rc = SQLITE_CORRUPT_BKPT;
004263        }else{
004264          rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf);
004265        }
004266  
004267        /* If no error occurred, set the output variables. */
004268        if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
004269          if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
004270          SEH_INJECT_FAULT;
004271          if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
004272        }
004273      }
004274    }
004275    SEH_EXCEPT( rc = walHandleException(pWal); )
004276  
004277    if( isChanged ){
004278      /* If a new wal-index header was loaded before the checkpoint was
004279      ** performed, then the pager-cache associated with pWal is now
004280      ** out of date. So zero the cached wal-index header to ensure that
004281      ** next time the pager opens a snapshot on this database it knows that
004282      ** the cache needs to be reset.
004283      */
004284      memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
004285    }
004286  
004287    walDisableBlocking(pWal);
004288    sqlite3WalDb(pWal, 0);
004289  
004290    /* Release the locks. */
004291    sqlite3WalEndWriteTransaction(pWal);
004292    if( pWal->ckptLock ){
004293      walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
004294      pWal->ckptLock = 0;
004295    }
004296    WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
004297  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
004298    if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
004299  #endif
004300    return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
004301  }
004302  
004303  /* Return the value to pass to a sqlite3_wal_hook callback, the
004304  ** number of frames in the WAL at the point of the last commit since
004305  ** sqlite3WalCallback() was called.  If no commits have occurred since
004306  ** the last call, then return 0.
004307  */
004308  int sqlite3WalCallback(Wal *pWal){
004309    u32 ret = 0;
004310    if( pWal ){
004311      ret = pWal->iCallback;
004312      pWal->iCallback = 0;
004313    }
004314    return (int)ret;
004315  }
004316  
004317  /*
004318  ** This function is called to change the WAL subsystem into or out
004319  ** of locking_mode=EXCLUSIVE.
004320  **
004321  ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
004322  ** into locking_mode=NORMAL.  This means that we must acquire a lock
004323  ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
004324  ** or if the acquisition of the lock fails, then return 0.  If the
004325  ** transition out of exclusive-mode is successful, return 1.  This
004326  ** operation must occur while the pager is still holding the exclusive
004327  ** lock on the main database file.
004328  **
004329  ** If op is one, then change from locking_mode=NORMAL into
004330  ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
004331  ** be released.  Return 1 if the transition is made and 0 if the
004332  ** WAL is already in exclusive-locking mode - meaning that this
004333  ** routine is a no-op.  The pager must already hold the exclusive lock
004334  ** on the main database file before invoking this operation.
004335  **
004336  ** If op is negative, then do a dry-run of the op==1 case but do
004337  ** not actually change anything. The pager uses this to see if it
004338  ** should acquire the database exclusive lock prior to invoking
004339  ** the op==1 case.
004340  */
004341  int sqlite3WalExclusiveMode(Wal *pWal, int op){
004342    int rc;
004343    assert( pWal->writeLock==0 );
004344    assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
004345  
004346    /* pWal->readLock is usually set, but might be -1 if there was a
004347    ** prior error while attempting to acquire are read-lock. This cannot
004348    ** happen if the connection is actually in exclusive mode (as no xShmLock
004349    ** locks are taken in this case). Nor should the pager attempt to
004350    ** upgrade to exclusive-mode following such an error.
004351    */
004352  #ifndef SQLITE_USE_SEH
004353    assert( pWal->readLock>=0 || pWal->lockError );
004354  #endif
004355    assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
004356  
004357    if( op==0 ){
004358      if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
004359        pWal->exclusiveMode = WAL_NORMAL_MODE;
004360        if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
004361          pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
004362        }
004363        rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
004364      }else{
004365        /* Already in locking_mode=NORMAL */
004366        rc = 0;
004367      }
004368    }else if( op>0 ){
004369      assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
004370      assert( pWal->readLock>=0 );
004371      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
004372      pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
004373      rc = 1;
004374    }else{
004375      rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
004376    }
004377    return rc;
004378  }
004379  
004380  /*
004381  ** Return true if the argument is non-NULL and the WAL module is using
004382  ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
004383  ** WAL module is using shared-memory, return false.
004384  */
004385  int sqlite3WalHeapMemory(Wal *pWal){
004386    return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
004387  }
004388  
004389  #ifdef SQLITE_ENABLE_SNAPSHOT
004390  /* Create a snapshot object.  The content of a snapshot is opaque to
004391  ** every other subsystem, so the WAL module can put whatever it needs
004392  ** in the object.
004393  */
004394  int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
004395    int rc = SQLITE_OK;
004396    WalIndexHdr *pRet;
004397    static const u32 aZero[4] = { 0, 0, 0, 0 };
004398  
004399    assert( pWal->readLock>=0 && pWal->writeLock==0 );
004400  
004401    if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
004402      *ppSnapshot = 0;
004403      return SQLITE_ERROR;
004404    }
004405    pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
004406    if( pRet==0 ){
004407      rc = SQLITE_NOMEM_BKPT;
004408    }else{
004409      memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
004410      *ppSnapshot = (sqlite3_snapshot*)pRet;
004411    }
004412  
004413    return rc;
004414  }
004415  
004416  /* Try to open on pSnapshot when the next read-transaction starts
004417  */
004418  void sqlite3WalSnapshotOpen(
004419    Wal *pWal,
004420    sqlite3_snapshot *pSnapshot
004421  ){
004422    pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
004423  }
004424  
004425  /*
004426  ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
004427  ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
004428  */
004429  int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
004430    WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
004431    WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
004432  
004433    /* aSalt[0] is a copy of the value stored in the wal file header. It
004434    ** is incremented each time the wal file is restarted.  */
004435    if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
004436    if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
004437    if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
004438    if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
004439    return 0;
004440  }
004441  
004442  /*
004443  ** The caller currently has a read transaction open on the database.
004444  ** This function takes a SHARED lock on the CHECKPOINTER slot and then
004445  ** checks if the snapshot passed as the second argument is still
004446  ** available. If so, SQLITE_OK is returned.
004447  **
004448  ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
004449  ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
004450  ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
004451  ** lock is released before returning.
004452  */
004453  int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
004454    int rc;
004455    SEH_TRY {
004456      rc = walLockShared(pWal, WAL_CKPT_LOCK);
004457      if( rc==SQLITE_OK ){
004458        WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
004459        if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
004460         || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
004461        ){
004462          rc = SQLITE_ERROR_SNAPSHOT;
004463          walUnlockShared(pWal, WAL_CKPT_LOCK);
004464        }
004465      }
004466    }
004467    SEH_EXCEPT( rc = walHandleException(pWal); )
004468    return rc;
004469  }
004470  
004471  /*
004472  ** Release a lock obtained by an earlier successful call to
004473  ** sqlite3WalSnapshotCheck().
004474  */
004475  void sqlite3WalSnapshotUnlock(Wal *pWal){
004476    assert( pWal );
004477    walUnlockShared(pWal, WAL_CKPT_LOCK);
004478  }
004479  
004480  
004481  #endif /* SQLITE_ENABLE_SNAPSHOT */
004482  
004483  #ifdef SQLITE_ENABLE_ZIPVFS
004484  /*
004485  ** If the argument is not NULL, it points to a Wal object that holds a
004486  ** read-lock. This function returns the database page-size if it is known,
004487  ** or zero if it is not (or if pWal is NULL).
004488  */
004489  int sqlite3WalFramesize(Wal *pWal){
004490    assert( pWal==0 || pWal->readLock>=0 );
004491    return (pWal ? pWal->szPage : 0);
004492  }
004493  #endif
004494  
004495  /* Return the sqlite3_file object for the WAL file
004496  */
004497  sqlite3_file *sqlite3WalFile(Wal *pWal){
004498    return pWal->pWalFd;
004499  }
004500  
004501  #endif /* #ifndef SQLITE_OMIT_WAL */