blob: 0d1d0e42b4d42b7f3408e7bb3235b861f8f3f05c [file] [log] [blame]
dan7c246102010-04-12 19:00:29 +00001/*
drh7ed91f22010-04-29 22:34:07 +00002** 2010 February 1
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
drh027a1282010-05-19 01:53:53 +000013** This file contains the implementation of a write-ahead log (WAL) used in
14** "journal_mode=WAL" mode.
drh29d4dbe2010-05-18 23:29:52 +000015**
drh7ed91f22010-04-29 22:34:07 +000016** WRITE-AHEAD LOG (WAL) FILE FORMAT
dan97a31352010-04-16 13:59:31 +000017**
drh7e263722010-05-20 21:21:09 +000018** A WAL file consists of a header followed by zero or more "frames".
drh027a1282010-05-19 01:53:53 +000019** Each frame records the revised content of a single page from the
drh29d4dbe2010-05-18 23:29:52 +000020** database file. All changes to the database are recorded by writing
21** frames into the WAL. Transactions commit when a frame is written that
22** contains a commit marker. A single WAL can and usually does record
23** multiple transactions. Periodically, the content of the WAL is
24** transferred back into the database file in an operation called a
25** "checkpoint".
26**
27** A single WAL file can be used multiple times. In other words, the
drh027a1282010-05-19 01:53:53 +000028** WAL can fill up with frames and then be checkpointed and then new
drh29d4dbe2010-05-18 23:29:52 +000029** frames can overwrite the old ones. A WAL always grows from beginning
30** toward the end. Checksums and counters attached to each frame are
31** used to determine which frames within the WAL are valid and which
32** are leftovers from prior checkpoints.
33**
drh23ea97b2010-05-20 16:45:58 +000034** The WAL header is 24 bytes in size and consists of the following six
dan97a31352010-04-16 13:59:31 +000035** big-endian 32-bit unsigned integer values:
36**
drh1b78eaf2010-05-25 13:40:03 +000037** 0: Magic number. 0x377f0682 or 0x377f0683
drh23ea97b2010-05-20 16:45:58 +000038** 4: File format version. Currently 3007000
39** 8: Database page size. Example: 1024
40** 12: Checkpoint sequence number
drh7e263722010-05-20 21:21:09 +000041** 16: Salt-1, random integer incremented with each checkpoint
42** 20: Salt-2, a different random integer changing with each ckpt
dan97a31352010-04-16 13:59:31 +000043**
drh23ea97b2010-05-20 16:45:58 +000044** Immediately following the wal-header are zero or more frames. Each
45** frame consists of a 24-byte frame-header followed by a <page-size> bytes
46** of page data. The frame-header is broken into 6 big-endian 32-bit unsigned
dan97a31352010-04-16 13:59:31 +000047** integer values, as follows:
48**
dan3de777f2010-04-17 12:31:37 +000049** 0: Page number.
50** 4: For commit records, the size of the database image in pages
dan97a31352010-04-16 13:59:31 +000051** after the commit. For all other records, zero.
drh7e263722010-05-20 21:21:09 +000052** 8: Salt-1 (copied from the header)
53** 12: Salt-2 (copied from the header)
drh23ea97b2010-05-20 16:45:58 +000054** 16: Checksum-1.
55** 20: Checksum-2.
drh29d4dbe2010-05-18 23:29:52 +000056**
drh7e263722010-05-20 21:21:09 +000057** A frame is considered valid if and only if the following conditions are
58** true:
59**
60** (1) The salt-1 and salt-2 values in the frame-header match
61** salt values in the wal-header
62**
63** (2) The checksum values in the final 8 bytes of the frame-header
drh1b78eaf2010-05-25 13:40:03 +000064** exactly match the checksum computed consecutively on the
65** WAL header and the first 8 bytes and the content of all frames
66** up to and including the current frame.
67**
68** The checksum is computed using 32-bit big-endian integers if the
69** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
70** is computed using little-endian if the magic number is 0x377f0682.
drh51b21b12010-05-25 15:53:31 +000071** The checksum values are always stored in the frame header in a
72** big-endian format regardless of which byte order is used to compute
73** the checksum. The checksum is computed by interpreting the input as
74** an even number of unsigned 32-bit integers: x[0] through x[N]. The
75**
76** for i from 0 to n-1 step 2:
77** s0 += x[i] + s1;
78** s1 += x[i+1] + s0;
79** endfor
drh7e263722010-05-20 21:21:09 +000080**
81** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
82** WAL is transferred into the database, then the database is VFS.xSync-ed.
83** The VFS.xSync operations server as write barriers - all writes launched
84** before the xSync must complete before any write that launches after the
85** xSync begins.
86**
87** After each checkpoint, the salt-1 value is incremented and the salt-2
88** value is randomized. This prevents old and new frames in the WAL from
89** being considered valid at the same time and being checkpointing together
90** following a crash.
91**
drh29d4dbe2010-05-18 23:29:52 +000092** READER ALGORITHM
93**
94** To read a page from the database (call it page number P), a reader
95** first checks the WAL to see if it contains page P. If so, then the
drh73b64e42010-05-30 19:55:15 +000096** last valid instance of page P that is a followed by a commit frame
97** or is a commit frame itself becomes the value read. If the WAL
98** contains no copies of page P that are valid and which are a commit
99** frame or are followed by a commit frame, then page P is read from
100** the database file.
drh29d4dbe2010-05-18 23:29:52 +0000101**
drh73b64e42010-05-30 19:55:15 +0000102** To start a read transaction, the reader records the index of the last
103** valid frame in the WAL. The reader uses this recorded "mxFrame" value
104** for all subsequent read operations. New transactions can be appended
105** to the WAL, but as long as the reader uses its original mxFrame value
106** and ignores the newly appended content, it will see a consistent snapshot
107** of the database from a single point in time. This technique allows
108** multiple concurrent readers to view different versions of the database
109** content simultaneously.
110**
111** The reader algorithm in the previous paragraphs works correctly, but
drh29d4dbe2010-05-18 23:29:52 +0000112** because frames for page P can appear anywhere within the WAL, the
drh027a1282010-05-19 01:53:53 +0000113** reader has to scan the entire WAL looking for page P frames. If the
drh29d4dbe2010-05-18 23:29:52 +0000114** WAL is large (multiple megabytes is typical) that scan can be slow,
drh027a1282010-05-19 01:53:53 +0000115** and read performance suffers. To overcome this problem, a separate
116** data structure called the wal-index is maintained to expedite the
drh29d4dbe2010-05-18 23:29:52 +0000117** search for frames of a particular page.
118**
119** WAL-INDEX FORMAT
120**
121** Conceptually, the wal-index is shared memory, though VFS implementations
122** might choose to implement the wal-index using a mmapped file. Because
123** the wal-index is shared memory, SQLite does not support journal_mode=WAL
124** on a network filesystem. All users of the database must be able to
125** share memory.
126**
127** The wal-index is transient. After a crash, the wal-index can (and should
128** be) reconstructed from the original WAL file. In fact, the VFS is required
129** to either truncate or zero the header of the wal-index when the last
130** connection to it closes. Because the wal-index is transient, it can
131** use an architecture-specific format; it does not have to be cross-platform.
132** Hence, unlike the database and WAL file formats which store all values
133** as big endian, the wal-index can store multi-byte values in the native
134** byte order of the host computer.
135**
136** The purpose of the wal-index is to answer this question quickly: Given
137** a page number P, return the index of the last frame for page P in the WAL,
138** or return NULL if there are no frames for page P in the WAL.
139**
140** The wal-index consists of a header region, followed by an one or
141** more index blocks.
142**
drh027a1282010-05-19 01:53:53 +0000143** The wal-index header contains the total number of frames within the WAL
144** in the the mxFrame field. Each index block contains information on
145** HASHTABLE_NPAGE frames. Each index block contains two sections, a
146** mapping which is a database page number for each frame, and a hash
147** table used to look up frames by page number. The mapping section is
148** an array of HASHTABLE_NPAGE 32-bit page numbers. The first entry on the
149** array is the page number for the first frame; the second entry is the
150** page number for the second frame; and so forth. The last index block
151** holds a total of (mxFrame%HASHTABLE_NPAGE) page numbers. All index
152** blocks other than the last are completely full with HASHTABLE_NPAGE
153** page numbers. All index blocks are the same size; the mapping section
154** of the last index block merely contains unused entries if mxFrame is
155** not an even multiple of HASHTABLE_NPAGE.
156**
157** Even without using the hash table, the last frame for page P
158** can be found by scanning the mapping sections of each index block
159** starting with the last index block and moving toward the first, and
160** within each index block, starting at the end and moving toward the
161** beginning. The first entry that equals P corresponds to the frame
162** holding the content for that page.
163**
164** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
165** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
166** hash table for each page number in the mapping section, so the hash
167** table is never more than half full. The expected number of collisions
168** prior to finding a match is 1. Each entry of the hash table is an
169** 1-based index of an entry in the mapping section of the same
170** index block. Let K be the 1-based index of the largest entry in
171** the mapping section. (For index blocks other than the last, K will
172** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
173** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
drh73b64e42010-05-30 19:55:15 +0000174** contain a value of 0.
drh027a1282010-05-19 01:53:53 +0000175**
176** To look for page P in the hash table, first compute a hash iKey on
177** P as follows:
178**
179** iKey = (P * 383) % HASHTABLE_NSLOT
180**
181** Then start scanning entries of the hash table, starting with iKey
182** (wrapping around to the beginning when the end of the hash table is
183** reached) until an unused hash slot is found. Let the first unused slot
184** be at index iUnused. (iUnused might be less than iKey if there was
185** wrap-around.) Because the hash table is never more than half full,
186** the search is guaranteed to eventually hit an unused entry. Let
187** iMax be the value between iKey and iUnused, closest to iUnused,
188** where aHash[iMax]==P. If there is no iMax entry (if there exists
189** no hash slot such that aHash[i]==p) then page P is not in the
190** current index block. Otherwise the iMax-th mapping entry of the
191** current index block corresponds to the last entry that references
192** page P.
193**
194** A hash search begins with the last index block and moves toward the
195** first index block, looking for entries corresponding to page P. On
196** average, only two or three slots in each index block need to be
197** examined in order to either find the last entry for page P, or to
198** establish that no such entry exists in the block. Each index block
199** holds over 4000 entries. So two or three index blocks are sufficient
200** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
201** comparisons (on average) suffice to either locate a frame in the
202** WAL or to establish that the frame does not exist in the WAL. This
203** is much faster than scanning the entire 10MB WAL.
204**
205** Note that entries are added in order of increasing K. Hence, one
206** reader might be using some value K0 and a second reader that started
207** at a later time (after additional transactions were added to the WAL
208** and to the wal-index) might be using a different value K1, where K1>K0.
209** Both readers can use the same hash table and mapping section to get
210** the correct result. There may be entries in the hash table with
211** K>K0 but to the first reader, those entries will appear to be unused
212** slots in the hash table and so the first reader will get an answer as
213** if no values greater than K0 had ever been inserted into the hash table
214** in the first place - which is what reader one wants. Meanwhile, the
215** second reader using K1 will see additional values that were inserted
216** later, which is exactly what reader two wants.
217**
dan6f150142010-05-21 15:31:56 +0000218** When a rollback occurs, the value of K is decreased. Hash table entries
219** that correspond to frames greater than the new K value are removed
220** from the hash table at this point.
dan97a31352010-04-16 13:59:31 +0000221*/
drh29d4dbe2010-05-18 23:29:52 +0000222#ifndef SQLITE_OMIT_WAL
dan97a31352010-04-16 13:59:31 +0000223
drh29d4dbe2010-05-18 23:29:52 +0000224#include "wal.h"
225
drh73b64e42010-05-30 19:55:15 +0000226/*
227** Indices of various locking bytes. WAL_NREADER is the number
228** of available reader locks and should be at least 3.
229*/
230#define WAL_WRITE_LOCK 0
231#define WAL_ALL_BUT_WRITE 1
232#define WAL_CKPT_LOCK 1
233#define WAL_RECOVER_LOCK 2
234#define WAL_READ_LOCK(I) (3+(I))
235#define WAL_NREADER (SQLITE_SHM_NLOCK-3)
236
dan97a31352010-04-16 13:59:31 +0000237
drh7ed91f22010-04-29 22:34:07 +0000238/* Object declarations */
239typedef struct WalIndexHdr WalIndexHdr;
240typedef struct WalIterator WalIterator;
drh73b64e42010-05-30 19:55:15 +0000241typedef struct WalCkptInfo WalCkptInfo;
dan7c246102010-04-12 19:00:29 +0000242
243
244/*
drh286a2882010-05-20 23:51:06 +0000245** The following object holds a copy of the wal-index header content.
246**
247** The actual header in the wal-index consists of two copies of this
248** object.
dan7c246102010-04-12 19:00:29 +0000249*/
drh7ed91f22010-04-29 22:34:07 +0000250struct WalIndexHdr {
dan71d89912010-05-24 13:57:42 +0000251 u32 iChange; /* Counter incremented each transaction */
252 u16 bigEndCksum; /* True if checksums in WAL are big-endian */
253 u16 szPage; /* Database page size in bytes */
254 u32 mxFrame; /* Index of last valid frame in the WAL */
255 u32 nPage; /* Size of database in pages */
256 u32 aFrameCksum[2]; /* Checksum of last frame in log */
257 u32 aSalt[2]; /* Two salt values copied from WAL header */
258 u32 aCksum[2]; /* Checksum over all prior fields */
dan7c246102010-04-12 19:00:29 +0000259};
260
drh73b64e42010-05-30 19:55:15 +0000261/*
262** A copy of the following object occurs in the wal-index immediately
263** following the second copy of the WalIndexHdr. This object stores
264** information used by checkpoint.
265**
266** nBackfill is the number of frames in the WAL that have been written
267** back into the database. (We call the act of moving content from WAL to
268** database "backfilling".) The nBackfill number is never greater than
269** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
270** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
271** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
272** mxFrame back to zero when the WAL is reset.
273**
274** There is one entry in aReadMark[] for each reader lock. If a reader
275** holds read-lock K, then the value in aReadMark[K] is no greater than
276** the mxFrame for that reader. aReadMark[0] is a special case. It
277** always holds zero. Readers holding WAL_READ_LOCK(0) always ignore
278** the entire WAL and read all content directly from the database.
279**
280** The value of aReadMark[K] may only be changed by a thread that
281** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
282** aReadMark[K] cannot changed while there is a reader is using that mark
283** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
284**
285** The checkpointer may only transfer frames from WAL to database where
286** the frame numbers are less than or equal to every aReadMark[] that is
287** in use (that is, every aReadMark[j] for which there is a corresponding
288** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
289** largest value and will increase an unused aReadMark[] to mxFrame if there
290** is not already an aReadMark[] equal to mxFrame. The exception to the
291** previous sentence is when nBackfill equals mxFrame (meaning that everything
292** in the WAL has been backfilled into the database) then new readers
293** will choose aReadMark[0] which has value 0 and hence such reader will
294** get all their all content directly from the database file and ignore
295** the WAL.
296**
297** Writers normally append new frames to the end of the WAL. However,
298** if nBackfill equals mxFrame (meaning that all WAL content has been
299** written back into the database) and if no readers are using the WAL
300** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
301** the writer will first "reset" the WAL back to the beginning and start
302** writing new content beginning at frame 1.
303**
304** We assume that 32-bit loads are atomic and so no locks are needed in
305** order to read from any aReadMark[] entries.
306*/
307struct WalCkptInfo {
308 u32 nBackfill; /* Number of WAL frames backfilled into DB */
309 u32 aReadMark[WAL_NREADER]; /* Reader marks */
310};
311
312
drh7e263722010-05-20 21:21:09 +0000313/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
314** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
315** only support mandatory file-locks, we do not read or write data
316** from the region of the file on which locks are applied.
danff207012010-04-24 04:49:15 +0000317*/
drh73b64e42010-05-30 19:55:15 +0000318#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
319#define WALINDEX_LOCK_RESERVED 16
drh026ac282010-05-26 15:06:38 +0000320#define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
dan7c246102010-04-12 19:00:29 +0000321
drh7ed91f22010-04-29 22:34:07 +0000322/* Size of header before each frame in wal */
drh23ea97b2010-05-20 16:45:58 +0000323#define WAL_FRAME_HDRSIZE 24
danff207012010-04-24 04:49:15 +0000324
drh7ed91f22010-04-29 22:34:07 +0000325/* Size of write ahead log header */
drh23ea97b2010-05-20 16:45:58 +0000326#define WAL_HDRSIZE 24
dan97a31352010-04-16 13:59:31 +0000327
danb8fd6c22010-05-24 10:39:36 +0000328/* WAL magic value. Either this value, or the same value with the least
329** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
330** big-endian format in the first 4 bytes of a WAL file.
331**
332** If the LSB is set, then the checksums for each frame within the WAL
333** file are calculated by treating all data as an array of 32-bit
334** big-endian words. Otherwise, they are calculated by interpreting
335** all data as 32-bit little-endian words.
336*/
337#define WAL_MAGIC 0x377f0682
338
dan97a31352010-04-16 13:59:31 +0000339/*
drh7ed91f22010-04-29 22:34:07 +0000340** Return the offset of frame iFrame in the write-ahead log file,
drh6e810962010-05-19 17:49:50 +0000341** assuming a database page size of szPage bytes. The offset returned
drh7ed91f22010-04-29 22:34:07 +0000342** is to the start of the write-ahead log frame-header.
dan97a31352010-04-16 13:59:31 +0000343*/
drh6e810962010-05-19 17:49:50 +0000344#define walFrameOffset(iFrame, szPage) ( \
345 WAL_HDRSIZE + ((iFrame)-1)*((szPage)+WAL_FRAME_HDRSIZE) \
dan97a31352010-04-16 13:59:31 +0000346)
dan7c246102010-04-12 19:00:29 +0000347
348/*
drh7ed91f22010-04-29 22:34:07 +0000349** An open write-ahead log file is represented by an instance of the
350** following object.
dance4f05f2010-04-22 19:14:13 +0000351*/
drh7ed91f22010-04-29 22:34:07 +0000352struct Wal {
drh73b64e42010-05-30 19:55:15 +0000353 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
drhd9e5c4f2010-05-12 18:01:39 +0000354 sqlite3_file *pDbFd; /* File handle for the database file */
355 sqlite3_file *pWalFd; /* File handle for WAL file */
drh7ed91f22010-04-29 22:34:07 +0000356 u32 iCallback; /* Value to pass to log callback (or 0) */
drh5530b762010-04-30 14:39:50 +0000357 int szWIndex; /* Size of the wal-index that is mapped in mem */
drh5939f442010-05-18 13:27:12 +0000358 volatile u32 *pWiData; /* Pointer to wal-index content in memory */
drh73b64e42010-05-30 19:55:15 +0000359 u16 szPage; /* Database page size */
360 i16 readLock; /* Which read lock is being held. -1 for none */
dan55437592010-05-11 12:19:26 +0000361 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
drh73b64e42010-05-30 19:55:15 +0000362 u8 isWIndexOpen; /* True if ShmOpen() called on pDbFd */
363 u8 writeLock; /* True if in a write transaction */
364 u8 ckptLock; /* True if holding a checkpoint lock */
365 WalIndexHdr hdr; /* Wal-index header for current transaction */
drhd9e5c4f2010-05-12 18:01:39 +0000366 char *zWalName; /* Name of WAL file */
drh7e263722010-05-20 21:21:09 +0000367 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
dan7c246102010-04-12 19:00:29 +0000368};
369
drh73b64e42010-05-30 19:55:15 +0000370/*
371** Return a pointer to the WalCkptInfo structure in the wal-index.
372*/
373static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
374 assert( pWal->pWiData!=0 );
375 return (volatile WalCkptInfo*)&pWal->pWiData[sizeof(WalIndexHdr)/2];
376}
377
dan64d039e2010-04-13 19:27:31 +0000378
dan7c246102010-04-12 19:00:29 +0000379/*
drha2a42012010-05-18 18:01:08 +0000380** This structure is used to implement an iterator that loops through
381** all frames in the WAL in database page order. Where two or more frames
dan7c246102010-04-12 19:00:29 +0000382** correspond to the same database page, the iterator visits only the
drha2a42012010-05-18 18:01:08 +0000383** frame most recently written to the WAL (in other words, the frame with
384** the largest index).
dan7c246102010-04-12 19:00:29 +0000385**
386** The internals of this structure are only accessed by:
387**
drh7ed91f22010-04-29 22:34:07 +0000388** walIteratorInit() - Create a new iterator,
389** walIteratorNext() - Step an iterator,
390** walIteratorFree() - Free an iterator.
dan7c246102010-04-12 19:00:29 +0000391**
drh7ed91f22010-04-29 22:34:07 +0000392** This functionality is used by the checkpoint code (see walCheckpoint()).
dan7c246102010-04-12 19:00:29 +0000393*/
drh7ed91f22010-04-29 22:34:07 +0000394struct WalIterator {
drha2a42012010-05-18 18:01:08 +0000395 int iPrior; /* Last result returned from the iterator */
396 int nSegment; /* Size of the aSegment[] array */
397 int nFinal; /* Elements in aSegment[nSegment-1] */
drh7ed91f22010-04-29 22:34:07 +0000398 struct WalSegment {
drha2a42012010-05-18 18:01:08 +0000399 int iNext; /* Next slot in aIndex[] not previously returned */
400 u8 *aIndex; /* i0, i1, i2... such that aPgno[iN] ascending */
401 u32 *aPgno; /* 256 page numbers. Pointer to Wal.pWiData */
402 } aSegment[1]; /* One for every 256 entries in the WAL */
dan7c246102010-04-12 19:00:29 +0000403};
404
danb8fd6c22010-05-24 10:39:36 +0000405/*
406** The argument to this macro must be of type u32. On a little-endian
407** architecture, it returns the u32 value that results from interpreting
408** the 4 bytes as a big-endian value. On a big-endian architecture, it
409** returns the value that would be produced by intepreting the 4 bytes
410** of the input value as a little-endian integer.
411*/
412#define BYTESWAP32(x) ( \
413 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
414 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
415)
dan64d039e2010-04-13 19:27:31 +0000416
dan7c246102010-04-12 19:00:29 +0000417/*
drh7e263722010-05-20 21:21:09 +0000418** Generate or extend an 8 byte checksum based on the data in
419** array aByte[] and the initial values of aIn[0] and aIn[1] (or
420** initial values of 0 and 0 if aIn==NULL).
421**
422** The checksum is written back into aOut[] before returning.
423**
424** nByte must be a positive multiple of 8.
dan7c246102010-04-12 19:00:29 +0000425*/
drh7e263722010-05-20 21:21:09 +0000426static void walChecksumBytes(
danb8fd6c22010-05-24 10:39:36 +0000427 int nativeCksum, /* True for native byte-order, false for non-native */
drh7e263722010-05-20 21:21:09 +0000428 u8 *a, /* Content to be checksummed */
429 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
430 const u32 *aIn, /* Initial checksum value input */
431 u32 *aOut /* OUT: Final checksum value output */
432){
433 u32 s1, s2;
danb8fd6c22010-05-24 10:39:36 +0000434 u32 *aData = (u32 *)a;
435 u32 *aEnd = (u32 *)&a[nByte];
436
drh7e263722010-05-20 21:21:09 +0000437 if( aIn ){
438 s1 = aIn[0];
439 s2 = aIn[1];
440 }else{
441 s1 = s2 = 0;
442 }
dan7c246102010-04-12 19:00:29 +0000443
drh584c7542010-05-19 18:08:10 +0000444 assert( nByte>=8 );
danb8fd6c22010-05-24 10:39:36 +0000445 assert( (nByte&0x00000007)==0 );
dan7c246102010-04-12 19:00:29 +0000446
danb8fd6c22010-05-24 10:39:36 +0000447 if( nativeCksum ){
448 do {
449 s1 += *aData++ + s2;
450 s2 += *aData++ + s1;
451 }while( aData<aEnd );
452 }else{
453 do {
454 s1 += BYTESWAP32(aData[0]) + s2;
455 s2 += BYTESWAP32(aData[1]) + s1;
456 aData += 2;
457 }while( aData<aEnd );
458 }
459
drh7e263722010-05-20 21:21:09 +0000460 aOut[0] = s1;
461 aOut[1] = s2;
dan7c246102010-04-12 19:00:29 +0000462}
463
464/*
drh7e263722010-05-20 21:21:09 +0000465** Write the header information in pWal->hdr into the wal-index.
466**
467** The checksum on pWal->hdr is updated before it is written.
drh7ed91f22010-04-29 22:34:07 +0000468*/
drh7e263722010-05-20 21:21:09 +0000469static void walIndexWriteHdr(Wal *pWal){
drh286a2882010-05-20 23:51:06 +0000470 WalIndexHdr *aHdr;
drh73b64e42010-05-30 19:55:15 +0000471
472 assert( pWal->writeLock );
473 walChecksumBytes(1, (u8*)&pWal->hdr, offsetof(WalIndexHdr, aCksum),
drh7e263722010-05-20 21:21:09 +0000474 0, pWal->hdr.aCksum);
drh286a2882010-05-20 23:51:06 +0000475 aHdr = (WalIndexHdr*)pWal->pWiData;
drh73b64e42010-05-30 19:55:15 +0000476 memcpy(&aHdr[1], &pWal->hdr, sizeof(WalIndexHdr));
drh286a2882010-05-20 23:51:06 +0000477 sqlite3OsShmBarrier(pWal->pDbFd);
drh73b64e42010-05-30 19:55:15 +0000478 memcpy(&aHdr[0], &pWal->hdr, sizeof(WalIndexHdr));
dan7c246102010-04-12 19:00:29 +0000479}
480
481/*
482** This function encodes a single frame header and writes it to a buffer
drh7ed91f22010-04-29 22:34:07 +0000483** supplied by the caller. A frame-header is made up of a series of
dan7c246102010-04-12 19:00:29 +0000484** 4-byte big-endian integers, as follows:
485**
drh23ea97b2010-05-20 16:45:58 +0000486** 0: Page number.
487** 4: For commit records, the size of the database image in pages
488** after the commit. For all other records, zero.
drh7e263722010-05-20 21:21:09 +0000489** 8: Salt-1 (copied from the wal-header)
490** 12: Salt-2 (copied from the wal-header)
drh23ea97b2010-05-20 16:45:58 +0000491** 16: Checksum-1.
492** 20: Checksum-2.
dan7c246102010-04-12 19:00:29 +0000493*/
drh7ed91f22010-04-29 22:34:07 +0000494static void walEncodeFrame(
drh23ea97b2010-05-20 16:45:58 +0000495 Wal *pWal, /* The write-ahead log */
dan7c246102010-04-12 19:00:29 +0000496 u32 iPage, /* Database page number for frame */
497 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
drh7e263722010-05-20 21:21:09 +0000498 u8 *aData, /* Pointer to page data */
dan7c246102010-04-12 19:00:29 +0000499 u8 *aFrame /* OUT: Write encoded frame here */
500){
danb8fd6c22010-05-24 10:39:36 +0000501 int nativeCksum; /* True for native byte-order checksums */
dan71d89912010-05-24 13:57:42 +0000502 u32 *aCksum = pWal->hdr.aFrameCksum;
drh23ea97b2010-05-20 16:45:58 +0000503 assert( WAL_FRAME_HDRSIZE==24 );
dan97a31352010-04-16 13:59:31 +0000504 sqlite3Put4byte(&aFrame[0], iPage);
505 sqlite3Put4byte(&aFrame[4], nTruncate);
drh7e263722010-05-20 21:21:09 +0000506 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
dan7c246102010-04-12 19:00:29 +0000507
danb8fd6c22010-05-24 10:39:36 +0000508 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
dan71d89912010-05-24 13:57:42 +0000509 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
danb8fd6c22010-05-24 10:39:36 +0000510 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
dan7c246102010-04-12 19:00:29 +0000511
drh23ea97b2010-05-20 16:45:58 +0000512 sqlite3Put4byte(&aFrame[16], aCksum[0]);
513 sqlite3Put4byte(&aFrame[20], aCksum[1]);
dan7c246102010-04-12 19:00:29 +0000514}
515
516/*
drh7e263722010-05-20 21:21:09 +0000517** Check to see if the frame with header in aFrame[] and content
518** in aData[] is valid. If it is a valid frame, fill *piPage and
519** *pnTruncate and return true. Return if the frame is not valid.
dan7c246102010-04-12 19:00:29 +0000520*/
drh7ed91f22010-04-29 22:34:07 +0000521static int walDecodeFrame(
drh23ea97b2010-05-20 16:45:58 +0000522 Wal *pWal, /* The write-ahead log */
dan7c246102010-04-12 19:00:29 +0000523 u32 *piPage, /* OUT: Database page number for frame */
524 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
dan7c246102010-04-12 19:00:29 +0000525 u8 *aData, /* Pointer to page data (for checksum) */
526 u8 *aFrame /* Frame data */
527){
danb8fd6c22010-05-24 10:39:36 +0000528 int nativeCksum; /* True for native byte-order checksums */
dan71d89912010-05-24 13:57:42 +0000529 u32 *aCksum = pWal->hdr.aFrameCksum;
drhc8179152010-05-24 13:28:36 +0000530 u32 pgno; /* Page number of the frame */
drh23ea97b2010-05-20 16:45:58 +0000531 assert( WAL_FRAME_HDRSIZE==24 );
532
drh7e263722010-05-20 21:21:09 +0000533 /* A frame is only valid if the salt values in the frame-header
534 ** match the salt values in the wal-header.
535 */
536 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
drh23ea97b2010-05-20 16:45:58 +0000537 return 0;
538 }
dan4a4b01d2010-04-16 11:30:18 +0000539
drhc8179152010-05-24 13:28:36 +0000540 /* A frame is only valid if the page number is creater than zero.
541 */
542 pgno = sqlite3Get4byte(&aFrame[0]);
543 if( pgno==0 ){
544 return 0;
545 }
546
drh7e263722010-05-20 21:21:09 +0000547 /* A frame is only valid if a checksum of the first 16 bytes
548 ** of the frame-header, and the frame-data matches
549 ** the checksum in the last 8 bytes of the frame-header.
550 */
danb8fd6c22010-05-24 10:39:36 +0000551 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
dan71d89912010-05-24 13:57:42 +0000552 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
danb8fd6c22010-05-24 10:39:36 +0000553 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
drh23ea97b2010-05-20 16:45:58 +0000554 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
555 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
dan7c246102010-04-12 19:00:29 +0000556 ){
557 /* Checksum failed. */
558 return 0;
559 }
560
drh7e263722010-05-20 21:21:09 +0000561 /* If we reach this point, the frame is valid. Return the page number
562 ** and the new database size.
563 */
drhc8179152010-05-24 13:28:36 +0000564 *piPage = pgno;
dan97a31352010-04-16 13:59:31 +0000565 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
dan7c246102010-04-12 19:00:29 +0000566 return 1;
567}
568
danbb23aff2010-05-10 14:46:09 +0000569/*
drh29d4dbe2010-05-18 23:29:52 +0000570** Define the parameters of the hash tables in the wal-index file. There
danbb23aff2010-05-10 14:46:09 +0000571** is a hash-table following every HASHTABLE_NPAGE page numbers in the
572** wal-index.
drh29d4dbe2010-05-18 23:29:52 +0000573**
574** Changing any of these constants will alter the wal-index format and
575** create incompatibilities.
danbb23aff2010-05-10 14:46:09 +0000576*/
drh29d4dbe2010-05-18 23:29:52 +0000577#define HASHTABLE_NPAGE 4096 /* Must be power of 2 and multiple of 256 */
danbb23aff2010-05-10 14:46:09 +0000578#define HASHTABLE_DATATYPE u16
drh29d4dbe2010-05-18 23:29:52 +0000579#define HASHTABLE_HASH_1 383 /* Should be prime */
580#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
581#define HASHTABLE_NBYTE (sizeof(HASHTABLE_DATATYPE)*HASHTABLE_NSLOT)
dan7c246102010-04-12 19:00:29 +0000582
583/*
drh73b64e42010-05-30 19:55:15 +0000584** Set or release locks.
585**
586** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
587*/
588static int walLockShared(Wal *pWal, int lockIdx){
589 if( pWal->exclusiveMode ) return SQLITE_OK;
590 return sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
591 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
592}
593static void walUnlockShared(Wal *pWal, int lockIdx){
594 if( pWal->exclusiveMode ) return;
595 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
596 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
597}
598static int walLockExclusive(Wal *pWal, int lockIdx, int n){
599 if( pWal->exclusiveMode ) return SQLITE_OK;
600 return sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
601 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
602}
603static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
604 if( pWal->exclusiveMode ) return;
605 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
606 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
607}
608
609/*
drha2a42012010-05-18 18:01:08 +0000610** Return the index in the Wal.pWiData array that corresponds to
611** frame iFrame.
612**
613** Wal.pWiData is an array of u32 elements that is the wal-index.
614** The array begins with a header and is then followed by alternating
615** "map" and "hash-table" blocks. Each "map" block consists of
616** HASHTABLE_NPAGE u32 elements which are page numbers corresponding
617** to frames in the WAL file.
618**
619** This routine returns an index X such that Wal.pWiData[X] is part
620** of a "map" block that contains the page number of the iFrame-th
621** frame in the WAL file.
dan7c246102010-04-12 19:00:29 +0000622*/
drh7ed91f22010-04-29 22:34:07 +0000623static int walIndexEntry(u32 iFrame){
danff207012010-04-24 04:49:15 +0000624 return (
drh7ed91f22010-04-29 22:34:07 +0000625 (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)/sizeof(u32)
danbb23aff2010-05-10 14:46:09 +0000626 + (((iFrame-1)/HASHTABLE_NPAGE) * HASHTABLE_NBYTE)/sizeof(u32)
627 + (iFrame-1)
danff207012010-04-24 04:49:15 +0000628 );
dan7c246102010-04-12 19:00:29 +0000629}
630
drh7ed91f22010-04-29 22:34:07 +0000631/*
danb7d53f52010-05-06 17:28:08 +0000632** Return the minimum mapping size in bytes that can be used to read the
633** wal-index up to and including frame iFrame. If iFrame is the last frame
634** in a block of 256 frames, the returned byte-count includes the space
635** required by the 256-byte index block.
636*/
637static int walMappingSize(u32 iFrame){
danbb23aff2010-05-10 14:46:09 +0000638 const int nByte = (sizeof(u32)*HASHTABLE_NPAGE + HASHTABLE_NBYTE) ;
639 return ( WALINDEX_LOCK_OFFSET
640 + WALINDEX_LOCK_RESERVED
641 + nByte * ((iFrame + HASHTABLE_NPAGE - 1)/HASHTABLE_NPAGE)
danb7d53f52010-05-06 17:28:08 +0000642 );
643}
644
645/*
drh5530b762010-04-30 14:39:50 +0000646** Release our reference to the wal-index memory map, if we are holding
647** it.
drh7ed91f22010-04-29 22:34:07 +0000648*/
649static void walIndexUnmap(Wal *pWal){
650 if( pWal->pWiData ){
drhd9e5c4f2010-05-12 18:01:39 +0000651 sqlite3OsShmRelease(pWal->pDbFd);
drh7ed91f22010-04-29 22:34:07 +0000652 }
drh026ac282010-05-26 15:06:38 +0000653 pWal->pWiData = 0;
654 pWal->szWIndex = -1;
drh7ed91f22010-04-29 22:34:07 +0000655}
dan7c246102010-04-12 19:00:29 +0000656
657/*
drh5530b762010-04-30 14:39:50 +0000658** Map the wal-index file into memory if it isn't already.
659**
drh026ac282010-05-26 15:06:38 +0000660** The reqSize parameter is the requested size of the mapping. The
661** mapping will be at least this big if the underlying storage is
662** that big. But the mapping will never grow larger than the underlying
663** storage. Use the walIndexRemap() to enlarget the storage space.
drh7ed91f22010-04-29 22:34:07 +0000664*/
drh5530b762010-04-30 14:39:50 +0000665static int walIndexMap(Wal *pWal, int reqSize){
666 int rc = SQLITE_OK;
dan998ad212010-05-07 06:59:08 +0000667 if( pWal->pWiData==0 || reqSize>pWal->szWIndex ){
drh5500a1f2010-05-13 09:11:31 +0000668 walIndexUnmap(pWal);
drhd9e5c4f2010-05-12 18:01:39 +0000669 rc = sqlite3OsShmGet(pWal->pDbFd, reqSize, &pWal->szWIndex,
drh5939f442010-05-18 13:27:12 +0000670 (void volatile**)(char volatile*)&pWal->pWiData);
dan65f2ac52010-05-07 09:43:50 +0000671 if( rc!=SQLITE_OK ){
672 walIndexUnmap(pWal);
673 }
drh79e6c782010-04-30 02:13:26 +0000674 }
675 return rc;
676}
677
678/*
drh026ac282010-05-26 15:06:38 +0000679** Enlarge the wal-index to be at least enlargeTo bytes in size and
drh5530b762010-04-30 14:39:50 +0000680** Remap the wal-index so that the mapping covers the full size
681** of the underlying file.
682**
683** If enlargeTo is non-negative, then increase the size of the underlying
684** storage to be at least as big as enlargeTo before remapping.
drh79e6c782010-04-30 02:13:26 +0000685*/
drh5530b762010-04-30 14:39:50 +0000686static int walIndexRemap(Wal *pWal, int enlargeTo){
687 int rc;
688 int sz;
drh73b64e42010-05-30 19:55:15 +0000689 assert( pWal->writeLock );
drhd9e5c4f2010-05-12 18:01:39 +0000690 rc = sqlite3OsShmSize(pWal->pDbFd, enlargeTo, &sz);
drh5530b762010-04-30 14:39:50 +0000691 if( rc==SQLITE_OK && sz>pWal->szWIndex ){
692 walIndexUnmap(pWal);
693 rc = walIndexMap(pWal, sz);
694 }
drh026ac282010-05-26 15:06:38 +0000695 assert( pWal->szWIndex>=enlargeTo || rc!=SQLITE_OK );
drh7ed91f22010-04-29 22:34:07 +0000696 return rc;
697}
698
699/*
drh29d4dbe2010-05-18 23:29:52 +0000700** Compute a hash on a page number. The resulting hash value must land
701** between 0 and (HASHTABLE_NSLOT-1).
702*/
703static int walHash(u32 iPage){
704 assert( iPage>0 );
705 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
706 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
707}
708static int walNextHash(int iPriorHash){
709 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
danbb23aff2010-05-10 14:46:09 +0000710}
711
712
713/*
714** Find the hash table and (section of the) page number array used to
715** store data for WAL frame iFrame.
716**
717** Set output variable *paHash to point to the start of the hash table
718** in the wal-index file. Set *piZero to one less than the frame
719** number of the first frame indexed by this hash table. If a
720** slot in the hash table is set to N, it refers to frame number
721** (*piZero+N) in the log.
722**
723** Finally, set *paPgno such that for all frames F between (*piZero+1) and
724** (*piZero+HASHTABLE_NPAGE), (*paPgno)[F] is the database page number
725** associated with frame F.
726*/
727static void walHashFind(
728 Wal *pWal, /* WAL handle */
729 u32 iFrame, /* Find the hash table indexing this frame */
drh5939f442010-05-18 13:27:12 +0000730 volatile HASHTABLE_DATATYPE **paHash, /* OUT: Pointer to hash index */
731 volatile u32 **paPgno, /* OUT: Pointer to page number array */
danbb23aff2010-05-10 14:46:09 +0000732 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
733){
734 u32 iZero;
drh5939f442010-05-18 13:27:12 +0000735 volatile u32 *aPgno;
736 volatile HASHTABLE_DATATYPE *aHash;
danbb23aff2010-05-10 14:46:09 +0000737
738 iZero = ((iFrame-1)/HASHTABLE_NPAGE) * HASHTABLE_NPAGE;
739 aPgno = &pWal->pWiData[walIndexEntry(iZero+1)-iZero-1];
740 aHash = (HASHTABLE_DATATYPE *)&aPgno[iZero+HASHTABLE_NPAGE+1];
741
742 /* Assert that:
743 **
744 ** + the mapping is large enough for this hash-table, and
745 **
746 ** + that aPgno[iZero+1] really is the database page number associated
747 ** with the first frame indexed by this hash table.
748 */
749 assert( (u32*)(&aHash[HASHTABLE_NSLOT])<=&pWal->pWiData[pWal->szWIndex/4] );
750 assert( walIndexEntry(iZero+1)==(&aPgno[iZero+1] - pWal->pWiData) );
751
752 *paHash = aHash;
753 *paPgno = aPgno;
754 *piZero = iZero;
755}
756
danca6b5ba2010-05-25 10:50:56 +0000757/*
758** Remove entries from the hash table that point to WAL slots greater
759** than pWal->hdr.mxFrame.
760**
761** This function is called whenever pWal->hdr.mxFrame is decreased due
762** to a rollback or savepoint.
763**
764** At most only the very last hash table needs to be updated. Any
765** later hash tables will be automatically cleared when pWal->hdr.mxFrame
766** advances to the point where those hash tables are actually needed.
767*/
768static void walCleanupHash(Wal *pWal){
769 volatile HASHTABLE_DATATYPE *aHash; /* Pointer to hash table to clear */
770 volatile u32 *aPgno; /* Unused return from walHashFind() */
771 u32 iZero; /* frame == (aHash[x]+iZero) */
772 int iLimit; /* Zero values greater than this */
773
drh73b64e42010-05-30 19:55:15 +0000774 assert( pWal->writeLock );
danca6b5ba2010-05-25 10:50:56 +0000775 walHashFind(pWal, pWal->hdr.mxFrame+1, &aHash, &aPgno, &iZero);
776 iLimit = pWal->hdr.mxFrame - iZero;
777 if( iLimit>0 ){
778 int nByte; /* Number of bytes to zero in aPgno[] */
779 int i; /* Used to iterate through aHash[] */
780 for(i=0; i<HASHTABLE_NSLOT; i++){
781 if( aHash[i]>iLimit ){
782 aHash[i] = 0;
783 }
784 }
785
786 /* Zero the entries in the aPgno array that correspond to frames with
787 ** frame numbers greater than pWal->hdr.mxFrame.
788 */
789 nByte = sizeof(u32) * (HASHTABLE_NPAGE-iLimit);
790 memset((void *)&aPgno[iZero+iLimit+1], 0, nByte);
791 assert( &((u8 *)&aPgno[iZero+iLimit+1])[nByte]==(u8 *)aHash );
792 }
793
794#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
795 /* Verify that the every entry in the mapping region is still reachable
796 ** via the hash table even after the cleanup.
797 */
798 {
799 int i; /* Loop counter */
800 int iKey; /* Hash key */
801 for(i=1; i<=iLimit; i++){
802 for(iKey=walHash(aPgno[i+iZero]); aHash[iKey]; iKey=walNextHash(iKey)){
803 if( aHash[iKey]==i ) break;
804 }
805 assert( aHash[iKey]==i );
806 }
807 }
808#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
809}
810
danbb23aff2010-05-10 14:46:09 +0000811
drh7ed91f22010-04-29 22:34:07 +0000812/*
drh29d4dbe2010-05-18 23:29:52 +0000813** Set an entry in the wal-index that will map database page number
814** pPage into WAL frame iFrame.
dan7c246102010-04-12 19:00:29 +0000815*/
drh7ed91f22010-04-29 22:34:07 +0000816static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
danbb23aff2010-05-10 14:46:09 +0000817 int rc; /* Return code */
818 int nMapping; /* Required mapping size in bytes */
drh7ed91f22010-04-29 22:34:07 +0000819
danbb23aff2010-05-10 14:46:09 +0000820 /* Make sure the wal-index is mapped. Enlarge the mapping if required. */
821 nMapping = walMappingSize(iFrame);
drh026ac282010-05-26 15:06:38 +0000822 rc = walIndexMap(pWal, nMapping);
danbb23aff2010-05-10 14:46:09 +0000823 while( rc==SQLITE_OK && nMapping>pWal->szWIndex ){
drh026ac282010-05-26 15:06:38 +0000824 rc = walIndexRemap(pWal, nMapping);
dance4f05f2010-04-22 19:14:13 +0000825 }
826
danbb23aff2010-05-10 14:46:09 +0000827 /* Assuming the wal-index file was successfully mapped, find the hash
828 ** table and section of of the page number array that pertain to frame
829 ** iFrame of the WAL. Then populate the page number array and the hash
830 ** table entry.
dan7c246102010-04-12 19:00:29 +0000831 */
danbb23aff2010-05-10 14:46:09 +0000832 if( rc==SQLITE_OK ){
833 int iKey; /* Hash table key */
834 u32 iZero; /* One less than frame number of aPgno[1] */
drh5939f442010-05-18 13:27:12 +0000835 volatile u32 *aPgno; /* Page number array */
836 volatile HASHTABLE_DATATYPE *aHash; /* Hash table */
837 int idx; /* Value to write to hash-table slot */
drh29d4dbe2010-05-18 23:29:52 +0000838 TESTONLY( int nCollide = 0; /* Number of hash collisions */ )
dan7c246102010-04-12 19:00:29 +0000839
danbb23aff2010-05-10 14:46:09 +0000840 walHashFind(pWal, iFrame, &aHash, &aPgno, &iZero);
841 idx = iFrame - iZero;
danca6b5ba2010-05-25 10:50:56 +0000842 if( idx==1 ){
843 memset((void*)&aPgno[iZero+1], 0, HASHTABLE_NPAGE*sizeof(u32));
844 memset((void*)aHash, 0, HASHTABLE_NBYTE);
845 }
drh29d4dbe2010-05-18 23:29:52 +0000846 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
danca6b5ba2010-05-25 10:50:56 +0000847
848 if( aPgno[iFrame] ){
849 /* If the entry in aPgno[] is already set, then the previous writer
850 ** must have exited unexpectedly in the middle of a transaction (after
851 ** writing one or more dirty pages to the WAL to free up memory).
852 ** Remove the remnants of that writers uncommitted transaction from
853 ** the hash-table before writing any new entries.
854 */
855 walCleanupHash(pWal);
856 assert( !aPgno[iFrame] );
857 }
danbb23aff2010-05-10 14:46:09 +0000858 aPgno[iFrame] = iPage;
dan6f150142010-05-21 15:31:56 +0000859 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
drh29d4dbe2010-05-18 23:29:52 +0000860 assert( nCollide++ < idx );
861 }
danbb23aff2010-05-10 14:46:09 +0000862 aHash[iKey] = idx;
drh4fa95bf2010-05-22 00:55:39 +0000863
864#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
865 /* Verify that the number of entries in the hash table exactly equals
866 ** the number of entries in the mapping region.
867 */
868 {
869 int i; /* Loop counter */
870 int nEntry = 0; /* Number of entries in the hash table */
871 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
872 assert( nEntry==idx );
873 }
874
875 /* Verify that the every entry in the mapping region is reachable
876 ** via the hash table. This turns out to be a really, really expensive
877 ** thing to check, so only do this occasionally - not on every
878 ** iteration.
879 */
880 if( (idx&0x3ff)==0 ){
881 int i; /* Loop counter */
882 for(i=1; i<=idx; i++){
883 for(iKey=walHash(aPgno[i+iZero]); aHash[iKey]; iKey=walNextHash(iKey)){
884 if( aHash[iKey]==i ) break;
885 }
886 assert( aHash[iKey]==i );
887 }
888 }
889#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
dan7c246102010-04-12 19:00:29 +0000890 }
dan31f98fc2010-04-27 05:42:32 +0000891
drh4fa95bf2010-05-22 00:55:39 +0000892
danbb23aff2010-05-10 14:46:09 +0000893 return rc;
dan7c246102010-04-12 19:00:29 +0000894}
895
896
897/*
drh7ed91f22010-04-29 22:34:07 +0000898** Recover the wal-index by reading the write-ahead log file.
drh73b64e42010-05-30 19:55:15 +0000899**
900** This routine first tries to establish an exclusive lock on the
901** wal-index to prevent other threads/processes from doing anything
902** with the WAL or wal-index while recovery is running. The
903** WAL_RECOVER_LOCK is also held so that other threads will know
904** that this thread is running recovery. If unable to establish
905** the necessary locks, this routine returns SQLITE_BUSY.
dan7c246102010-04-12 19:00:29 +0000906*/
drh7ed91f22010-04-29 22:34:07 +0000907static int walIndexRecover(Wal *pWal){
dan7c246102010-04-12 19:00:29 +0000908 int rc; /* Return Code */
909 i64 nSize; /* Size of log file */
dan71d89912010-05-24 13:57:42 +0000910 u32 aFrameCksum[2] = {0, 0};
dan7c246102010-04-12 19:00:29 +0000911
drh73b64e42010-05-30 19:55:15 +0000912 rc = walLockExclusive(pWal, WAL_ALL_BUT_WRITE, SQLITE_SHM_NLOCK-1);
913 if( rc ){
914 return rc;
915 }
916
dan71d89912010-05-24 13:57:42 +0000917 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
dan7c246102010-04-12 19:00:29 +0000918
drhd9e5c4f2010-05-12 18:01:39 +0000919 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
dan7c246102010-04-12 19:00:29 +0000920 if( rc!=SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +0000921 goto recovery_error;
dan7c246102010-04-12 19:00:29 +0000922 }
923
danb8fd6c22010-05-24 10:39:36 +0000924 if( nSize>WAL_HDRSIZE ){
925 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
dan7c246102010-04-12 19:00:29 +0000926 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
drh584c7542010-05-19 18:08:10 +0000927 int szFrame; /* Number of bytes in buffer aFrame[] */
dan7c246102010-04-12 19:00:29 +0000928 u8 *aData; /* Pointer to data part of aFrame buffer */
929 int iFrame; /* Index of last frame read */
930 i64 iOffset; /* Next offset to read from log file */
drh6e810962010-05-19 17:49:50 +0000931 int szPage; /* Page size according to the log */
danb8fd6c22010-05-24 10:39:36 +0000932 u32 magic; /* Magic value read from WAL header */
dan7c246102010-04-12 19:00:29 +0000933
danb8fd6c22010-05-24 10:39:36 +0000934 /* Read in the WAL header. */
drhd9e5c4f2010-05-12 18:01:39 +0000935 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
dan7c246102010-04-12 19:00:29 +0000936 if( rc!=SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +0000937 goto recovery_error;
dan7c246102010-04-12 19:00:29 +0000938 }
939
940 /* If the database page size is not a power of two, or is greater than
danb8fd6c22010-05-24 10:39:36 +0000941 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
942 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
943 ** WAL file.
dan7c246102010-04-12 19:00:29 +0000944 */
danb8fd6c22010-05-24 10:39:36 +0000945 magic = sqlite3Get4byte(&aBuf[0]);
drh23ea97b2010-05-20 16:45:58 +0000946 szPage = sqlite3Get4byte(&aBuf[8]);
danb8fd6c22010-05-24 10:39:36 +0000947 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
948 || szPage&(szPage-1)
949 || szPage>SQLITE_MAX_PAGE_SIZE
950 || szPage<512
951 ){
dan7c246102010-04-12 19:00:29 +0000952 goto finished;
953 }
dan71d89912010-05-24 13:57:42 +0000954 pWal->hdr.bigEndCksum = (magic&0x00000001);
drh7e263722010-05-20 21:21:09 +0000955 pWal->szPage = szPage;
drh23ea97b2010-05-20 16:45:58 +0000956 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
drh7e263722010-05-20 21:21:09 +0000957 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
dan71d89912010-05-24 13:57:42 +0000958 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
959 aBuf, WAL_HDRSIZE, 0, pWal->hdr.aFrameCksum
960 );
dan7c246102010-04-12 19:00:29 +0000961
962 /* Malloc a buffer to read frames into. */
drh584c7542010-05-19 18:08:10 +0000963 szFrame = szPage + WAL_FRAME_HDRSIZE;
964 aFrame = (u8 *)sqlite3_malloc(szFrame);
dan7c246102010-04-12 19:00:29 +0000965 if( !aFrame ){
drh73b64e42010-05-30 19:55:15 +0000966 rc = SQLITE_NOMEM;
967 goto recovery_error;
dan7c246102010-04-12 19:00:29 +0000968 }
drh7ed91f22010-04-29 22:34:07 +0000969 aData = &aFrame[WAL_FRAME_HDRSIZE];
dan7c246102010-04-12 19:00:29 +0000970
971 /* Read all frames from the log file. */
972 iFrame = 0;
drh584c7542010-05-19 18:08:10 +0000973 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
dan7c246102010-04-12 19:00:29 +0000974 u32 pgno; /* Database page number for frame */
975 u32 nTruncate; /* dbsize field from frame header */
976 int isValid; /* True if this frame is valid */
977
978 /* Read and decode the next log frame. */
drh584c7542010-05-19 18:08:10 +0000979 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
dan7c246102010-04-12 19:00:29 +0000980 if( rc!=SQLITE_OK ) break;
drh7e263722010-05-20 21:21:09 +0000981 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
dan7c246102010-04-12 19:00:29 +0000982 if( !isValid ) break;
danc7991bd2010-05-05 19:04:59 +0000983 rc = walIndexAppend(pWal, ++iFrame, pgno);
984 if( rc!=SQLITE_OK ) break;
dan7c246102010-04-12 19:00:29 +0000985
986 /* If nTruncate is non-zero, this is a commit record. */
987 if( nTruncate ){
dan71d89912010-05-24 13:57:42 +0000988 pWal->hdr.mxFrame = iFrame;
989 pWal->hdr.nPage = nTruncate;
990 pWal->hdr.szPage = szPage;
991 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
992 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
dan7c246102010-04-12 19:00:29 +0000993 }
994 }
995
996 sqlite3_free(aFrame);
dan7c246102010-04-12 19:00:29 +0000997 }
998
999finished:
dan71d89912010-05-24 13:57:42 +00001000 if( rc==SQLITE_OK && pWal->hdr.mxFrame==0 ){
drh026ac282010-05-26 15:06:38 +00001001 rc = walIndexRemap(pWal, walMappingSize(1));
dan576bc322010-05-06 18:04:50 +00001002 }
1003 if( rc==SQLITE_OK ){
dan71d89912010-05-24 13:57:42 +00001004 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
1005 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
drh7e263722010-05-20 21:21:09 +00001006 walIndexWriteHdr(pWal);
dan576bc322010-05-06 18:04:50 +00001007 }
drh73b64e42010-05-30 19:55:15 +00001008
1009recovery_error:
1010 walUnlockExclusive(pWal, WAL_ALL_BUT_WRITE, SQLITE_SHM_NLOCK-1);
dan7c246102010-04-12 19:00:29 +00001011 return rc;
1012}
1013
drha8e654e2010-05-04 17:38:42 +00001014/*
dan1018e902010-05-05 15:33:05 +00001015** Close an open wal-index.
drha8e654e2010-05-04 17:38:42 +00001016*/
dan1018e902010-05-05 15:33:05 +00001017static void walIndexClose(Wal *pWal, int isDelete){
drh73b64e42010-05-30 19:55:15 +00001018 if( pWal->isWIndexOpen ){
drhd9e5c4f2010-05-12 18:01:39 +00001019 sqlite3OsShmClose(pWal->pDbFd, isDelete);
drh73b64e42010-05-30 19:55:15 +00001020 pWal->isWIndexOpen = 0;
drha8e654e2010-05-04 17:38:42 +00001021 }
1022}
1023
dan7c246102010-04-12 19:00:29 +00001024/*
1025** Open a connection to the log file associated with database zDb. The
1026** database file does not actually have to exist. zDb is used only to
1027** figure out the name of the log file to open. If the log file does not
1028** exist it is created by this call.
dan3de777f2010-04-17 12:31:37 +00001029**
1030** A SHARED lock should be held on the database file when this function
1031** is called. The purpose of this SHARED lock is to prevent any other
drh7ed91f22010-04-29 22:34:07 +00001032** client from unlinking the log or wal-index file. If another process
dan3de777f2010-04-17 12:31:37 +00001033** were to do this just after this client opened one of these files, the
1034** system would be badly broken.
danef378022010-05-04 11:06:03 +00001035**
1036** If the log file is successfully opened, SQLITE_OK is returned and
1037** *ppWal is set to point to a new WAL handle. If an error occurs,
1038** an SQLite error code is returned and *ppWal is left unmodified.
dan7c246102010-04-12 19:00:29 +00001039*/
drhc438efd2010-04-26 00:19:45 +00001040int sqlite3WalOpen(
drh7ed91f22010-04-29 22:34:07 +00001041 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
drhd9e5c4f2010-05-12 18:01:39 +00001042 sqlite3_file *pDbFd, /* The open database file */
1043 const char *zDbName, /* Name of the database file */
drh7ed91f22010-04-29 22:34:07 +00001044 Wal **ppWal /* OUT: Allocated Wal handle */
dan7c246102010-04-12 19:00:29 +00001045){
danef378022010-05-04 11:06:03 +00001046 int rc; /* Return Code */
drh7ed91f22010-04-29 22:34:07 +00001047 Wal *pRet; /* Object to allocate and return */
dan7c246102010-04-12 19:00:29 +00001048 int flags; /* Flags passed to OsOpen() */
drhd9e5c4f2010-05-12 18:01:39 +00001049 char *zWal; /* Name of write-ahead log file */
dan7c246102010-04-12 19:00:29 +00001050 int nWal; /* Length of zWal in bytes */
1051
drhd9e5c4f2010-05-12 18:01:39 +00001052 assert( zDbName && zDbName[0] );
1053 assert( pDbFd );
dan7c246102010-04-12 19:00:29 +00001054
drh1b78eaf2010-05-25 13:40:03 +00001055 /* In the amalgamation, the os_unix.c and os_win.c source files come before
1056 ** this source file. Verify that the #defines of the locking byte offsets
1057 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
1058 */
1059#ifdef WIN_SHM_BASE
1060 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
1061#endif
1062#ifdef UNIX_SHM_BASE
1063 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
1064#endif
1065
1066
drh7ed91f22010-04-29 22:34:07 +00001067 /* Allocate an instance of struct Wal to return. */
1068 *ppWal = 0;
drh686138f2010-05-12 18:10:52 +00001069 nWal = sqlite3Strlen30(zDbName) + 5;
drhd9e5c4f2010-05-12 18:01:39 +00001070 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile + nWal);
dan76ed3bc2010-05-03 17:18:24 +00001071 if( !pRet ){
1072 return SQLITE_NOMEM;
1073 }
1074
dan7c246102010-04-12 19:00:29 +00001075 pRet->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00001076 pRet->pWalFd = (sqlite3_file *)&pRet[1];
1077 pRet->pDbFd = pDbFd;
drh026ac282010-05-26 15:06:38 +00001078 pRet->szWIndex = -1;
drh73b64e42010-05-30 19:55:15 +00001079 pRet->readLock = -1;
drh7e263722010-05-20 21:21:09 +00001080 sqlite3_randomness(8, &pRet->hdr.aSalt);
drhd9e5c4f2010-05-12 18:01:39 +00001081 pRet->zWalName = zWal = pVfs->szOsFile + (char*)pRet->pWalFd;
1082 sqlite3_snprintf(nWal, zWal, "%s-wal", zDbName);
1083 rc = sqlite3OsShmOpen(pDbFd);
dan7c246102010-04-12 19:00:29 +00001084
drh7ed91f22010-04-29 22:34:07 +00001085 /* Open file handle on the write-ahead log file. */
dan76ed3bc2010-05-03 17:18:24 +00001086 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00001087 pRet->isWIndexOpen = 1;
dan76ed3bc2010-05-03 17:18:24 +00001088 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_JOURNAL);
drhd9e5c4f2010-05-12 18:01:39 +00001089 rc = sqlite3OsOpen(pVfs, zWal, pRet->pWalFd, flags, &flags);
dan76ed3bc2010-05-03 17:18:24 +00001090 }
dan7c246102010-04-12 19:00:29 +00001091
dan7c246102010-04-12 19:00:29 +00001092 if( rc!=SQLITE_OK ){
dan1018e902010-05-05 15:33:05 +00001093 walIndexClose(pRet, 0);
drhd9e5c4f2010-05-12 18:01:39 +00001094 sqlite3OsClose(pRet->pWalFd);
danef378022010-05-04 11:06:03 +00001095 sqlite3_free(pRet);
1096 }else{
1097 *ppWal = pRet;
dan7c246102010-04-12 19:00:29 +00001098 }
dan7c246102010-04-12 19:00:29 +00001099 return rc;
1100}
1101
drha2a42012010-05-18 18:01:08 +00001102/*
1103** Find the smallest page number out of all pages held in the WAL that
1104** has not been returned by any prior invocation of this method on the
1105** same WalIterator object. Write into *piFrame the frame index where
1106** that page was last written into the WAL. Write into *piPage the page
1107** number.
1108**
1109** Return 0 on success. If there are no pages in the WAL with a page
1110** number larger than *piPage, then return 1.
1111*/
drh7ed91f22010-04-29 22:34:07 +00001112static int walIteratorNext(
1113 WalIterator *p, /* Iterator */
drha2a42012010-05-18 18:01:08 +00001114 u32 *piPage, /* OUT: The page number of the next page */
1115 u32 *piFrame /* OUT: Wal frame index of next page */
dan7c246102010-04-12 19:00:29 +00001116){
drha2a42012010-05-18 18:01:08 +00001117 u32 iMin; /* Result pgno must be greater than iMin */
1118 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
1119 int i; /* For looping through segments */
1120 int nBlock = p->nFinal; /* Number of entries in current segment */
dan7c246102010-04-12 19:00:29 +00001121
drha2a42012010-05-18 18:01:08 +00001122 iMin = p->iPrior;
1123 assert( iMin<0xffffffff );
dan7c246102010-04-12 19:00:29 +00001124 for(i=p->nSegment-1; i>=0; i--){
drh7ed91f22010-04-29 22:34:07 +00001125 struct WalSegment *pSegment = &p->aSegment[i];
dan7c246102010-04-12 19:00:29 +00001126 while( pSegment->iNext<nBlock ){
drha2a42012010-05-18 18:01:08 +00001127 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
dan7c246102010-04-12 19:00:29 +00001128 if( iPg>iMin ){
1129 if( iPg<iRet ){
1130 iRet = iPg;
1131 *piFrame = i*256 + 1 + pSegment->aIndex[pSegment->iNext];
1132 }
1133 break;
1134 }
1135 pSegment->iNext++;
1136 }
dan7c246102010-04-12 19:00:29 +00001137 nBlock = 256;
1138 }
1139
drha2a42012010-05-18 18:01:08 +00001140 *piPage = p->iPrior = iRet;
dan7c246102010-04-12 19:00:29 +00001141 return (iRet==0xFFFFFFFF);
1142}
1143
dan7c246102010-04-12 19:00:29 +00001144
drha2a42012010-05-18 18:01:08 +00001145static void walMergesort8(
1146 Pgno *aContent, /* Pages in wal */
1147 u8 *aBuffer, /* Buffer of at least *pnList items to use */
1148 u8 *aList, /* IN/OUT: List to sort */
1149 int *pnList /* IN/OUT: Number of elements in aList[] */
1150){
1151 int nList = *pnList;
1152 if( nList>1 ){
1153 int nLeft = nList / 2; /* Elements in left list */
1154 int nRight = nList - nLeft; /* Elements in right list */
1155 u8 *aLeft = aList; /* Left list */
1156 u8 *aRight = &aList[nLeft]; /* Right list */
1157 int iLeft = 0; /* Current index in aLeft */
1158 int iRight = 0; /* Current index in aright */
1159 int iOut = 0; /* Current index in output buffer */
1160
1161 /* TODO: Change to non-recursive version. */
1162 walMergesort8(aContent, aBuffer, aLeft, &nLeft);
1163 walMergesort8(aContent, aBuffer, aRight, &nRight);
1164
1165 while( iRight<nRight || iLeft<nLeft ){
1166 u8 logpage;
1167 Pgno dbpage;
1168
1169 if( (iLeft<nLeft)
1170 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
1171 ){
1172 logpage = aLeft[iLeft++];
1173 }else{
1174 logpage = aRight[iRight++];
1175 }
1176 dbpage = aContent[logpage];
1177
1178 aBuffer[iOut++] = logpage;
1179 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
1180
1181 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
1182 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
1183 }
1184 memcpy(aList, aBuffer, sizeof(aList[0])*iOut);
1185 *pnList = iOut;
1186 }
1187
1188#ifdef SQLITE_DEBUG
1189 {
1190 int i;
1191 for(i=1; i<*pnList; i++){
1192 assert( aContent[aList[i]] > aContent[aList[i-1]] );
1193 }
1194 }
1195#endif
1196}
1197
1198/*
1199** Map the wal-index into memory owned by this thread, if it is not
1200** mapped already. Then construct a WalInterator object that can be
1201** used to loop over all pages in the WAL in ascending order.
1202**
1203** On success, make *pp point to the newly allocated WalInterator object
1204** return SQLITE_OK. Otherwise, leave *pp unchanged and return an error
1205** code.
1206**
1207** The calling routine should invoke walIteratorFree() to destroy the
1208** WalIterator object when it has finished with it. The caller must
1209** also unmap the wal-index. But the wal-index must not be unmapped
1210** prior to the WalIterator object being destroyed.
1211*/
1212static int walIteratorInit(Wal *pWal, WalIterator **pp){
1213 u32 *aData; /* Content of the wal-index file */
1214 WalIterator *p; /* Return value */
1215 int nSegment; /* Number of segments to merge */
1216 u32 iLast; /* Last frame in log */
1217 int nByte; /* Number of bytes to allocate */
1218 int i; /* Iterator variable */
1219 int nFinal; /* Number of unindexed entries */
1220 u8 *aTmp; /* Temp space used by merge-sort */
1221 int rc; /* Return code of walIndexMap() */
1222 u8 *aSpace; /* Surplus space on the end of the allocation */
1223
1224 /* Make sure the wal-index is mapped into local memory */
drh027a1282010-05-19 01:53:53 +00001225 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
dan8f6097c2010-05-06 07:43:58 +00001226 if( rc!=SQLITE_OK ){
1227 return rc;
1228 }
drha2a42012010-05-18 18:01:08 +00001229
1230 /* This routine only runs while holding SQLITE_SHM_CHECKPOINT. No other
1231 ** thread is able to write to shared memory while this routine is
1232 ** running (or, indeed, while the WalIterator object exists). Hence,
1233 ** we can cast off the volatile qualifacation from shared memory
1234 */
drh73b64e42010-05-30 19:55:15 +00001235 assert( pWal->ckptLock );
drh5939f442010-05-18 13:27:12 +00001236 aData = (u32*)pWal->pWiData;
drha2a42012010-05-18 18:01:08 +00001237
1238 /* Allocate space for the WalIterator object */
drh027a1282010-05-19 01:53:53 +00001239 iLast = pWal->hdr.mxFrame;
dan7c246102010-04-12 19:00:29 +00001240 nSegment = (iLast >> 8) + 1;
1241 nFinal = (iLast & 0x000000FF);
danbb23aff2010-05-10 14:46:09 +00001242 nByte = sizeof(WalIterator) + (nSegment+1)*(sizeof(struct WalSegment)+256);
drh7ed91f22010-04-29 22:34:07 +00001243 p = (WalIterator *)sqlite3_malloc(nByte);
dan8f6097c2010-05-06 07:43:58 +00001244 if( !p ){
drha2a42012010-05-18 18:01:08 +00001245 return SQLITE_NOMEM;
1246 }
1247 memset(p, 0, nByte);
dan76ed3bc2010-05-03 17:18:24 +00001248
drha2a42012010-05-18 18:01:08 +00001249 /* Initialize the WalIterator object. Each 256-entry segment is
1250 ** presorted in order to make iterating through all entries much
1251 ** faster.
1252 */
1253 p->nSegment = nSegment;
1254 aSpace = (u8 *)&p->aSegment[nSegment];
1255 aTmp = &aSpace[nSegment*256];
1256 for(i=0; i<nSegment; i++){
1257 int j;
1258 int nIndex = (i==nSegment-1) ? nFinal : 256;
1259 p->aSegment[i].aPgno = &aData[walIndexEntry(i*256+1)];
1260 p->aSegment[i].aIndex = aSpace;
1261 for(j=0; j<nIndex; j++){
1262 aSpace[j] = j;
dan76ed3bc2010-05-03 17:18:24 +00001263 }
drha2a42012010-05-18 18:01:08 +00001264 walMergesort8(p->aSegment[i].aPgno, aTmp, aSpace, &nIndex);
1265 memset(&aSpace[nIndex], aSpace[nIndex-1], 256-nIndex);
1266 aSpace += 256;
1267 p->nFinal = nIndex;
dan7c246102010-04-12 19:00:29 +00001268 }
1269
drha2a42012010-05-18 18:01:08 +00001270 /* Return the fully initializd WalIterator object */
dan8f6097c2010-05-06 07:43:58 +00001271 *pp = p;
drha2a42012010-05-18 18:01:08 +00001272 return SQLITE_OK ;
dan7c246102010-04-12 19:00:29 +00001273}
1274
1275/*
drha2a42012010-05-18 18:01:08 +00001276** Free an iterator allocated by walIteratorInit().
dan7c246102010-04-12 19:00:29 +00001277*/
drh7ed91f22010-04-29 22:34:07 +00001278static void walIteratorFree(WalIterator *p){
dan7c246102010-04-12 19:00:29 +00001279 sqlite3_free(p);
1280}
1281
drh73b64e42010-05-30 19:55:15 +00001282
dan7c246102010-04-12 19:00:29 +00001283/*
drh73b64e42010-05-30 19:55:15 +00001284** Copy as much content as we can from the WAL back into the database file
1285** in response to an sqlite3_wal_checkpoint() request or the equivalent.
1286**
1287** The amount of information copies from WAL to database might be limited
1288** by active readers. This routine will never overwrite a database page
1289** that a concurrent reader might be using.
1290**
1291** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
1292** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
1293** checkpoints are always run by a background thread or background
1294** process, foreground threads will never block on a lengthy fsync call.
1295**
1296** Fsync is called on the WAL before writing content out of the WAL and
1297** into the database. This ensures that if the new content is persistent
1298** in the WAL and can be recovered following a power-loss or hard reset.
1299**
1300** Fsync is also called on the database file if (and only if) the entire
1301** WAL content is copied into the database file. This second fsync makes
1302** it safe to delete the WAL since the new content will persist in the
1303** database file.
1304**
1305** This routine uses and updates the nBackfill field of the wal-index header.
1306** This is the only routine tha will increase the value of nBackfill.
1307** (A WAL reset or recovery will revert nBackfill to zero, but not increase
1308** its value.)
1309**
1310** The caller must be holding sufficient locks to ensure that no other
1311** checkpoint is running (in any other thread or process) at the same
1312** time.
dan7c246102010-04-12 19:00:29 +00001313*/
drh7ed91f22010-04-29 22:34:07 +00001314static int walCheckpoint(
1315 Wal *pWal, /* Wal connection */
danc5118782010-04-17 17:34:41 +00001316 int sync_flags, /* Flags for OsSync() (or 0) */
danb6e099a2010-05-04 14:47:39 +00001317 int nBuf, /* Size of zBuf in bytes */
dan7c246102010-04-12 19:00:29 +00001318 u8 *zBuf /* Temporary buffer to use */
1319){
1320 int rc; /* Return code */
drh6e810962010-05-19 17:49:50 +00001321 int szPage = pWal->hdr.szPage; /* Database page-size */
drh7ed91f22010-04-29 22:34:07 +00001322 WalIterator *pIter = 0; /* Wal iterator context */
dan7c246102010-04-12 19:00:29 +00001323 u32 iDbpage = 0; /* Next database page to write */
drh7ed91f22010-04-29 22:34:07 +00001324 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
drh73b64e42010-05-30 19:55:15 +00001325 u32 mxSafeFrame; /* Max frame that can be backfilled */
1326 int i; /* Loop counter */
1327 volatile WalIndexHdr *pHdr; /* The actual wal-index header in SHM */
1328 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
dan7c246102010-04-12 19:00:29 +00001329
1330 /* Allocate the iterator */
dan8f6097c2010-05-06 07:43:58 +00001331 rc = walIteratorInit(pWal, &pIter);
drh027a1282010-05-19 01:53:53 +00001332 if( rc!=SQLITE_OK || pWal->hdr.mxFrame==0 ){
drh73b64e42010-05-30 19:55:15 +00001333 walIteratorFree(pIter);
1334 return rc;
danb6e099a2010-05-04 14:47:39 +00001335 }
1336
drh73b64e42010-05-30 19:55:15 +00001337 /*** TODO: Move this test out to the caller. Make it an assert() here ***/
drh6e810962010-05-19 17:49:50 +00001338 if( pWal->hdr.szPage!=nBuf ){
drh73b64e42010-05-30 19:55:15 +00001339 walIteratorFree(pIter);
1340 return SQLITE_CORRUPT_BKPT;
danb6e099a2010-05-04 14:47:39 +00001341 }
1342
drh73b64e42010-05-30 19:55:15 +00001343 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
1344 ** safe to write into the database. Frames beyond mxSafeFrame might
1345 ** overwrite database pages that are in use by active readers and thus
1346 ** cannot be backfilled from the WAL.
1347 */
1348 mxSafeFrame = 0;
1349 pHdr = (volatile WalIndexHdr*)pWal->pWiData;
1350 pInfo = (volatile WalCkptInfo*)&pHdr[2];
1351 assert( pInfo==walCkptInfo(pWal) );
1352 for(i=1; i<WAL_NREADER; i++){
1353 u32 y = pInfo->aReadMark[i];
1354 if( y>0 && (mxSafeFrame==0 || mxSafeFrame<y) ){
1355 if( y<pWal->hdr.mxFrame
1356 && (rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1))==SQLITE_OK
1357 ){
1358 pInfo->aReadMark[i] = 0;
1359 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
1360 }else{
1361 mxSafeFrame = y;
1362 }
1363 }
danc5118782010-04-17 17:34:41 +00001364 }
dan7c246102010-04-12 19:00:29 +00001365
drh73b64e42010-05-30 19:55:15 +00001366 if( pInfo->nBackfill<mxSafeFrame
1367 && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
1368 ){
1369 u32 nBackfill = pInfo->nBackfill;
1370
1371 /* Sync the WAL to disk */
1372 if( sync_flags ){
1373 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
1374 }
1375
1376 /* Iterate through the contents of the WAL, copying data to the db file. */
1377 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
1378 if( iFrame<=nBackfill || iFrame>mxSafeFrame ) continue;
1379 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage,
1380 walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE
1381 );
1382 if( rc!=SQLITE_OK ) break;
1383 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, (iDbpage-1)*szPage);
1384 if( rc!=SQLITE_OK ) break;
1385 }
1386
1387 /* If work was actually accomplished... */
1388 if( rc==SQLITE_OK && pInfo->nBackfill<mxSafeFrame ){
1389 pInfo->nBackfill = mxSafeFrame;
1390 if( mxSafeFrame==pHdr[0].mxFrame && sync_flags ){
1391 rc = sqlite3OsTruncate(pWal->pDbFd, ((i64)pWal->hdr.nPage*(i64)szPage));
1392 if( rc==SQLITE_OK && sync_flags ){
1393 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
1394 }
1395 }
1396 }
1397
1398 /* Release the reader lock held while backfilling */
1399 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
dan7c246102010-04-12 19:00:29 +00001400 }
1401
drh7ed91f22010-04-29 22:34:07 +00001402 walIteratorFree(pIter);
dan7c246102010-04-12 19:00:29 +00001403 return rc;
1404}
1405
1406/*
1407** Close a connection to a log file.
1408*/
drhc438efd2010-04-26 00:19:45 +00001409int sqlite3WalClose(
drh7ed91f22010-04-29 22:34:07 +00001410 Wal *pWal, /* Wal to close */
danc5118782010-04-17 17:34:41 +00001411 int sync_flags, /* Flags to pass to OsSync() (or 0) */
danb6e099a2010-05-04 14:47:39 +00001412 int nBuf,
1413 u8 *zBuf /* Buffer of at least nBuf bytes */
dan7c246102010-04-12 19:00:29 +00001414){
1415 int rc = SQLITE_OK;
drh7ed91f22010-04-29 22:34:07 +00001416 if( pWal ){
dan30c86292010-04-30 16:24:46 +00001417 int isDelete = 0; /* True to unlink wal and wal-index files */
1418
1419 /* If an EXCLUSIVE lock can be obtained on the database file (using the
1420 ** ordinary, rollback-mode locking methods, this guarantees that the
1421 ** connection associated with this log file is the only connection to
1422 ** the database. In this case checkpoint the database and unlink both
1423 ** the wal and wal-index files.
1424 **
1425 ** The EXCLUSIVE lock is not released before returning.
1426 */
drhd9e5c4f2010-05-12 18:01:39 +00001427 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
dan30c86292010-04-30 16:24:46 +00001428 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00001429 pWal->exclusiveMode = 1;
1430 rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
dan30c86292010-04-30 16:24:46 +00001431 if( rc==SQLITE_OK ){
1432 isDelete = 1;
1433 }
1434 walIndexUnmap(pWal);
1435 }
1436
dan1018e902010-05-05 15:33:05 +00001437 walIndexClose(pWal, isDelete);
drhd9e5c4f2010-05-12 18:01:39 +00001438 sqlite3OsClose(pWal->pWalFd);
dan30c86292010-04-30 16:24:46 +00001439 if( isDelete ){
drhd9e5c4f2010-05-12 18:01:39 +00001440 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
dan30c86292010-04-30 16:24:46 +00001441 }
drh7ed91f22010-04-29 22:34:07 +00001442 sqlite3_free(pWal);
dan7c246102010-04-12 19:00:29 +00001443 }
1444 return rc;
1445}
1446
1447/*
drha2a42012010-05-18 18:01:08 +00001448** Try to read the wal-index header. Return 0 on success and 1 if
1449** there is a problem.
1450**
1451** The wal-index is in shared memory. Another thread or process might
1452** be writing the header at the same time this procedure is trying to
1453** read it, which might result in inconsistency. A dirty read is detected
drh73b64e42010-05-30 19:55:15 +00001454** by verifying that both copies of the header are the same and also by
1455** a checksum on the header.
drha2a42012010-05-18 18:01:08 +00001456**
1457** If and only if the read is consistent and the header is different from
1458** pWal->hdr, then pWal->hdr is updated to the content of the new header
1459** and *pChanged is set to 1.
danb9bf16b2010-04-14 11:23:30 +00001460**
dan84670502010-05-07 05:46:23 +00001461** If the checksum cannot be verified return non-zero. If the header
1462** is read successfully and the checksum verified, return zero.
danb9bf16b2010-04-14 11:23:30 +00001463*/
dan84670502010-05-07 05:46:23 +00001464int walIndexTryHdr(Wal *pWal, int *pChanged){
drh286a2882010-05-20 23:51:06 +00001465 u32 aCksum[2]; /* Checksum on the header content */
drhf0b20f82010-05-21 13:16:18 +00001466 WalIndexHdr h1, h2; /* Two copies of the header content */
drh286a2882010-05-20 23:51:06 +00001467 WalIndexHdr *aHdr; /* Header in shared memory */
danb9bf16b2010-04-14 11:23:30 +00001468
drh026ac282010-05-26 15:06:38 +00001469 if( pWal->szWIndex < WALINDEX_HDR_SIZE ){
1470 /* The wal-index is not large enough to hold the header, then assume
1471 ** header is invalid. */
dan84670502010-05-07 05:46:23 +00001472 return 1;
drh79e6c782010-04-30 02:13:26 +00001473 }
drh026ac282010-05-26 15:06:38 +00001474 assert( pWal->pWiData );
drh79e6c782010-04-30 02:13:26 +00001475
drh73b64e42010-05-30 19:55:15 +00001476 /* Read the header. This might happen currently with a write to the
1477 ** same area of shared memory on a different CPU in a SMP,
1478 ** meaning it is possible that an inconsistent snapshot is read
dan84670502010-05-07 05:46:23 +00001479 ** from the file. If this happens, return non-zero.
drhf0b20f82010-05-21 13:16:18 +00001480 **
1481 ** There are two copies of the header at the beginning of the wal-index.
1482 ** When reading, read [0] first then [1]. Writes are in the reverse order.
1483 ** Memory barriers are used to prevent the compiler or the hardware from
1484 ** reordering the reads and writes.
danb9bf16b2010-04-14 11:23:30 +00001485 */
drh286a2882010-05-20 23:51:06 +00001486 aHdr = (WalIndexHdr*)pWal->pWiData;
drhf0b20f82010-05-21 13:16:18 +00001487 memcpy(&h1, &aHdr[0], sizeof(h1));
drh286a2882010-05-20 23:51:06 +00001488 sqlite3OsShmBarrier(pWal->pDbFd);
drhf0b20f82010-05-21 13:16:18 +00001489 memcpy(&h2, &aHdr[1], sizeof(h2));
drh286a2882010-05-20 23:51:06 +00001490
drhf0b20f82010-05-21 13:16:18 +00001491 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
1492 return 1; /* Dirty read */
drh286a2882010-05-20 23:51:06 +00001493 }
drhf0b20f82010-05-21 13:16:18 +00001494 if( h1.szPage==0 ){
1495 return 1; /* Malformed header - probably all zeros */
1496 }
danb8fd6c22010-05-24 10:39:36 +00001497 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
drhf0b20f82010-05-21 13:16:18 +00001498 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
1499 return 1; /* Checksum does not match */
danb9bf16b2010-04-14 11:23:30 +00001500 }
1501
drhf0b20f82010-05-21 13:16:18 +00001502 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
dana8614692010-05-06 14:42:34 +00001503 *pChanged = 1;
drhf0b20f82010-05-21 13:16:18 +00001504 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
drh7e263722010-05-20 21:21:09 +00001505 pWal->szPage = pWal->hdr.szPage;
danb9bf16b2010-04-14 11:23:30 +00001506 }
dan84670502010-05-07 05:46:23 +00001507
1508 /* The header was successfully read. Return zero. */
1509 return 0;
danb9bf16b2010-04-14 11:23:30 +00001510}
1511
1512/*
drha2a42012010-05-18 18:01:08 +00001513** Read the wal-index header from the wal-index and into pWal->hdr.
1514** If the wal-header appears to be corrupt, try to recover the log
1515** before returning.
1516**
1517** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
1518** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
1519** to 0.
1520**
1521** This routine also maps the wal-index content into memory and assigns
1522** ownership of that mapping to the current thread. In some implementations,
1523** only one thread at a time can hold a mapping of the wal-index. Hence,
1524** the caller should strive to invoke walIndexUnmap() as soon as possible
1525** after this routine returns.
danb9bf16b2010-04-14 11:23:30 +00001526**
drh7ed91f22010-04-29 22:34:07 +00001527** If the wal-index header is successfully read, return SQLITE_OK.
danb9bf16b2010-04-14 11:23:30 +00001528** Otherwise an SQLite error code.
1529*/
drh7ed91f22010-04-29 22:34:07 +00001530static int walIndexReadHdr(Wal *pWal, int *pChanged){
dan84670502010-05-07 05:46:23 +00001531 int rc; /* Return code */
drh73b64e42010-05-30 19:55:15 +00001532 int badHdr; /* True if a header read failed */
danb9bf16b2010-04-14 11:23:30 +00001533
dana8614692010-05-06 14:42:34 +00001534 assert( pChanged );
drh026ac282010-05-26 15:06:38 +00001535 rc = walIndexMap(pWal, walMappingSize(1));
danc7991bd2010-05-05 19:04:59 +00001536 if( rc!=SQLITE_OK ){
1537 return rc;
1538 }
drh7ed91f22010-04-29 22:34:07 +00001539
drh73b64e42010-05-30 19:55:15 +00001540 /* Try once to read the header straight out. This works most of the
1541 ** time.
danb9bf16b2010-04-14 11:23:30 +00001542 */
drh73b64e42010-05-30 19:55:15 +00001543 badHdr = walIndexTryHdr(pWal, pChanged);
drhbab7b912010-05-26 17:31:58 +00001544
drh73b64e42010-05-30 19:55:15 +00001545 /* If the first attempt failed, it might have been due to a race
1546 ** with a writer. So get a WRITE lock and try again.
1547 */
1548 assert( pWal->writeLock==0 );
1549 if( badHdr ){
1550 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
1551 if( rc==SQLITE_OK ){
1552 pWal->writeLock = 1;
1553 badHdr = walIndexTryHdr(pWal, pChanged);
1554 if( badHdr ){
1555 /* If the wal-index header is still malformed even while holding
1556 ** a WRITE lock, it can only mean that the header is corrupted and
1557 ** needs to be reconstructed. So run recovery to do exactly that.
1558 */
drhbab7b912010-05-26 17:31:58 +00001559 rc = walIndexRecover(pWal);
1560 }
drh73b64e42010-05-30 19:55:15 +00001561 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
1562 pWal->writeLock = 0;
1563 }else if( rc!=SQLITE_BUSY ){
1564 return rc;
drhbab7b912010-05-26 17:31:58 +00001565 }
danb9bf16b2010-04-14 11:23:30 +00001566 }
1567
drhbab7b912010-05-26 17:31:58 +00001568 /* Make sure the mapping is large enough to cover the entire wal-index */
1569 if( rc==SQLITE_OK ){
1570 int szWanted = walMappingSize(pWal->hdr.mxFrame);
1571 if( pWal->szWIndex<szWanted ){
1572 rc = walIndexMap(pWal, szWanted);
dan65be0d82010-05-06 18:48:27 +00001573 }
danb9bf16b2010-04-14 11:23:30 +00001574 }
1575
1576 return rc;
1577}
1578
1579/*
drh73b64e42010-05-30 19:55:15 +00001580** This is the value that walTryBeginRead returns when it needs to
1581** be retried.
dan7c246102010-04-12 19:00:29 +00001582*/
drh73b64e42010-05-30 19:55:15 +00001583#define WAL_RETRY (-1)
dan64d039e2010-04-13 19:27:31 +00001584
drh73b64e42010-05-30 19:55:15 +00001585/*
1586** Attempt to start a read transaction. This might fail due to a race or
1587** other transient condition. When that happens, it returns WAL_RETRY to
1588** indicate to the caller that it is safe to retry immediately.
1589**
1590** On success return SQLITE_OK. On a permantent failure (such an
1591** I/O error or an SQLITE_BUSY because another process is running
1592** recovery) return a positive error code.
1593**
1594** On success, this routine obtains a read lock on
1595** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
1596** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
1597** that means the Wal does not hold any read lock. The reader must not
1598** access any database page that is modified by a WAL frame up to and
1599** including frame number aReadMark[pWal->readLock]. The reader will
1600** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
1601** Or if pWal->readLock==0, then the reader will ignore the WAL
1602** completely and get all content directly from the database file.
1603** When the read transaction is completed, the caller must release the
1604** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
1605**
1606** This routine uses the nBackfill and aReadMark[] fields of the header
1607** to select a particular WAL_READ_LOCK() that strives to let the
1608** checkpoint process do as much work as possible. This routine might
1609** update values of the aReadMark[] array in the header, but if it does
1610** so it takes care to hold an exclusive lock on the corresponding
1611** WAL_READ_LOCK() while changing values.
1612*/
1613static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal){
1614 volatile WalIndexHdr *pHdr; /* Header of the wal-index */
1615 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
1616 u32 mxReadMark; /* Largest aReadMark[] value */
1617 int mxI; /* Index of largest aReadMark[] value */
1618 int i; /* Loop counter */
1619 int rc; /* Return code */
dan64d039e2010-04-13 19:27:31 +00001620
drh73b64e42010-05-30 19:55:15 +00001621 assert( pWal->readLock<0 ); /* No read lock held on entry */
1622
1623 if( !useWal ){
drh7ed91f22010-04-29 22:34:07 +00001624 rc = walIndexReadHdr(pWal, pChanged);
drh73b64e42010-05-30 19:55:15 +00001625 if( rc==SQLITE_BUSY ){
1626 /* If there is not a recovery running in another thread or process
1627 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
1628 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
1629 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
1630 ** would be technically correct. But the race is benign since with
1631 ** WAL_RETRY this routine will be called again and will probably be
1632 ** right on the second iteration.
1633 */
1634 rc = walLockShared(pWal, WAL_RECOVER_LOCK);
1635 if( rc==SQLITE_OK ){
1636 walUnlockShared(pWal, WAL_RECOVER_LOCK);
1637 rc = WAL_RETRY;
1638 }else if( rc==SQLITE_BUSY ){
1639 rc = SQLITE_BUSY_RECOVERY;
1640 }
1641 }
1642 }else{
1643 rc = walIndexMap(pWal, pWal->hdr.mxFrame);
1644 }
1645 if( rc!=SQLITE_OK ){
1646 return rc;
1647 }
1648
1649 pHdr = (volatile WalIndexHdr*)pWal->pWiData;
1650 pInfo = (volatile WalCkptInfo*)&pHdr[2];
1651 assert( pInfo==walCkptInfo(pWal) );
1652 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
1653 /* The WAL has been completely backfilled (or it is empty).
1654 ** and can be safely ignored.
1655 */
1656 rc = walLockShared(pWal, WAL_READ_LOCK(0));
1657 if( rc==SQLITE_OK ){
1658 if( pHdr->mxFrame!=pWal->hdr.mxFrame ){
1659 walUnlockShared(pWal, WAL_READ_LOCK(0));
1660 return WAL_RETRY;
1661 }
1662 pWal->readLock = 0;
1663 return SQLITE_OK;
1664 }else if( rc!=SQLITE_BUSY ){
1665 return rc;
dan64d039e2010-04-13 19:27:31 +00001666 }
dan7c246102010-04-12 19:00:29 +00001667 }
danba515902010-04-30 09:32:06 +00001668
drh73b64e42010-05-30 19:55:15 +00001669 /* If we get this far, it means that the reader will want to use
1670 ** the WAL to get at content from recent commits. The job now is
1671 ** to select one of the aReadMark[] entries that is closest to
1672 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
1673 */
1674 mxReadMark = 0;
1675 mxI = 0;
1676 for(i=1; i<WAL_NREADER; i++){
1677 u32 thisMark = pInfo->aReadMark[i];
1678 if( mxReadMark<thisMark ){
1679 mxReadMark = thisMark;
1680 mxI = i;
1681 }
1682 }
1683 if( mxI==0 ){
1684 /* If we get here, it means that all of the aReadMark[] entries between
1685 ** 1 and WAL_NREADER-1 are zero. Try to initialize aReadMark[1] to
1686 ** be mxFrame, then retry.
1687 */
1688 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
1689 if( rc==SQLITE_OK ){
1690 pInfo->aReadMark[1] = pWal->hdr.mxFrame;
1691 walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
1692 }
1693 return WAL_RETRY;
1694 }else{
1695 if( mxReadMark < pWal->hdr.mxFrame ){
1696 for(i=0; i<WAL_NREADER; i++){
1697 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
1698 if( rc==SQLITE_OK ){
1699 pInfo->aReadMark[i] = pWal->hdr.mxFrame;
1700 mxReadMark = pWal->hdr.mxFrame;
1701 mxI = i;
1702 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
1703 break;
1704 }
1705 }
1706 }
1707
1708 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
1709 if( rc ){
1710 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
1711 }
1712 if( pInfo->aReadMark[mxI]!=mxReadMark
1713 || pHdr[0].mxFrame!=pWal->hdr.mxFrame
1714 || (sqlite3OsShmBarrier(pWal->pDbFd), pHdr[1].mxFrame!=pWal->hdr.mxFrame)
1715 ){
1716 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
1717 return WAL_RETRY;
1718 }else{
1719 pWal->readLock = mxI;
1720 }
1721 }
1722 return rc;
1723}
1724
1725/*
1726** Begin a read transaction on the database.
1727**
1728** This routine used to be called sqlite3OpenSnapshot() and with good reason:
1729** it takes a snapshot of the state of the WAL and wal-index for the current
1730** instant in time. The current thread will continue to use this snapshot.
1731** Other threads might append new content to the WAL and wal-index but
1732** that extra content is ignored by the current thread.
1733**
1734** If the database contents have changes since the previous read
1735** transaction, then *pChanged is set to 1 before returning. The
1736** Pager layer will use this to know that is cache is stale and
1737** needs to be flushed.
1738*/
1739int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
1740 int rc; /* Return code */
1741
1742 do{
1743 rc = walTryBeginRead(pWal, pChanged, 0);
1744 }while( rc==WAL_RETRY );
danba515902010-04-30 09:32:06 +00001745 walIndexUnmap(pWal);
dan7c246102010-04-12 19:00:29 +00001746 return rc;
1747}
1748
1749/*
drh73b64e42010-05-30 19:55:15 +00001750** Finish with a read transaction. All this does is release the
1751** read-lock.
dan7c246102010-04-12 19:00:29 +00001752*/
drh73b64e42010-05-30 19:55:15 +00001753void sqlite3WalEndReadTransaction(Wal *pWal){
1754 if( pWal->readLock>=0 ){
1755 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
1756 pWal->readLock = -1;
1757 }
dan7c246102010-04-12 19:00:29 +00001758}
1759
dan5e0ce872010-04-28 17:48:44 +00001760/*
drh73b64e42010-05-30 19:55:15 +00001761** Read a page from the WAL, if it is present in the WAL and if the
1762** current read transaction is configured to use the WAL.
1763**
1764** The *pInWal is set to 1 if the requested page is in the WAL and
1765** has been loaded. Or *pInWal is set to 0 if the page was not in
1766** the WAL and needs to be read out of the database.
dan7c246102010-04-12 19:00:29 +00001767*/
danb6e099a2010-05-04 14:47:39 +00001768int sqlite3WalRead(
danbb23aff2010-05-10 14:46:09 +00001769 Wal *pWal, /* WAL handle */
1770 Pgno pgno, /* Database page number to read data for */
1771 int *pInWal, /* OUT: True if data is read from WAL */
1772 int nOut, /* Size of buffer pOut in bytes */
1773 u8 *pOut /* Buffer to write page data to */
danb6e099a2010-05-04 14:47:39 +00001774){
danc7991bd2010-05-05 19:04:59 +00001775 int rc; /* Return code */
danbb23aff2010-05-10 14:46:09 +00001776 u32 iRead = 0; /* If !=0, WAL frame to return data from */
drh027a1282010-05-19 01:53:53 +00001777 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
danbb23aff2010-05-10 14:46:09 +00001778 int iHash; /* Used to loop through N hash tables */
dan7c246102010-04-12 19:00:29 +00001779
drh73b64e42010-05-30 19:55:15 +00001780 /* This routine is only called from within a read transaction */
1781 assert( pWal->readLock>=0 );
1782
danbb23aff2010-05-10 14:46:09 +00001783 /* If the "last page" field of the wal-index header snapshot is 0, then
1784 ** no data will be read from the wal under any circumstances. Return early
drh73b64e42010-05-30 19:55:15 +00001785 ** in this case to avoid the walIndexMap/Unmap overhead. Likewise, if
1786 ** pWal->readLock==0, then the WAL is ignored by the reader so
1787 ** return early, as if the WAL were empty.
danbb23aff2010-05-10 14:46:09 +00001788 */
drh73b64e42010-05-30 19:55:15 +00001789 if( iLast==0 || pWal->readLock==0 ){
danbb23aff2010-05-10 14:46:09 +00001790 *pInWal = 0;
1791 return SQLITE_OK;
1792 }
1793
1794 /* Ensure the wal-index is mapped. */
danbb23aff2010-05-10 14:46:09 +00001795 rc = walIndexMap(pWal, walMappingSize(iLast));
danc7991bd2010-05-05 19:04:59 +00001796 if( rc!=SQLITE_OK ){
1797 return rc;
1798 }
dancd11fb22010-04-26 10:40:52 +00001799
danbb23aff2010-05-10 14:46:09 +00001800 /* Search the hash table or tables for an entry matching page number
1801 ** pgno. Each iteration of the following for() loop searches one
1802 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
1803 **
1804 ** This code may run concurrently to the code in walIndexAppend()
1805 ** that adds entries to the wal-index (and possibly to this hash
drh6e810962010-05-19 17:49:50 +00001806 ** table). This means the value just read from the hash
danbb23aff2010-05-10 14:46:09 +00001807 ** slot (aHash[iKey]) may have been added before or after the
1808 ** current read transaction was opened. Values added after the
1809 ** read transaction was opened may have been written incorrectly -
1810 ** i.e. these slots may contain garbage data. However, we assume
1811 ** that any slots written before the current read transaction was
1812 ** opened remain unmodified.
1813 **
1814 ** For the reasons above, the if(...) condition featured in the inner
1815 ** loop of the following block is more stringent that would be required
1816 ** if we had exclusive access to the hash-table:
1817 **
1818 ** (aPgno[iFrame]==pgno):
1819 ** This condition filters out normal hash-table collisions.
1820 **
1821 ** (iFrame<=iLast):
1822 ** This condition filters out entries that were added to the hash
1823 ** table after the current read-transaction had started.
1824 **
1825 ** (iFrame>iRead):
1826 ** This filters out a dangerous class of garbage data. The
1827 ** garbage hash slot may refer to a frame with the correct page
1828 ** number, but not the most recent version of the frame. For
drh6e810962010-05-19 17:49:50 +00001829 ** example, if at the start of the read-transaction the WAL
danbb23aff2010-05-10 14:46:09 +00001830 ** contains three copies of the desired page in frames 2, 3 and 4,
1831 ** the hash table may contain the following:
1832 **
drh6e810962010-05-19 17:49:50 +00001833 ** { ..., 2, 3, 4, 99, 99, ..... }
danbb23aff2010-05-10 14:46:09 +00001834 **
1835 ** The correct answer is to read data from frame 4. But a
1836 ** dirty-read may potentially cause the hash-table to appear as
1837 ** follows to the reader:
1838 **
drh6e810962010-05-19 17:49:50 +00001839 ** { ..., 2, 3, 4, 3, 99, ..... }
danbb23aff2010-05-10 14:46:09 +00001840 **
1841 ** Without this part of the if(...) clause, the reader might
1842 ** incorrectly read data from frame 3 instead of 4. This would be
1843 ** an error.
1844 **
1845 ** It is not actually clear to the developers that such a dirty-read
1846 ** can occur. But if it does, it should not cause any problems.
dan7c246102010-04-12 19:00:29 +00001847 */
danbb23aff2010-05-10 14:46:09 +00001848 for(iHash=iLast; iHash>0 && iRead==0; iHash-=HASHTABLE_NPAGE){
drh5939f442010-05-18 13:27:12 +00001849 volatile HASHTABLE_DATATYPE *aHash; /* Pointer to hash table */
1850 volatile u32 *aPgno; /* Pointer to array of page numbers */
danbb23aff2010-05-10 14:46:09 +00001851 u32 iZero; /* Frame number corresponding to aPgno[0] */
1852 int iKey; /* Hash slot index */
drh29d4dbe2010-05-18 23:29:52 +00001853 int mxHash; /* upper bound on aHash[] values */
danbb23aff2010-05-10 14:46:09 +00001854
1855 walHashFind(pWal, iHash, &aHash, &aPgno, &iZero);
drh29d4dbe2010-05-18 23:29:52 +00001856 mxHash = iLast - iZero;
1857 if( mxHash > HASHTABLE_NPAGE ) mxHash = HASHTABLE_NPAGE;
dan6f150142010-05-21 15:31:56 +00001858 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
danbb23aff2010-05-10 14:46:09 +00001859 u32 iFrame = aHash[iKey] + iZero;
dan6f150142010-05-21 15:31:56 +00001860 if( iFrame<=iLast && aPgno[iFrame]==pgno && iFrame>iRead ){
danbb23aff2010-05-10 14:46:09 +00001861 iRead = iFrame;
1862 }
dan7c246102010-04-12 19:00:29 +00001863 }
1864 }
danbb23aff2010-05-10 14:46:09 +00001865 assert( iRead==0 || pWal->pWiData[walIndexEntry(iRead)]==pgno );
dan7c246102010-04-12 19:00:29 +00001866
danbb23aff2010-05-10 14:46:09 +00001867#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
1868 /* If expensive assert() statements are available, do a linear search
1869 ** of the wal-index file content. Make sure the results agree with the
1870 ** result obtained using the hash indexes above. */
1871 {
1872 u32 iRead2 = 0;
1873 u32 iTest;
1874 for(iTest=iLast; iTest>0; iTest--){
1875 if( pWal->pWiData[walIndexEntry(iTest)]==pgno ){
1876 iRead2 = iTest;
dan7c246102010-04-12 19:00:29 +00001877 break;
1878 }
dan7c246102010-04-12 19:00:29 +00001879 }
danbb23aff2010-05-10 14:46:09 +00001880 assert( iRead==iRead2 );
dan7c246102010-04-12 19:00:29 +00001881 }
danbb23aff2010-05-10 14:46:09 +00001882#endif
dancd11fb22010-04-26 10:40:52 +00001883
dan7c246102010-04-12 19:00:29 +00001884 /* If iRead is non-zero, then it is the log frame number that contains the
1885 ** required page. Read and return data from the log file.
1886 */
danbb23aff2010-05-10 14:46:09 +00001887 walIndexUnmap(pWal);
dan7c246102010-04-12 19:00:29 +00001888 if( iRead ){
drh6e810962010-05-19 17:49:50 +00001889 i64 iOffset = walFrameOffset(iRead, pWal->hdr.szPage) + WAL_FRAME_HDRSIZE;
drh7ed91f22010-04-29 22:34:07 +00001890 *pInWal = 1;
drhd9e5c4f2010-05-12 18:01:39 +00001891 return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
dan7c246102010-04-12 19:00:29 +00001892 }
1893
drh7ed91f22010-04-29 22:34:07 +00001894 *pInWal = 0;
dan7c246102010-04-12 19:00:29 +00001895 return SQLITE_OK;
1896}
1897
1898
1899/*
1900** Set *pPgno to the size of the database file (or zero, if unknown).
1901*/
drh7ed91f22010-04-29 22:34:07 +00001902void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno){
drh73b64e42010-05-30 19:55:15 +00001903 assert( pWal->readLock>=0 );
drh7ed91f22010-04-29 22:34:07 +00001904 *pPgno = pWal->hdr.nPage;
dan7c246102010-04-12 19:00:29 +00001905}
1906
dan30c86292010-04-30 16:24:46 +00001907
drh73b64e42010-05-30 19:55:15 +00001908/*
1909** This function starts a write transaction on the WAL.
1910**
1911** A read transaction must have already been started by a prior call
1912** to sqlite3WalBeginReadTransaction().
1913**
1914** If another thread or process has written into the database since
1915** the read transaction was started, then it is not possible for this
1916** thread to write as doing so would cause a fork. So this routine
1917** returns SQLITE_BUSY in that case and no write transaction is started.
1918**
1919** There can only be a single writer active at a time.
1920*/
1921int sqlite3WalBeginWriteTransaction(Wal *pWal){
1922 int rc;
1923 volatile WalCkptInfo *pInfo;
1924
1925 /* Cannot start a write transaction without first holding a read
1926 ** transaction. */
1927 assert( pWal->readLock>=0 );
1928
1929 /* Only one writer allowed at a time. Get the write lock. Return
1930 ** SQLITE_BUSY if unable.
1931 */
1932 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
1933 if( rc ){
1934 return rc;
1935 }
drhc99597c2010-05-31 01:41:15 +00001936 pWal->writeLock = 1;
drh73b64e42010-05-30 19:55:15 +00001937
1938 /* If another connection has written to the database file since the
1939 ** time the read transaction on this connection was started, then
1940 ** the write is disallowed.
1941 */
1942 rc = walIndexMap(pWal, pWal->hdr.mxFrame);
1943 if( rc ){
1944 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
drhc99597c2010-05-31 01:41:15 +00001945 pWal->writeLock = 0;
drh73b64e42010-05-30 19:55:15 +00001946 return rc;
1947 }
1948 if( memcmp(&pWal->hdr, (void*)pWal->pWiData, sizeof(WalIndexHdr))!=0 ){
1949 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
drhc99597c2010-05-31 01:41:15 +00001950 pWal->writeLock = 0;
drh73b64e42010-05-30 19:55:15 +00001951 walIndexUnmap(pWal);
1952 return SQLITE_BUSY;
1953 }
1954
1955 pInfo = walCkptInfo(pWal);
1956 if( pWal->readLock==0 && pInfo->nBackfill==pWal->hdr.mxFrame ){
1957 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
dan30c86292010-04-30 16:24:46 +00001958 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00001959 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
1960 ** readers are currently using the WAL) */
1961 pWal->nCkpt++;
1962 pWal->hdr.mxFrame = 0;
1963 sqlite3Put4byte((u8*)pWal->hdr.aSalt,
1964 1 + sqlite3Get4byte((u8*)pWal->hdr.aSalt));
1965 sqlite3_randomness(4, &pWal->hdr.aSalt[1]);
1966 walIndexWriteHdr(pWal);
1967 pInfo->nBackfill = 0;
1968 memset(&pInfo->aReadMark[1], 0, sizeof(pInfo->aReadMark)-sizeof(u32));
1969 rc = sqlite3OsTruncate(pWal->pDbFd,
1970 ((i64)pWal->hdr.nPage*(i64)pWal->szPage));
1971 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
dan30c86292010-04-30 16:24:46 +00001972 }
drh73b64e42010-05-30 19:55:15 +00001973 walUnlockShared(pWal, WAL_READ_LOCK(0));
drhc99597c2010-05-31 01:41:15 +00001974 pWal->readLock = -1;
drh73b64e42010-05-30 19:55:15 +00001975 do{
1976 int notUsed;
1977 rc = walTryBeginRead(pWal, &notUsed, 1);
1978 }while( rc==WAL_RETRY );
dan7c246102010-04-12 19:00:29 +00001979 }
drh7ed91f22010-04-29 22:34:07 +00001980 return rc;
dan7c246102010-04-12 19:00:29 +00001981}
1982
dan74d6cd82010-04-24 18:44:05 +00001983/*
drh73b64e42010-05-30 19:55:15 +00001984** End a write transaction. The commit has already been done. This
1985** routine merely releases the lock.
1986*/
1987int sqlite3WalEndWriteTransaction(Wal *pWal){
1988 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
1989 return SQLITE_OK;
1990}
1991
1992/*
dan74d6cd82010-04-24 18:44:05 +00001993** If any data has been written (but not committed) to the log file, this
1994** function moves the write-pointer back to the start of the transaction.
1995**
1996** Additionally, the callback function is invoked for each frame written
drh73b64e42010-05-30 19:55:15 +00001997** to the WAL since the start of the transaction. If the callback returns
dan74d6cd82010-04-24 18:44:05 +00001998** other than SQLITE_OK, it is not invoked again and the error code is
1999** returned to the caller.
2000**
2001** Otherwise, if the callback function does not return an error, this
2002** function returns SQLITE_OK.
2003*/
drh7ed91f22010-04-29 22:34:07 +00002004int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
dan55437592010-05-11 12:19:26 +00002005 int rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00002006 if( pWal->writeLock ){
dan55437592010-05-11 12:19:26 +00002007 int unused;
drh027a1282010-05-19 01:53:53 +00002008 Pgno iMax = pWal->hdr.mxFrame;
dan55437592010-05-11 12:19:26 +00002009 Pgno iFrame;
2010
2011 assert( pWal->pWiData==0 );
2012 rc = walIndexReadHdr(pWal, &unused);
dan6f150142010-05-21 15:31:56 +00002013 if( rc==SQLITE_OK ){
drhbab7b912010-05-26 17:31:58 +00002014 rc = walIndexMap(pWal, walMappingSize(iMax));
2015 }
2016 if( rc==SQLITE_OK ){
drh4fa95bf2010-05-22 00:55:39 +00002017 for(iFrame=pWal->hdr.mxFrame+1; rc==SQLITE_OK && iFrame<=iMax; iFrame++){
drh73b64e42010-05-30 19:55:15 +00002018 assert( pWal->writeLock );
drh4fa95bf2010-05-22 00:55:39 +00002019 rc = xUndo(pUndoCtx, pWal->pWiData[walIndexEntry(iFrame)]);
2020 }
danca6b5ba2010-05-25 10:50:56 +00002021 walCleanupHash(pWal);
dan6f150142010-05-21 15:31:56 +00002022 }
dan55437592010-05-11 12:19:26 +00002023 walIndexUnmap(pWal);
dan74d6cd82010-04-24 18:44:05 +00002024 }
2025 return rc;
2026}
2027
dan71d89912010-05-24 13:57:42 +00002028/*
2029** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
2030** values. This function populates the array with values required to
2031** "rollback" the write position of the WAL handle back to the current
2032** point in the event of a savepoint rollback (via WalSavepointUndo()).
drh7ed91f22010-04-29 22:34:07 +00002033*/
dan71d89912010-05-24 13:57:42 +00002034void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
drh73b64e42010-05-30 19:55:15 +00002035 assert( pWal->writeLock );
dan71d89912010-05-24 13:57:42 +00002036 aWalData[0] = pWal->hdr.mxFrame;
2037 aWalData[1] = pWal->hdr.aFrameCksum[0];
2038 aWalData[2] = pWal->hdr.aFrameCksum[1];
dan4cd78b42010-04-26 16:57:10 +00002039}
2040
dan71d89912010-05-24 13:57:42 +00002041/*
2042** Move the write position of the WAL back to the point identified by
2043** the values in the aWalData[] array. aWalData must point to an array
2044** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
2045** by a call to WalSavepoint().
drh7ed91f22010-04-29 22:34:07 +00002046*/
dan71d89912010-05-24 13:57:42 +00002047int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
dan4cd78b42010-04-26 16:57:10 +00002048 int rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00002049 assert( pWal->writeLock );
dan4cd78b42010-04-26 16:57:10 +00002050
dan71d89912010-05-24 13:57:42 +00002051 assert( aWalData[0]<=pWal->hdr.mxFrame );
2052 if( aWalData[0]<pWal->hdr.mxFrame ){
drh4fa95bf2010-05-22 00:55:39 +00002053 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
dan71d89912010-05-24 13:57:42 +00002054 pWal->hdr.mxFrame = aWalData[0];
2055 pWal->hdr.aFrameCksum[0] = aWalData[1];
2056 pWal->hdr.aFrameCksum[1] = aWalData[2];
drh4fa95bf2010-05-22 00:55:39 +00002057 if( rc==SQLITE_OK ){
2058 walCleanupHash(pWal);
2059 walIndexUnmap(pWal);
2060 }
dan6f150142010-05-21 15:31:56 +00002061 }
dan4cd78b42010-04-26 16:57:10 +00002062 return rc;
2063}
2064
dan7c246102010-04-12 19:00:29 +00002065/*
dan4cd78b42010-04-26 16:57:10 +00002066** Write a set of frames to the log. The caller must hold the write-lock
2067** on the log file (obtained using sqlite3WalWriteLock()).
dan7c246102010-04-12 19:00:29 +00002068*/
drhc438efd2010-04-26 00:19:45 +00002069int sqlite3WalFrames(
drh7ed91f22010-04-29 22:34:07 +00002070 Wal *pWal, /* Wal handle to write to */
drh6e810962010-05-19 17:49:50 +00002071 int szPage, /* Database page-size in bytes */
dan7c246102010-04-12 19:00:29 +00002072 PgHdr *pList, /* List of dirty pages to write */
2073 Pgno nTruncate, /* Database size after this commit */
2074 int isCommit, /* True if this is a commit */
danc5118782010-04-17 17:34:41 +00002075 int sync_flags /* Flags to pass to OsSync() (or 0) */
dan7c246102010-04-12 19:00:29 +00002076){
dan7c246102010-04-12 19:00:29 +00002077 int rc; /* Used to catch return codes */
2078 u32 iFrame; /* Next frame address */
drh7ed91f22010-04-29 22:34:07 +00002079 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
dan7c246102010-04-12 19:00:29 +00002080 PgHdr *p; /* Iterator to run through pList with. */
drhe874d9e2010-05-07 20:02:23 +00002081 PgHdr *pLast = 0; /* Last frame in list */
dan7c246102010-04-12 19:00:29 +00002082 int nLast = 0; /* Number of extra copies of last page */
2083
dan7c246102010-04-12 19:00:29 +00002084 assert( pList );
drh73b64e42010-05-30 19:55:15 +00002085 assert( pWal->writeLock );
danba515902010-04-30 09:32:06 +00002086 assert( pWal->pWiData==0 );
dan7c246102010-04-12 19:00:29 +00002087
drha2a42012010-05-18 18:01:08 +00002088 /* If this is the first frame written into the log, write the WAL
2089 ** header to the start of the WAL file. See comments at the top of
2090 ** this source file for a description of the WAL header format.
dan97a31352010-04-16 13:59:31 +00002091 */
drh027a1282010-05-19 01:53:53 +00002092 iFrame = pWal->hdr.mxFrame;
dan97a31352010-04-16 13:59:31 +00002093 if( iFrame==0 ){
drh23ea97b2010-05-20 16:45:58 +00002094 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assembly wal-header in */
danb8fd6c22010-05-24 10:39:36 +00002095 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
drh23ea97b2010-05-20 16:45:58 +00002096 sqlite3Put4byte(&aWalHdr[4], 3007000);
2097 sqlite3Put4byte(&aWalHdr[8], szPage);
drh7e263722010-05-20 21:21:09 +00002098 pWal->szPage = szPage;
danb8fd6c22010-05-24 10:39:36 +00002099 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
drh23ea97b2010-05-20 16:45:58 +00002100 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
drh7e263722010-05-20 21:21:09 +00002101 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
drh23ea97b2010-05-20 16:45:58 +00002102 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
dan97a31352010-04-16 13:59:31 +00002103 if( rc!=SQLITE_OK ){
2104 return rc;
2105 }
dan71d89912010-05-24 13:57:42 +00002106 walChecksumBytes(1, aWalHdr, sizeof(aWalHdr), 0, pWal->hdr.aFrameCksum);
dan97a31352010-04-16 13:59:31 +00002107 }
drh7e263722010-05-20 21:21:09 +00002108 assert( pWal->szPage==szPage );
dan97a31352010-04-16 13:59:31 +00002109
drh7e263722010-05-20 21:21:09 +00002110 /* Write the log file. */
dan7c246102010-04-12 19:00:29 +00002111 for(p=pList; p; p=p->pDirty){
2112 u32 nDbsize; /* Db-size field for frame header */
2113 i64 iOffset; /* Write offset in log file */
2114
drh6e810962010-05-19 17:49:50 +00002115 iOffset = walFrameOffset(++iFrame, szPage);
dan7c246102010-04-12 19:00:29 +00002116
2117 /* Populate and write the frame header */
2118 nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
drh7e263722010-05-20 21:21:09 +00002119 walEncodeFrame(pWal, p->pgno, nDbsize, p->pData, aFrame);
drhd9e5c4f2010-05-12 18:01:39 +00002120 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
dan7c246102010-04-12 19:00:29 +00002121 if( rc!=SQLITE_OK ){
2122 return rc;
2123 }
2124
2125 /* Write the page data */
drh6e810962010-05-19 17:49:50 +00002126 rc = sqlite3OsWrite(pWal->pWalFd, p->pData, szPage, iOffset+sizeof(aFrame));
dan7c246102010-04-12 19:00:29 +00002127 if( rc!=SQLITE_OK ){
2128 return rc;
2129 }
2130 pLast = p;
2131 }
2132
2133 /* Sync the log file if the 'isSync' flag was specified. */
danc5118782010-04-17 17:34:41 +00002134 if( sync_flags ){
drhd9e5c4f2010-05-12 18:01:39 +00002135 i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
drh6e810962010-05-19 17:49:50 +00002136 i64 iOffset = walFrameOffset(iFrame+1, szPage);
dan67032392010-04-17 15:42:43 +00002137
2138 assert( isCommit );
drh69c46962010-05-17 20:16:50 +00002139 assert( iSegment>0 );
dan7c246102010-04-12 19:00:29 +00002140
dan7c246102010-04-12 19:00:29 +00002141 iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
2142 while( iOffset<iSegment ){
drh7e263722010-05-20 21:21:09 +00002143 walEncodeFrame(pWal, pLast->pgno, nTruncate, pLast->pData, aFrame);
drhd9e5c4f2010-05-12 18:01:39 +00002144 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
dan7c246102010-04-12 19:00:29 +00002145 if( rc!=SQLITE_OK ){
2146 return rc;
2147 }
2148
drh7ed91f22010-04-29 22:34:07 +00002149 iOffset += WAL_FRAME_HDRSIZE;
drh6e810962010-05-19 17:49:50 +00002150 rc = sqlite3OsWrite(pWal->pWalFd, pLast->pData, szPage, iOffset);
dan7c246102010-04-12 19:00:29 +00002151 if( rc!=SQLITE_OK ){
2152 return rc;
2153 }
2154 nLast++;
drh6e810962010-05-19 17:49:50 +00002155 iOffset += szPage;
dan7c246102010-04-12 19:00:29 +00002156 }
dan7c246102010-04-12 19:00:29 +00002157
drhd9e5c4f2010-05-12 18:01:39 +00002158 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
dan7c246102010-04-12 19:00:29 +00002159 }
danba515902010-04-30 09:32:06 +00002160 assert( pWal->pWiData==0 );
dan7c246102010-04-12 19:00:29 +00002161
drhe730fec2010-05-18 12:56:50 +00002162 /* Append data to the wal-index. It is not necessary to lock the
drha2a42012010-05-18 18:01:08 +00002163 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
dan7c246102010-04-12 19:00:29 +00002164 ** guarantees that there are no other writers, and no data that may
2165 ** be in use by existing readers is being overwritten.
2166 */
drh027a1282010-05-19 01:53:53 +00002167 iFrame = pWal->hdr.mxFrame;
danc7991bd2010-05-05 19:04:59 +00002168 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
dan7c246102010-04-12 19:00:29 +00002169 iFrame++;
danc7991bd2010-05-05 19:04:59 +00002170 rc = walIndexAppend(pWal, iFrame, p->pgno);
dan7c246102010-04-12 19:00:29 +00002171 }
danc7991bd2010-05-05 19:04:59 +00002172 while( nLast>0 && rc==SQLITE_OK ){
dan7c246102010-04-12 19:00:29 +00002173 iFrame++;
2174 nLast--;
danc7991bd2010-05-05 19:04:59 +00002175 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
dan7c246102010-04-12 19:00:29 +00002176 }
2177
danc7991bd2010-05-05 19:04:59 +00002178 if( rc==SQLITE_OK ){
2179 /* Update the private copy of the header. */
drh6e810962010-05-19 17:49:50 +00002180 pWal->hdr.szPage = szPage;
drh027a1282010-05-19 01:53:53 +00002181 pWal->hdr.mxFrame = iFrame;
danc7991bd2010-05-05 19:04:59 +00002182 if( isCommit ){
2183 pWal->hdr.iChange++;
2184 pWal->hdr.nPage = nTruncate;
2185 }
danc7991bd2010-05-05 19:04:59 +00002186 /* If this is a commit, update the wal-index header too. */
2187 if( isCommit ){
drh7e263722010-05-20 21:21:09 +00002188 walIndexWriteHdr(pWal);
danc7991bd2010-05-05 19:04:59 +00002189 pWal->iCallback = iFrame;
2190 }
dan7c246102010-04-12 19:00:29 +00002191 }
danc7991bd2010-05-05 19:04:59 +00002192
drh7ed91f22010-04-29 22:34:07 +00002193 walIndexUnmap(pWal);
dan8d22a172010-04-19 18:03:51 +00002194 return rc;
dan7c246102010-04-12 19:00:29 +00002195}
2196
2197/*
drh73b64e42010-05-30 19:55:15 +00002198** This routine is called to implement sqlite3_wal_checkpoint() and
2199** related interfaces.
danb9bf16b2010-04-14 11:23:30 +00002200**
drh73b64e42010-05-30 19:55:15 +00002201** Obtain a CHECKPOINT lock and then backfill as much information as
2202** we can from WAL into the database.
dan7c246102010-04-12 19:00:29 +00002203*/
drhc438efd2010-04-26 00:19:45 +00002204int sqlite3WalCheckpoint(
drh7ed91f22010-04-29 22:34:07 +00002205 Wal *pWal, /* Wal connection */
danc5118782010-04-17 17:34:41 +00002206 int sync_flags, /* Flags to sync db file with (or 0) */
danb6e099a2010-05-04 14:47:39 +00002207 int nBuf, /* Size of temporary buffer */
drh73b64e42010-05-30 19:55:15 +00002208 u8 *zBuf /* Temporary buffer to use */
dan7c246102010-04-12 19:00:29 +00002209){
danb9bf16b2010-04-14 11:23:30 +00002210 int rc; /* Return code */
dan31c03902010-04-29 14:51:33 +00002211 int isChanged = 0; /* True if a new wal-index header is loaded */
dan7c246102010-04-12 19:00:29 +00002212
dan5cf53532010-05-01 16:40:20 +00002213 assert( pWal->pWiData==0 );
dan39c79f52010-04-15 10:58:51 +00002214
drh73b64e42010-05-30 19:55:15 +00002215 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
2216 if( rc ){
2217 /* Usually this is SQLITE_BUSY meaning that another thread or process
2218 ** is already running a checkpoint, or maybe a recovery. But it might
2219 ** also be SQLITE_IOERR. */
danb9bf16b2010-04-14 11:23:30 +00002220 return rc;
2221 }
dan64d039e2010-04-13 19:27:31 +00002222
danb9bf16b2010-04-14 11:23:30 +00002223 /* Copy data from the log to the database file. */
drh7ed91f22010-04-29 22:34:07 +00002224 rc = walIndexReadHdr(pWal, &isChanged);
danb9bf16b2010-04-14 11:23:30 +00002225 if( rc==SQLITE_OK ){
drhd9e5c4f2010-05-12 18:01:39 +00002226 rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
danb9bf16b2010-04-14 11:23:30 +00002227 }
dan31c03902010-04-29 14:51:33 +00002228 if( isChanged ){
2229 /* If a new wal-index header was loaded before the checkpoint was
drha2a42012010-05-18 18:01:08 +00002230 ** performed, then the pager-cache associated with pWal is now
dan31c03902010-04-29 14:51:33 +00002231 ** out of date. So zero the cached wal-index header to ensure that
2232 ** next time the pager opens a snapshot on this database it knows that
2233 ** the cache needs to be reset.
2234 */
drh7ed91f22010-04-29 22:34:07 +00002235 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
dan31c03902010-04-29 14:51:33 +00002236 }
danb9bf16b2010-04-14 11:23:30 +00002237
2238 /* Release the locks. */
dan87bfb512010-04-30 11:43:28 +00002239 walIndexUnmap(pWal);
drh73b64e42010-05-30 19:55:15 +00002240 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
dan64d039e2010-04-13 19:27:31 +00002241 return rc;
dan7c246102010-04-12 19:00:29 +00002242}
2243
drh7ed91f22010-04-29 22:34:07 +00002244/* Return the value to pass to a sqlite3_wal_hook callback, the
2245** number of frames in the WAL at the point of the last commit since
2246** sqlite3WalCallback() was called. If no commits have occurred since
2247** the last call, then return 0.
2248*/
2249int sqlite3WalCallback(Wal *pWal){
dan8d22a172010-04-19 18:03:51 +00002250 u32 ret = 0;
drh7ed91f22010-04-29 22:34:07 +00002251 if( pWal ){
2252 ret = pWal->iCallback;
2253 pWal->iCallback = 0;
dan8d22a172010-04-19 18:03:51 +00002254 }
2255 return (int)ret;
2256}
dan55437592010-05-11 12:19:26 +00002257
2258/*
2259** This function is called to set or query the exclusive-mode flag
2260** associated with the WAL connection passed as the first argument. The
2261** exclusive-mode flag should be set to indicate that the caller is
2262** holding an EXCLUSIVE lock on the database file (it does this in
2263** locking_mode=exclusive mode). If the EXCLUSIVE lock is to be dropped,
2264** the flag set by this function should be cleared before doing so.
2265**
dan55437592010-05-11 12:19:26 +00002266** When the flag is set, this module does not call the VFS xShmLock()
2267** method to obtain any locks on the wal-index (as it assumes it
2268** has exclusive access to the wal and wal-index files anyhow). It
2269** continues to hold (and does not drop) the existing READ lock on
2270** the wal-index.
2271**
2272** To set or clear the flag, the "op" parameter is passed 1 or 0,
2273** respectively. To query the flag, pass -1. In all cases, the value
2274** returned is the value of the exclusive-mode flag (after its value
2275** has been modified, if applicable).
2276*/
2277int sqlite3WalExclusiveMode(Wal *pWal, int op){
2278 if( op>=0 ){
dan55437592010-05-11 12:19:26 +00002279 pWal->exclusiveMode = (u8)op;
2280 }
2281 return pWal->exclusiveMode;
2282}
2283
dan5cf53532010-05-01 16:40:20 +00002284#endif /* #ifndef SQLITE_OMIT_WAL */