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