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