blob: 3de43ddc6ed02277929ae6aa2638a42be681fc87 [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**
drh7ed91f22010-04-29 22:34:07 +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**
34** The WAL header is 12 bytes in size and consists of the following three
dan97a31352010-04-16 13:59:31 +000035** big-endian 32-bit unsigned integer values:
36**
dan3de777f2010-04-17 12:31:37 +000037** 0: Database page size,
38** 4: Randomly selected salt value 1,
39** 8: Randomly selected salt value 2.
dan97a31352010-04-16 13:59:31 +000040**
drh7ed91f22010-04-29 22:34:07 +000041** Immediately following the header are zero or more frames. Each
drh027a1282010-05-19 01:53:53 +000042** frame consists of a 16-byte header followed by a <page-size> bytes
dan97a31352010-04-16 13:59:31 +000043** of page data. The header is broken into 4 big-endian 32-bit unsigned
44** integer values, as follows:
45**
dan3de777f2010-04-17 12:31:37 +000046** 0: Page number.
47** 4: For commit records, the size of the database image in pages
dan97a31352010-04-16 13:59:31 +000048** after the commit. For all other records, zero.
dan3de777f2010-04-17 12:31:37 +000049** 8: Checksum value 1.
dan97a31352010-04-16 13:59:31 +000050** 12: Checksum value 2.
drh29d4dbe2010-05-18 23:29:52 +000051**
52** READER ALGORITHM
53**
54** To read a page from the database (call it page number P), a reader
55** first checks the WAL to see if it contains page P. If so, then the
56** last valid instance of page P that is or is followed by a commit frame
57** become the value read. If the WAL contains no copies of page P that
58** are valid and which are or are followed by a commit frame, then page
59** P is read from the database file.
60**
61** The reader algorithm in the previous paragraph works correctly, but
62** because frames for page P can appear anywhere within the WAL, the
drh027a1282010-05-19 01:53:53 +000063** reader has to scan the entire WAL looking for page P frames. If the
drh29d4dbe2010-05-18 23:29:52 +000064** WAL is large (multiple megabytes is typical) that scan can be slow,
drh027a1282010-05-19 01:53:53 +000065** and read performance suffers. To overcome this problem, a separate
66** data structure called the wal-index is maintained to expedite the
drh29d4dbe2010-05-18 23:29:52 +000067** search for frames of a particular page.
68**
69** WAL-INDEX FORMAT
70**
71** Conceptually, the wal-index is shared memory, though VFS implementations
72** might choose to implement the wal-index using a mmapped file. Because
73** the wal-index is shared memory, SQLite does not support journal_mode=WAL
74** on a network filesystem. All users of the database must be able to
75** share memory.
76**
77** The wal-index is transient. After a crash, the wal-index can (and should
78** be) reconstructed from the original WAL file. In fact, the VFS is required
79** to either truncate or zero the header of the wal-index when the last
80** connection to it closes. Because the wal-index is transient, it can
81** use an architecture-specific format; it does not have to be cross-platform.
82** Hence, unlike the database and WAL file formats which store all values
83** as big endian, the wal-index can store multi-byte values in the native
84** byte order of the host computer.
85**
86** The purpose of the wal-index is to answer this question quickly: Given
87** a page number P, return the index of the last frame for page P in the WAL,
88** or return NULL if there are no frames for page P in the WAL.
89**
90** The wal-index consists of a header region, followed by an one or
91** more index blocks.
92**
drh027a1282010-05-19 01:53:53 +000093** The wal-index header contains the total number of frames within the WAL
94** in the the mxFrame field. Each index block contains information on
95** HASHTABLE_NPAGE frames. Each index block contains two sections, a
96** mapping which is a database page number for each frame, and a hash
97** table used to look up frames by page number. The mapping section is
98** an array of HASHTABLE_NPAGE 32-bit page numbers. The first entry on the
99** array is the page number for the first frame; the second entry is the
100** page number for the second frame; and so forth. The last index block
101** holds a total of (mxFrame%HASHTABLE_NPAGE) page numbers. All index
102** blocks other than the last are completely full with HASHTABLE_NPAGE
103** page numbers. All index blocks are the same size; the mapping section
104** of the last index block merely contains unused entries if mxFrame is
105** not an even multiple of HASHTABLE_NPAGE.
106**
107** Even without using the hash table, the last frame for page P
108** can be found by scanning the mapping sections of each index block
109** starting with the last index block and moving toward the first, and
110** within each index block, starting at the end and moving toward the
111** beginning. The first entry that equals P corresponds to the frame
112** holding the content for that page.
113**
114** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
115** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
116** hash table for each page number in the mapping section, so the hash
117** table is never more than half full. The expected number of collisions
118** prior to finding a match is 1. Each entry of the hash table is an
119** 1-based index of an entry in the mapping section of the same
120** index block. Let K be the 1-based index of the largest entry in
121** the mapping section. (For index blocks other than the last, K will
122** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
123** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
124** contain a value greater than K. Note that no hash table slot ever
125** contains a zero value.
126**
127** To look for page P in the hash table, first compute a hash iKey on
128** P as follows:
129**
130** iKey = (P * 383) % HASHTABLE_NSLOT
131**
132** Then start scanning entries of the hash table, starting with iKey
133** (wrapping around to the beginning when the end of the hash table is
134** reached) until an unused hash slot is found. Let the first unused slot
135** be at index iUnused. (iUnused might be less than iKey if there was
136** wrap-around.) Because the hash table is never more than half full,
137** the search is guaranteed to eventually hit an unused entry. Let
138** iMax be the value between iKey and iUnused, closest to iUnused,
139** where aHash[iMax]==P. If there is no iMax entry (if there exists
140** no hash slot such that aHash[i]==p) then page P is not in the
141** current index block. Otherwise the iMax-th mapping entry of the
142** current index block corresponds to the last entry that references
143** page P.
144**
145** A hash search begins with the last index block and moves toward the
146** first index block, looking for entries corresponding to page P. On
147** average, only two or three slots in each index block need to be
148** examined in order to either find the last entry for page P, or to
149** establish that no such entry exists in the block. Each index block
150** holds over 4000 entries. So two or three index blocks are sufficient
151** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
152** comparisons (on average) suffice to either locate a frame in the
153** WAL or to establish that the frame does not exist in the WAL. This
154** is much faster than scanning the entire 10MB WAL.
155**
156** Note that entries are added in order of increasing K. Hence, one
157** reader might be using some value K0 and a second reader that started
158** at a later time (after additional transactions were added to the WAL
159** and to the wal-index) might be using a different value K1, where K1>K0.
160** Both readers can use the same hash table and mapping section to get
161** the correct result. There may be entries in the hash table with
162** K>K0 but to the first reader, those entries will appear to be unused
163** slots in the hash table and so the first reader will get an answer as
164** if no values greater than K0 had ever been inserted into the hash table
165** in the first place - which is what reader one wants. Meanwhile, the
166** second reader using K1 will see additional values that were inserted
167** later, which is exactly what reader two wants.
168**
169** When a rollback occurs, the value of K is decreased. This has the
170** effect of automatically removing entries from the hash table.
dan97a31352010-04-16 13:59:31 +0000171*/
drh29d4dbe2010-05-18 23:29:52 +0000172#ifndef SQLITE_OMIT_WAL
dan97a31352010-04-16 13:59:31 +0000173
drh29d4dbe2010-05-18 23:29:52 +0000174#include "wal.h"
175
dan97a31352010-04-16 13:59:31 +0000176
drh7ed91f22010-04-29 22:34:07 +0000177/* Object declarations */
178typedef struct WalIndexHdr WalIndexHdr;
179typedef struct WalIterator WalIterator;
dan7c246102010-04-12 19:00:29 +0000180
181
182/*
drh7ed91f22010-04-29 22:34:07 +0000183** The following object stores a copy of the wal-index header.
dan7c246102010-04-12 19:00:29 +0000184**
185** Member variables iCheck1 and iCheck2 contain the checksum for the
drh7ed91f22010-04-29 22:34:07 +0000186** last frame written to the wal, or 2 and 3 respectively if the log
dan7c246102010-04-12 19:00:29 +0000187** is currently empty.
188*/
drh7ed91f22010-04-29 22:34:07 +0000189struct WalIndexHdr {
dan7c246102010-04-12 19:00:29 +0000190 u32 iChange; /* Counter incremented each transaction */
191 u32 pgsz; /* Database page size in bytes */
drh027a1282010-05-19 01:53:53 +0000192 u32 mxFrame; /* Index of last valid frame in the WAL */
dan7c246102010-04-12 19:00:29 +0000193 u32 nPage; /* Size of database in pages */
194 u32 iCheck1; /* Checkpoint value 1 */
195 u32 iCheck2; /* Checkpoint value 2 */
196};
197
drh7ed91f22010-04-29 22:34:07 +0000198/* Size of serialized WalIndexHdr object. */
199#define WALINDEX_HDR_NFIELD (sizeof(WalIndexHdr) / sizeof(u32))
dan7c246102010-04-12 19:00:29 +0000200
drh7ed91f22010-04-29 22:34:07 +0000201/* A block of 16 bytes beginning at WALINDEX_LOCK_OFFSET is reserved
danff207012010-04-24 04:49:15 +0000202** for locks. Since some systems only feature mandatory file-locks, we
203** do not read or write data from the region of the file on which locks
204** are applied.
205*/
drh7ed91f22010-04-29 22:34:07 +0000206#define WALINDEX_LOCK_OFFSET ((sizeof(WalIndexHdr))+2*sizeof(u32))
207#define WALINDEX_LOCK_RESERVED 8
dan7c246102010-04-12 19:00:29 +0000208
drh7ed91f22010-04-29 22:34:07 +0000209/* Size of header before each frame in wal */
210#define WAL_FRAME_HDRSIZE 16
danff207012010-04-24 04:49:15 +0000211
drh7ed91f22010-04-29 22:34:07 +0000212/* Size of write ahead log header */
213#define WAL_HDRSIZE 12
dan97a31352010-04-16 13:59:31 +0000214
215/*
drh7ed91f22010-04-29 22:34:07 +0000216** Return the offset of frame iFrame in the write-ahead log file,
217** assuming a database page size of pgsz bytes. The offset returned
218** is to the start of the write-ahead log frame-header.
dan97a31352010-04-16 13:59:31 +0000219*/
drh7ed91f22010-04-29 22:34:07 +0000220#define walFrameOffset(iFrame, pgsz) ( \
221 WAL_HDRSIZE + ((iFrame)-1)*((pgsz)+WAL_FRAME_HDRSIZE) \
dan97a31352010-04-16 13:59:31 +0000222)
dan7c246102010-04-12 19:00:29 +0000223
224/*
drh7ed91f22010-04-29 22:34:07 +0000225** An open write-ahead log file is represented by an instance of the
226** following object.
dance4f05f2010-04-22 19:14:13 +0000227*/
drh7ed91f22010-04-29 22:34:07 +0000228struct Wal {
229 sqlite3_vfs *pVfs; /* The VFS used to create pFd */
drhd9e5c4f2010-05-12 18:01:39 +0000230 sqlite3_file *pDbFd; /* File handle for the database file */
231 sqlite3_file *pWalFd; /* File handle for WAL file */
drh7ed91f22010-04-29 22:34:07 +0000232 u32 iCallback; /* Value to pass to log callback (or 0) */
drh5530b762010-04-30 14:39:50 +0000233 int szWIndex; /* Size of the wal-index that is mapped in mem */
drh5939f442010-05-18 13:27:12 +0000234 volatile u32 *pWiData; /* Pointer to wal-index content in memory */
drh7ed91f22010-04-29 22:34:07 +0000235 u8 lockState; /* SQLITE_SHM_xxxx constant showing lock state */
236 u8 readerType; /* SQLITE_SHM_READ or SQLITE_SHM_READ_FULL */
dan55437592010-05-11 12:19:26 +0000237 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
drhd9e5c4f2010-05-12 18:01:39 +0000238 u8 isWindexOpen; /* True if ShmOpen() called on pDbFd */
drh7ed91f22010-04-29 22:34:07 +0000239 WalIndexHdr hdr; /* Wal-index for current snapshot */
drhd9e5c4f2010-05-12 18:01:39 +0000240 char *zWalName; /* Name of WAL file */
dan7c246102010-04-12 19:00:29 +0000241};
242
dan64d039e2010-04-13 19:27:31 +0000243
dan7c246102010-04-12 19:00:29 +0000244/*
drha2a42012010-05-18 18:01:08 +0000245** This structure is used to implement an iterator that loops through
246** all frames in the WAL in database page order. Where two or more frames
dan7c246102010-04-12 19:00:29 +0000247** correspond to the same database page, the iterator visits only the
drha2a42012010-05-18 18:01:08 +0000248** frame most recently written to the WAL (in other words, the frame with
249** the largest index).
dan7c246102010-04-12 19:00:29 +0000250**
251** The internals of this structure are only accessed by:
252**
drh7ed91f22010-04-29 22:34:07 +0000253** walIteratorInit() - Create a new iterator,
254** walIteratorNext() - Step an iterator,
255** walIteratorFree() - Free an iterator.
dan7c246102010-04-12 19:00:29 +0000256**
drh7ed91f22010-04-29 22:34:07 +0000257** This functionality is used by the checkpoint code (see walCheckpoint()).
dan7c246102010-04-12 19:00:29 +0000258*/
drh7ed91f22010-04-29 22:34:07 +0000259struct WalIterator {
drha2a42012010-05-18 18:01:08 +0000260 int iPrior; /* Last result returned from the iterator */
261 int nSegment; /* Size of the aSegment[] array */
262 int nFinal; /* Elements in aSegment[nSegment-1] */
drh7ed91f22010-04-29 22:34:07 +0000263 struct WalSegment {
drha2a42012010-05-18 18:01:08 +0000264 int iNext; /* Next slot in aIndex[] not previously returned */
265 u8 *aIndex; /* i0, i1, i2... such that aPgno[iN] ascending */
266 u32 *aPgno; /* 256 page numbers. Pointer to Wal.pWiData */
267 } aSegment[1]; /* One for every 256 entries in the WAL */
dan7c246102010-04-12 19:00:29 +0000268};
269
dan64d039e2010-04-13 19:27:31 +0000270
dan7c246102010-04-12 19:00:29 +0000271/*
272** Generate an 8 byte checksum based on the data in array aByte[] and the
273** initial values of aCksum[0] and aCksum[1]. The checksum is written into
274** aCksum[] before returning.
dan56d95912010-04-24 19:07:29 +0000275**
276** The range of bytes to checksum is treated as an array of 32-bit
277** little-endian unsigned integers. For each integer X in the array, from
278** start to finish, do the following:
279**
280** aCksum[0] += X;
281** aCksum[1] += aCksum[0];
282**
283** For the calculation above, use 64-bit unsigned accumulators. Before
284** returning, truncate the values to 32-bits as follows:
285**
286** aCksum[0] = (u32)(aCksum[0] + (aCksum[0]>>24));
287** aCksum[1] = (u32)(aCksum[1] + (aCksum[1]>>24));
dan7c246102010-04-12 19:00:29 +0000288*/
drh7ed91f22010-04-29 22:34:07 +0000289static void walChecksumBytes(u8 *aByte, int nByte, u32 *aCksum){
dan39c79f52010-04-15 10:58:51 +0000290 u64 sum1 = aCksum[0];
291 u64 sum2 = aCksum[1];
292 u32 *a32 = (u32 *)aByte;
293 u32 *aEnd = (u32 *)&aByte[nByte];
dan7c246102010-04-12 19:00:29 +0000294
dan7c246102010-04-12 19:00:29 +0000295 assert( (nByte&0x00000003)==0 );
296
dance4f05f2010-04-22 19:14:13 +0000297 if( SQLITE_LITTLEENDIAN ){
298#ifdef SQLITE_DEBUG
299 u8 *a = (u8 *)a32;
300 assert( *a32==(a[0] + (a[1]<<8) + (a[2]<<16) + (a[3]<<24)) );
301#endif
302 do {
303 sum1 += *a32;
304 sum2 += sum1;
305 } while( ++a32<aEnd );
306 }else{
307 do {
308 u8 *a = (u8*)a32;
309 sum1 += a[0] + (a[1]<<8) + (a[2]<<16) + (a[3]<<24);
310 sum2 += sum1;
311 } while( ++a32<aEnd );
312 }
dan7c246102010-04-12 19:00:29 +0000313
dan39c79f52010-04-15 10:58:51 +0000314 aCksum[0] = sum1 + (sum1>>24);
315 aCksum[1] = sum2 + (sum2>>24);
dan7c246102010-04-12 19:00:29 +0000316}
317
318/*
drh7ed91f22010-04-29 22:34:07 +0000319** Attempt to change the lock status.
dan7c246102010-04-12 19:00:29 +0000320**
drh7ed91f22010-04-29 22:34:07 +0000321** When changing the lock status to SQLITE_SHM_READ, store the
322** type of reader lock (either SQLITE_SHM_READ or SQLITE_SHM_READ_FULL)
323** in pWal->readerType.
dan7c246102010-04-12 19:00:29 +0000324*/
drh7ed91f22010-04-29 22:34:07 +0000325static int walSetLock(Wal *pWal, int desiredStatus){
dan55437592010-05-11 12:19:26 +0000326 int rc = SQLITE_OK; /* Return code */
327 if( pWal->exclusiveMode || pWal->lockState==desiredStatus ){
328 pWal->lockState = desiredStatus;
329 }else{
330 int got = pWal->lockState;
drh686138f2010-05-12 18:10:52 +0000331 rc = sqlite3OsShmLock(pWal->pDbFd, desiredStatus, &got);
dan55437592010-05-11 12:19:26 +0000332 pWal->lockState = got;
333 if( got==SQLITE_SHM_READ_FULL || got==SQLITE_SHM_READ ){
334 pWal->readerType = got;
335 pWal->lockState = SQLITE_SHM_READ;
336 }
dan7c246102010-04-12 19:00:29 +0000337 }
338 return rc;
339}
340
drh7ed91f22010-04-29 22:34:07 +0000341/*
342** Update the header of the wal-index file.
343*/
344static void walIndexWriteHdr(Wal *pWal, WalIndexHdr *pHdr){
drh5939f442010-05-18 13:27:12 +0000345 volatile u32 *aHdr = pWal->pWiData; /* Write header here */
346 volatile u32 *aCksum = &aHdr[WALINDEX_HDR_NFIELD]; /* Write cksum here */
danff207012010-04-24 04:49:15 +0000347
drh7ed91f22010-04-29 22:34:07 +0000348 assert( WALINDEX_HDR_NFIELD==sizeof(WalIndexHdr)/4 );
349 assert( aHdr!=0 );
drh5939f442010-05-18 13:27:12 +0000350 memcpy((void*)aHdr, pHdr, sizeof(WalIndexHdr));
danff207012010-04-24 04:49:15 +0000351 aCksum[0] = aCksum[1] = 1;
drh5939f442010-05-18 13:27:12 +0000352 walChecksumBytes((u8*)aHdr, sizeof(WalIndexHdr), (u32*)aCksum);
dan7c246102010-04-12 19:00:29 +0000353}
354
355/*
356** This function encodes a single frame header and writes it to a buffer
drh7ed91f22010-04-29 22:34:07 +0000357** supplied by the caller. A frame-header is made up of a series of
dan7c246102010-04-12 19:00:29 +0000358** 4-byte big-endian integers, as follows:
359**
360** 0: Database page size in bytes.
361** 4: Page number.
362** 8: New database size (for commit frames, otherwise zero).
363** 12: Frame checksum 1.
364** 16: Frame checksum 2.
365*/
drh7ed91f22010-04-29 22:34:07 +0000366static void walEncodeFrame(
dan7c246102010-04-12 19:00:29 +0000367 u32 *aCksum, /* IN/OUT: Checksum values */
368 u32 iPage, /* Database page number for frame */
369 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
370 int nData, /* Database page size (size of aData[]) */
371 u8 *aData, /* Pointer to page data (for checksum) */
372 u8 *aFrame /* OUT: Write encoded frame here */
373){
drh7ed91f22010-04-29 22:34:07 +0000374 assert( WAL_FRAME_HDRSIZE==16 );
dan7c246102010-04-12 19:00:29 +0000375
dan97a31352010-04-16 13:59:31 +0000376 sqlite3Put4byte(&aFrame[0], iPage);
377 sqlite3Put4byte(&aFrame[4], nTruncate);
dan7c246102010-04-12 19:00:29 +0000378
drh7ed91f22010-04-29 22:34:07 +0000379 walChecksumBytes(aFrame, 8, aCksum);
380 walChecksumBytes(aData, nData, aCksum);
dan7c246102010-04-12 19:00:29 +0000381
dan97a31352010-04-16 13:59:31 +0000382 sqlite3Put4byte(&aFrame[8], aCksum[0]);
383 sqlite3Put4byte(&aFrame[12], aCksum[1]);
dan7c246102010-04-12 19:00:29 +0000384}
385
386/*
387** Return 1 and populate *piPage, *pnTruncate and aCksum if the
388** frame checksum looks Ok. Otherwise return 0.
389*/
drh7ed91f22010-04-29 22:34:07 +0000390static int walDecodeFrame(
dan7c246102010-04-12 19:00:29 +0000391 u32 *aCksum, /* IN/OUT: Checksum values */
392 u32 *piPage, /* OUT: Database page number for frame */
393 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
394 int nData, /* Database page size (size of aData[]) */
395 u8 *aData, /* Pointer to page data (for checksum) */
396 u8 *aFrame /* Frame data */
397){
drh7ed91f22010-04-29 22:34:07 +0000398 assert( WAL_FRAME_HDRSIZE==16 );
dan4a4b01d2010-04-16 11:30:18 +0000399
drh7ed91f22010-04-29 22:34:07 +0000400 walChecksumBytes(aFrame, 8, aCksum);
401 walChecksumBytes(aData, nData, aCksum);
dan7c246102010-04-12 19:00:29 +0000402
dan97a31352010-04-16 13:59:31 +0000403 if( aCksum[0]!=sqlite3Get4byte(&aFrame[8])
404 || aCksum[1]!=sqlite3Get4byte(&aFrame[12])
dan7c246102010-04-12 19:00:29 +0000405 ){
406 /* Checksum failed. */
407 return 0;
408 }
409
dan97a31352010-04-16 13:59:31 +0000410 *piPage = sqlite3Get4byte(&aFrame[0]);
411 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
dan7c246102010-04-12 19:00:29 +0000412 return 1;
413}
414
danbb23aff2010-05-10 14:46:09 +0000415/*
drh29d4dbe2010-05-18 23:29:52 +0000416** Define the parameters of the hash tables in the wal-index file. There
danbb23aff2010-05-10 14:46:09 +0000417** is a hash-table following every HASHTABLE_NPAGE page numbers in the
418** wal-index.
drh29d4dbe2010-05-18 23:29:52 +0000419**
420** Changing any of these constants will alter the wal-index format and
421** create incompatibilities.
danbb23aff2010-05-10 14:46:09 +0000422*/
drh29d4dbe2010-05-18 23:29:52 +0000423#define HASHTABLE_NPAGE 4096 /* Must be power of 2 and multiple of 256 */
danbb23aff2010-05-10 14:46:09 +0000424#define HASHTABLE_DATATYPE u16
drh29d4dbe2010-05-18 23:29:52 +0000425#define HASHTABLE_HASH_1 383 /* Should be prime */
426#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
427#define HASHTABLE_NBYTE (sizeof(HASHTABLE_DATATYPE)*HASHTABLE_NSLOT)
dan7c246102010-04-12 19:00:29 +0000428
429/*
drha2a42012010-05-18 18:01:08 +0000430** Return the index in the Wal.pWiData array that corresponds to
431** frame iFrame.
432**
433** Wal.pWiData is an array of u32 elements that is the wal-index.
434** The array begins with a header and is then followed by alternating
435** "map" and "hash-table" blocks. Each "map" block consists of
436** HASHTABLE_NPAGE u32 elements which are page numbers corresponding
437** to frames in the WAL file.
438**
439** This routine returns an index X such that Wal.pWiData[X] is part
440** of a "map" block that contains the page number of the iFrame-th
441** frame in the WAL file.
dan7c246102010-04-12 19:00:29 +0000442*/
drh7ed91f22010-04-29 22:34:07 +0000443static int walIndexEntry(u32 iFrame){
danff207012010-04-24 04:49:15 +0000444 return (
drh7ed91f22010-04-29 22:34:07 +0000445 (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)/sizeof(u32)
danbb23aff2010-05-10 14:46:09 +0000446 + (((iFrame-1)/HASHTABLE_NPAGE) * HASHTABLE_NBYTE)/sizeof(u32)
447 + (iFrame-1)
danff207012010-04-24 04:49:15 +0000448 );
dan7c246102010-04-12 19:00:29 +0000449}
450
drh7ed91f22010-04-29 22:34:07 +0000451/*
danb7d53f52010-05-06 17:28:08 +0000452** Return the minimum mapping size in bytes that can be used to read the
453** wal-index up to and including frame iFrame. If iFrame is the last frame
454** in a block of 256 frames, the returned byte-count includes the space
455** required by the 256-byte index block.
456*/
457static int walMappingSize(u32 iFrame){
danbb23aff2010-05-10 14:46:09 +0000458 const int nByte = (sizeof(u32)*HASHTABLE_NPAGE + HASHTABLE_NBYTE) ;
459 return ( WALINDEX_LOCK_OFFSET
460 + WALINDEX_LOCK_RESERVED
461 + nByte * ((iFrame + HASHTABLE_NPAGE - 1)/HASHTABLE_NPAGE)
danb7d53f52010-05-06 17:28:08 +0000462 );
463}
464
465/*
drh5530b762010-04-30 14:39:50 +0000466** Release our reference to the wal-index memory map, if we are holding
467** it.
drh7ed91f22010-04-29 22:34:07 +0000468*/
469static void walIndexUnmap(Wal *pWal){
470 if( pWal->pWiData ){
drhd9e5c4f2010-05-12 18:01:39 +0000471 sqlite3OsShmRelease(pWal->pDbFd);
drh7ed91f22010-04-29 22:34:07 +0000472 pWal->pWiData = 0;
473 }
474}
dan7c246102010-04-12 19:00:29 +0000475
476/*
drh5530b762010-04-30 14:39:50 +0000477** Map the wal-index file into memory if it isn't already.
478**
479** The reqSize parameter is the minimum required size of the mapping.
dan998ad212010-05-07 06:59:08 +0000480** A value of -1 means "don't care".
drh7ed91f22010-04-29 22:34:07 +0000481*/
drh5530b762010-04-30 14:39:50 +0000482static int walIndexMap(Wal *pWal, int reqSize){
483 int rc = SQLITE_OK;
dan998ad212010-05-07 06:59:08 +0000484 if( pWal->pWiData==0 || reqSize>pWal->szWIndex ){
drh5500a1f2010-05-13 09:11:31 +0000485 walIndexUnmap(pWal);
drhd9e5c4f2010-05-12 18:01:39 +0000486 rc = sqlite3OsShmGet(pWal->pDbFd, reqSize, &pWal->szWIndex,
drh5939f442010-05-18 13:27:12 +0000487 (void volatile**)(char volatile*)&pWal->pWiData);
drh5530b762010-04-30 14:39:50 +0000488 if( rc==SQLITE_OK && pWal->pWiData==0 ){
489 /* Make sure pWal->pWiData is not NULL while we are holding the
490 ** lock on the mapping. */
491 assert( pWal->szWIndex==0 );
492 pWal->pWiData = &pWal->iCallback;
493 }
dan65f2ac52010-05-07 09:43:50 +0000494 if( rc!=SQLITE_OK ){
495 walIndexUnmap(pWal);
496 }
drh79e6c782010-04-30 02:13:26 +0000497 }
498 return rc;
499}
500
501/*
drh5530b762010-04-30 14:39:50 +0000502** Remap the wal-index so that the mapping covers the full size
503** of the underlying file.
504**
505** If enlargeTo is non-negative, then increase the size of the underlying
506** storage to be at least as big as enlargeTo before remapping.
drh79e6c782010-04-30 02:13:26 +0000507*/
drh5530b762010-04-30 14:39:50 +0000508static int walIndexRemap(Wal *pWal, int enlargeTo){
509 int rc;
510 int sz;
drhd9e5c4f2010-05-12 18:01:39 +0000511 rc = sqlite3OsShmSize(pWal->pDbFd, enlargeTo, &sz);
drh5530b762010-04-30 14:39:50 +0000512 if( rc==SQLITE_OK && sz>pWal->szWIndex ){
513 walIndexUnmap(pWal);
514 rc = walIndexMap(pWal, sz);
515 }
drh7ed91f22010-04-29 22:34:07 +0000516 return rc;
517}
518
519/*
520** Increment by which to increase the wal-index file size.
521*/
522#define WALINDEX_MMAP_INCREMENT (64*1024)
523
drh29d4dbe2010-05-18 23:29:52 +0000524
525/*
526** Compute a hash on a page number. The resulting hash value must land
527** between 0 and (HASHTABLE_NSLOT-1).
528*/
529static int walHash(u32 iPage){
530 assert( iPage>0 );
531 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
532 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
533}
534static int walNextHash(int iPriorHash){
535 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
danbb23aff2010-05-10 14:46:09 +0000536}
537
538
539/*
540** Find the hash table and (section of the) page number array used to
541** store data for WAL frame iFrame.
542**
543** Set output variable *paHash to point to the start of the hash table
544** in the wal-index file. Set *piZero to one less than the frame
545** number of the first frame indexed by this hash table. If a
546** slot in the hash table is set to N, it refers to frame number
547** (*piZero+N) in the log.
548**
549** Finally, set *paPgno such that for all frames F between (*piZero+1) and
550** (*piZero+HASHTABLE_NPAGE), (*paPgno)[F] is the database page number
551** associated with frame F.
552*/
553static void walHashFind(
554 Wal *pWal, /* WAL handle */
555 u32 iFrame, /* Find the hash table indexing this frame */
drh5939f442010-05-18 13:27:12 +0000556 volatile HASHTABLE_DATATYPE **paHash, /* OUT: Pointer to hash index */
557 volatile u32 **paPgno, /* OUT: Pointer to page number array */
danbb23aff2010-05-10 14:46:09 +0000558 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
559){
560 u32 iZero;
drh5939f442010-05-18 13:27:12 +0000561 volatile u32 *aPgno;
562 volatile HASHTABLE_DATATYPE *aHash;
danbb23aff2010-05-10 14:46:09 +0000563
564 iZero = ((iFrame-1)/HASHTABLE_NPAGE) * HASHTABLE_NPAGE;
565 aPgno = &pWal->pWiData[walIndexEntry(iZero+1)-iZero-1];
566 aHash = (HASHTABLE_DATATYPE *)&aPgno[iZero+HASHTABLE_NPAGE+1];
567
568 /* Assert that:
569 **
570 ** + the mapping is large enough for this hash-table, and
571 **
572 ** + that aPgno[iZero+1] really is the database page number associated
573 ** with the first frame indexed by this hash table.
574 */
575 assert( (u32*)(&aHash[HASHTABLE_NSLOT])<=&pWal->pWiData[pWal->szWIndex/4] );
576 assert( walIndexEntry(iZero+1)==(&aPgno[iZero+1] - pWal->pWiData) );
577
578 *paHash = aHash;
579 *paPgno = aPgno;
580 *piZero = iZero;
581}
582
583
drh7ed91f22010-04-29 22:34:07 +0000584/*
drh29d4dbe2010-05-18 23:29:52 +0000585** Set an entry in the wal-index that will map database page number
586** pPage into WAL frame iFrame.
dan7c246102010-04-12 19:00:29 +0000587*/
drh7ed91f22010-04-29 22:34:07 +0000588static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
danbb23aff2010-05-10 14:46:09 +0000589 int rc; /* Return code */
590 int nMapping; /* Required mapping size in bytes */
drh7ed91f22010-04-29 22:34:07 +0000591
danbb23aff2010-05-10 14:46:09 +0000592 /* Make sure the wal-index is mapped. Enlarge the mapping if required. */
593 nMapping = walMappingSize(iFrame);
danc7991bd2010-05-05 19:04:59 +0000594 rc = walIndexMap(pWal, -1);
danbb23aff2010-05-10 14:46:09 +0000595 while( rc==SQLITE_OK && nMapping>pWal->szWIndex ){
danc9d53db2010-04-30 16:50:00 +0000596 int nByte = pWal->szWIndex + WALINDEX_MMAP_INCREMENT;
drh7ed91f22010-04-29 22:34:07 +0000597 rc = walIndexRemap(pWal, nByte);
dance4f05f2010-04-22 19:14:13 +0000598 }
599
danbb23aff2010-05-10 14:46:09 +0000600 /* Assuming the wal-index file was successfully mapped, find the hash
601 ** table and section of of the page number array that pertain to frame
602 ** iFrame of the WAL. Then populate the page number array and the hash
603 ** table entry.
dan7c246102010-04-12 19:00:29 +0000604 */
danbb23aff2010-05-10 14:46:09 +0000605 if( rc==SQLITE_OK ){
606 int iKey; /* Hash table key */
607 u32 iZero; /* One less than frame number of aPgno[1] */
drh5939f442010-05-18 13:27:12 +0000608 volatile u32 *aPgno; /* Page number array */
609 volatile HASHTABLE_DATATYPE *aHash; /* Hash table */
610 int idx; /* Value to write to hash-table slot */
drh29d4dbe2010-05-18 23:29:52 +0000611 TESTONLY( int nCollide = 0; /* Number of hash collisions */ )
dan7c246102010-04-12 19:00:29 +0000612
danbb23aff2010-05-10 14:46:09 +0000613 walHashFind(pWal, iFrame, &aHash, &aPgno, &iZero);
614 idx = iFrame - iZero;
drh29d4dbe2010-05-18 23:29:52 +0000615 if( idx==1 ) memset((void*)aHash, 0xff, HASHTABLE_NBYTE);
616 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
danbb23aff2010-05-10 14:46:09 +0000617 aPgno[iFrame] = iPage;
drh29d4dbe2010-05-18 23:29:52 +0000618 for(iKey=walHash(iPage); aHash[iKey]<idx; iKey=walNextHash(iKey)){
619 assert( nCollide++ < idx );
620 }
danbb23aff2010-05-10 14:46:09 +0000621 aHash[iKey] = idx;
dan7c246102010-04-12 19:00:29 +0000622 }
dan31f98fc2010-04-27 05:42:32 +0000623
danbb23aff2010-05-10 14:46:09 +0000624 return rc;
dan7c246102010-04-12 19:00:29 +0000625}
626
627
628/*
drh7ed91f22010-04-29 22:34:07 +0000629** Recover the wal-index by reading the write-ahead log file.
630** The caller must hold RECOVER lock on the wal-index file.
dan7c246102010-04-12 19:00:29 +0000631*/
drh7ed91f22010-04-29 22:34:07 +0000632static int walIndexRecover(Wal *pWal){
dan7c246102010-04-12 19:00:29 +0000633 int rc; /* Return Code */
634 i64 nSize; /* Size of log file */
drh7ed91f22010-04-29 22:34:07 +0000635 WalIndexHdr hdr; /* Recovered wal-index header */
dan7c246102010-04-12 19:00:29 +0000636
dan65be0d82010-05-06 18:48:27 +0000637 assert( pWal->lockState>SQLITE_SHM_READ );
dan7c246102010-04-12 19:00:29 +0000638 memset(&hdr, 0, sizeof(hdr));
639
drhd9e5c4f2010-05-12 18:01:39 +0000640 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
dan7c246102010-04-12 19:00:29 +0000641 if( rc!=SQLITE_OK ){
642 return rc;
643 }
644
drh7ed91f22010-04-29 22:34:07 +0000645 if( nSize>WAL_FRAME_HDRSIZE ){
646 u8 aBuf[WAL_FRAME_HDRSIZE]; /* Buffer to load first frame header into */
dan7c246102010-04-12 19:00:29 +0000647 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
648 int nFrame; /* Number of bytes at aFrame */
649 u8 *aData; /* Pointer to data part of aFrame buffer */
650 int iFrame; /* Index of last frame read */
651 i64 iOffset; /* Next offset to read from log file */
652 int nPgsz; /* Page size according to the log */
dan97a31352010-04-16 13:59:31 +0000653 u32 aCksum[2]; /* Running checksum */
dan7c246102010-04-12 19:00:29 +0000654
655 /* Read in the first frame header in the file (to determine the
656 ** database page size).
657 */
drhd9e5c4f2010-05-12 18:01:39 +0000658 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
dan7c246102010-04-12 19:00:29 +0000659 if( rc!=SQLITE_OK ){
660 return rc;
661 }
662
663 /* If the database page size is not a power of two, or is greater than
664 ** SQLITE_MAX_PAGE_SIZE, conclude that the log file contains no valid data.
665 */
666 nPgsz = sqlite3Get4byte(&aBuf[0]);
dance4f05f2010-04-22 19:14:13 +0000667 if( nPgsz&(nPgsz-1) || nPgsz>SQLITE_MAX_PAGE_SIZE || nPgsz<512 ){
dan7c246102010-04-12 19:00:29 +0000668 goto finished;
669 }
dan97a31352010-04-16 13:59:31 +0000670 aCksum[0] = sqlite3Get4byte(&aBuf[4]);
671 aCksum[1] = sqlite3Get4byte(&aBuf[8]);
dan7c246102010-04-12 19:00:29 +0000672
673 /* Malloc a buffer to read frames into. */
drh7ed91f22010-04-29 22:34:07 +0000674 nFrame = nPgsz + WAL_FRAME_HDRSIZE;
dan7c246102010-04-12 19:00:29 +0000675 aFrame = (u8 *)sqlite3_malloc(nFrame);
676 if( !aFrame ){
677 return SQLITE_NOMEM;
678 }
drh7ed91f22010-04-29 22:34:07 +0000679 aData = &aFrame[WAL_FRAME_HDRSIZE];
dan7c246102010-04-12 19:00:29 +0000680
681 /* Read all frames from the log file. */
682 iFrame = 0;
drh7ed91f22010-04-29 22:34:07 +0000683 for(iOffset=WAL_HDRSIZE; (iOffset+nFrame)<=nSize; iOffset+=nFrame){
dan7c246102010-04-12 19:00:29 +0000684 u32 pgno; /* Database page number for frame */
685 u32 nTruncate; /* dbsize field from frame header */
686 int isValid; /* True if this frame is valid */
687
688 /* Read and decode the next log frame. */
drhd9e5c4f2010-05-12 18:01:39 +0000689 rc = sqlite3OsRead(pWal->pWalFd, aFrame, nFrame, iOffset);
dan7c246102010-04-12 19:00:29 +0000690 if( rc!=SQLITE_OK ) break;
drh7ed91f22010-04-29 22:34:07 +0000691 isValid = walDecodeFrame(aCksum, &pgno, &nTruncate, nPgsz, aData, aFrame);
dan7c246102010-04-12 19:00:29 +0000692 if( !isValid ) break;
danc7991bd2010-05-05 19:04:59 +0000693 rc = walIndexAppend(pWal, ++iFrame, pgno);
694 if( rc!=SQLITE_OK ) break;
dan7c246102010-04-12 19:00:29 +0000695
696 /* If nTruncate is non-zero, this is a commit record. */
697 if( nTruncate ){
698 hdr.iCheck1 = aCksum[0];
699 hdr.iCheck2 = aCksum[1];
drh027a1282010-05-19 01:53:53 +0000700 hdr.mxFrame = iFrame;
dan7c246102010-04-12 19:00:29 +0000701 hdr.nPage = nTruncate;
702 hdr.pgsz = nPgsz;
703 }
704 }
705
706 sqlite3_free(aFrame);
707 }else{
708 hdr.iCheck1 = 2;
709 hdr.iCheck2 = 3;
710 }
711
712finished:
drh027a1282010-05-19 01:53:53 +0000713 if( rc==SQLITE_OK && hdr.mxFrame==0 ){
dan576bc322010-05-06 18:04:50 +0000714 rc = walIndexRemap(pWal, WALINDEX_MMAP_INCREMENT);
715 }
716 if( rc==SQLITE_OK ){
717 walIndexWriteHdr(pWal, &hdr);
718 memcpy(&pWal->hdr, &hdr, sizeof(hdr));
719 }
dan7c246102010-04-12 19:00:29 +0000720 return rc;
721}
722
drha8e654e2010-05-04 17:38:42 +0000723/*
dan1018e902010-05-05 15:33:05 +0000724** Close an open wal-index.
drha8e654e2010-05-04 17:38:42 +0000725*/
dan1018e902010-05-05 15:33:05 +0000726static void walIndexClose(Wal *pWal, int isDelete){
drhd9e5c4f2010-05-12 18:01:39 +0000727 if( pWal->isWindexOpen ){
drha8e654e2010-05-04 17:38:42 +0000728 int notUsed;
drhd9e5c4f2010-05-12 18:01:39 +0000729 sqlite3OsShmLock(pWal->pDbFd, SQLITE_SHM_UNLOCK, &notUsed);
730 sqlite3OsShmClose(pWal->pDbFd, isDelete);
731 pWal->isWindexOpen = 0;
drha8e654e2010-05-04 17:38:42 +0000732 }
733}
734
dan7c246102010-04-12 19:00:29 +0000735/*
736** Open a connection to the log file associated with database zDb. The
737** database file does not actually have to exist. zDb is used only to
738** figure out the name of the log file to open. If the log file does not
739** exist it is created by this call.
dan3de777f2010-04-17 12:31:37 +0000740**
741** A SHARED lock should be held on the database file when this function
742** is called. The purpose of this SHARED lock is to prevent any other
drh7ed91f22010-04-29 22:34:07 +0000743** client from unlinking the log or wal-index file. If another process
dan3de777f2010-04-17 12:31:37 +0000744** were to do this just after this client opened one of these files, the
745** system would be badly broken.
danef378022010-05-04 11:06:03 +0000746**
747** If the log file is successfully opened, SQLITE_OK is returned and
748** *ppWal is set to point to a new WAL handle. If an error occurs,
749** an SQLite error code is returned and *ppWal is left unmodified.
dan7c246102010-04-12 19:00:29 +0000750*/
drhc438efd2010-04-26 00:19:45 +0000751int sqlite3WalOpen(
drh7ed91f22010-04-29 22:34:07 +0000752 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
drhd9e5c4f2010-05-12 18:01:39 +0000753 sqlite3_file *pDbFd, /* The open database file */
754 const char *zDbName, /* Name of the database file */
drh7ed91f22010-04-29 22:34:07 +0000755 Wal **ppWal /* OUT: Allocated Wal handle */
dan7c246102010-04-12 19:00:29 +0000756){
danef378022010-05-04 11:06:03 +0000757 int rc; /* Return Code */
drh7ed91f22010-04-29 22:34:07 +0000758 Wal *pRet; /* Object to allocate and return */
dan7c246102010-04-12 19:00:29 +0000759 int flags; /* Flags passed to OsOpen() */
drhd9e5c4f2010-05-12 18:01:39 +0000760 char *zWal; /* Name of write-ahead log file */
dan7c246102010-04-12 19:00:29 +0000761 int nWal; /* Length of zWal in bytes */
762
drhd9e5c4f2010-05-12 18:01:39 +0000763 assert( zDbName && zDbName[0] );
764 assert( pDbFd );
dan7c246102010-04-12 19:00:29 +0000765
drh7ed91f22010-04-29 22:34:07 +0000766 /* Allocate an instance of struct Wal to return. */
767 *ppWal = 0;
drh686138f2010-05-12 18:10:52 +0000768 nWal = sqlite3Strlen30(zDbName) + 5;
drhd9e5c4f2010-05-12 18:01:39 +0000769 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile + nWal);
dan76ed3bc2010-05-03 17:18:24 +0000770 if( !pRet ){
771 return SQLITE_NOMEM;
772 }
773
dan7c246102010-04-12 19:00:29 +0000774 pRet->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +0000775 pRet->pWalFd = (sqlite3_file *)&pRet[1];
776 pRet->pDbFd = pDbFd;
777 pRet->zWalName = zWal = pVfs->szOsFile + (char*)pRet->pWalFd;
778 sqlite3_snprintf(nWal, zWal, "%s-wal", zDbName);
779 rc = sqlite3OsShmOpen(pDbFd);
dan7c246102010-04-12 19:00:29 +0000780
drh7ed91f22010-04-29 22:34:07 +0000781 /* Open file handle on the write-ahead log file. */
dan76ed3bc2010-05-03 17:18:24 +0000782 if( rc==SQLITE_OK ){
danbd50dde2010-05-13 07:08:53 +0000783 pRet->isWindexOpen = 1;
dan76ed3bc2010-05-03 17:18:24 +0000784 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_JOURNAL);
drhd9e5c4f2010-05-12 18:01:39 +0000785 rc = sqlite3OsOpen(pVfs, zWal, pRet->pWalFd, flags, &flags);
dan76ed3bc2010-05-03 17:18:24 +0000786 }
dan7c246102010-04-12 19:00:29 +0000787
dan7c246102010-04-12 19:00:29 +0000788 if( rc!=SQLITE_OK ){
dan1018e902010-05-05 15:33:05 +0000789 walIndexClose(pRet, 0);
drhd9e5c4f2010-05-12 18:01:39 +0000790 sqlite3OsClose(pRet->pWalFd);
danef378022010-05-04 11:06:03 +0000791 sqlite3_free(pRet);
792 }else{
793 *ppWal = pRet;
dan7c246102010-04-12 19:00:29 +0000794 }
dan7c246102010-04-12 19:00:29 +0000795 return rc;
796}
797
drha2a42012010-05-18 18:01:08 +0000798/*
799** Find the smallest page number out of all pages held in the WAL that
800** has not been returned by any prior invocation of this method on the
801** same WalIterator object. Write into *piFrame the frame index where
802** that page was last written into the WAL. Write into *piPage the page
803** number.
804**
805** Return 0 on success. If there are no pages in the WAL with a page
806** number larger than *piPage, then return 1.
807*/
drh7ed91f22010-04-29 22:34:07 +0000808static int walIteratorNext(
809 WalIterator *p, /* Iterator */
drha2a42012010-05-18 18:01:08 +0000810 u32 *piPage, /* OUT: The page number of the next page */
811 u32 *piFrame /* OUT: Wal frame index of next page */
dan7c246102010-04-12 19:00:29 +0000812){
drha2a42012010-05-18 18:01:08 +0000813 u32 iMin; /* Result pgno must be greater than iMin */
814 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
815 int i; /* For looping through segments */
816 int nBlock = p->nFinal; /* Number of entries in current segment */
dan7c246102010-04-12 19:00:29 +0000817
drha2a42012010-05-18 18:01:08 +0000818 iMin = p->iPrior;
819 assert( iMin<0xffffffff );
dan7c246102010-04-12 19:00:29 +0000820 for(i=p->nSegment-1; i>=0; i--){
drh7ed91f22010-04-29 22:34:07 +0000821 struct WalSegment *pSegment = &p->aSegment[i];
dan7c246102010-04-12 19:00:29 +0000822 while( pSegment->iNext<nBlock ){
drha2a42012010-05-18 18:01:08 +0000823 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
dan7c246102010-04-12 19:00:29 +0000824 if( iPg>iMin ){
825 if( iPg<iRet ){
826 iRet = iPg;
827 *piFrame = i*256 + 1 + pSegment->aIndex[pSegment->iNext];
828 }
829 break;
830 }
831 pSegment->iNext++;
832 }
dan7c246102010-04-12 19:00:29 +0000833 nBlock = 256;
834 }
835
drha2a42012010-05-18 18:01:08 +0000836 *piPage = p->iPrior = iRet;
dan7c246102010-04-12 19:00:29 +0000837 return (iRet==0xFFFFFFFF);
838}
839
dan7c246102010-04-12 19:00:29 +0000840
drha2a42012010-05-18 18:01:08 +0000841static void walMergesort8(
842 Pgno *aContent, /* Pages in wal */
843 u8 *aBuffer, /* Buffer of at least *pnList items to use */
844 u8 *aList, /* IN/OUT: List to sort */
845 int *pnList /* IN/OUT: Number of elements in aList[] */
846){
847 int nList = *pnList;
848 if( nList>1 ){
849 int nLeft = nList / 2; /* Elements in left list */
850 int nRight = nList - nLeft; /* Elements in right list */
851 u8 *aLeft = aList; /* Left list */
852 u8 *aRight = &aList[nLeft]; /* Right list */
853 int iLeft = 0; /* Current index in aLeft */
854 int iRight = 0; /* Current index in aright */
855 int iOut = 0; /* Current index in output buffer */
856
857 /* TODO: Change to non-recursive version. */
858 walMergesort8(aContent, aBuffer, aLeft, &nLeft);
859 walMergesort8(aContent, aBuffer, aRight, &nRight);
860
861 while( iRight<nRight || iLeft<nLeft ){
862 u8 logpage;
863 Pgno dbpage;
864
865 if( (iLeft<nLeft)
866 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
867 ){
868 logpage = aLeft[iLeft++];
869 }else{
870 logpage = aRight[iRight++];
871 }
872 dbpage = aContent[logpage];
873
874 aBuffer[iOut++] = logpage;
875 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
876
877 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
878 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
879 }
880 memcpy(aList, aBuffer, sizeof(aList[0])*iOut);
881 *pnList = iOut;
882 }
883
884#ifdef SQLITE_DEBUG
885 {
886 int i;
887 for(i=1; i<*pnList; i++){
888 assert( aContent[aList[i]] > aContent[aList[i-1]] );
889 }
890 }
891#endif
892}
893
894/*
895** Map the wal-index into memory owned by this thread, if it is not
896** mapped already. Then construct a WalInterator object that can be
897** used to loop over all pages in the WAL in ascending order.
898**
899** On success, make *pp point to the newly allocated WalInterator object
900** return SQLITE_OK. Otherwise, leave *pp unchanged and return an error
901** code.
902**
903** The calling routine should invoke walIteratorFree() to destroy the
904** WalIterator object when it has finished with it. The caller must
905** also unmap the wal-index. But the wal-index must not be unmapped
906** prior to the WalIterator object being destroyed.
907*/
908static int walIteratorInit(Wal *pWal, WalIterator **pp){
909 u32 *aData; /* Content of the wal-index file */
910 WalIterator *p; /* Return value */
911 int nSegment; /* Number of segments to merge */
912 u32 iLast; /* Last frame in log */
913 int nByte; /* Number of bytes to allocate */
914 int i; /* Iterator variable */
915 int nFinal; /* Number of unindexed entries */
916 u8 *aTmp; /* Temp space used by merge-sort */
917 int rc; /* Return code of walIndexMap() */
918 u8 *aSpace; /* Surplus space on the end of the allocation */
919
920 /* Make sure the wal-index is mapped into local memory */
drh027a1282010-05-19 01:53:53 +0000921 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
dan8f6097c2010-05-06 07:43:58 +0000922 if( rc!=SQLITE_OK ){
923 return rc;
924 }
drha2a42012010-05-18 18:01:08 +0000925
926 /* This routine only runs while holding SQLITE_SHM_CHECKPOINT. No other
927 ** thread is able to write to shared memory while this routine is
928 ** running (or, indeed, while the WalIterator object exists). Hence,
929 ** we can cast off the volatile qualifacation from shared memory
930 */
931 assert( pWal->lockState==SQLITE_SHM_CHECKPOINT );
drh5939f442010-05-18 13:27:12 +0000932 aData = (u32*)pWal->pWiData;
drha2a42012010-05-18 18:01:08 +0000933
934 /* Allocate space for the WalIterator object */
drh027a1282010-05-19 01:53:53 +0000935 iLast = pWal->hdr.mxFrame;
dan7c246102010-04-12 19:00:29 +0000936 nSegment = (iLast >> 8) + 1;
937 nFinal = (iLast & 0x000000FF);
danbb23aff2010-05-10 14:46:09 +0000938 nByte = sizeof(WalIterator) + (nSegment+1)*(sizeof(struct WalSegment)+256);
drh7ed91f22010-04-29 22:34:07 +0000939 p = (WalIterator *)sqlite3_malloc(nByte);
dan8f6097c2010-05-06 07:43:58 +0000940 if( !p ){
drha2a42012010-05-18 18:01:08 +0000941 return SQLITE_NOMEM;
942 }
943 memset(p, 0, nByte);
dan76ed3bc2010-05-03 17:18:24 +0000944
drha2a42012010-05-18 18:01:08 +0000945 /* Initialize the WalIterator object. Each 256-entry segment is
946 ** presorted in order to make iterating through all entries much
947 ** faster.
948 */
949 p->nSegment = nSegment;
950 aSpace = (u8 *)&p->aSegment[nSegment];
951 aTmp = &aSpace[nSegment*256];
952 for(i=0; i<nSegment; i++){
953 int j;
954 int nIndex = (i==nSegment-1) ? nFinal : 256;
955 p->aSegment[i].aPgno = &aData[walIndexEntry(i*256+1)];
956 p->aSegment[i].aIndex = aSpace;
957 for(j=0; j<nIndex; j++){
958 aSpace[j] = j;
dan76ed3bc2010-05-03 17:18:24 +0000959 }
drha2a42012010-05-18 18:01:08 +0000960 walMergesort8(p->aSegment[i].aPgno, aTmp, aSpace, &nIndex);
961 memset(&aSpace[nIndex], aSpace[nIndex-1], 256-nIndex);
962 aSpace += 256;
963 p->nFinal = nIndex;
dan7c246102010-04-12 19:00:29 +0000964 }
965
drha2a42012010-05-18 18:01:08 +0000966 /* Return the fully initializd WalIterator object */
dan8f6097c2010-05-06 07:43:58 +0000967 *pp = p;
drha2a42012010-05-18 18:01:08 +0000968 return SQLITE_OK ;
dan7c246102010-04-12 19:00:29 +0000969}
970
971/*
drha2a42012010-05-18 18:01:08 +0000972** Free an iterator allocated by walIteratorInit().
dan7c246102010-04-12 19:00:29 +0000973*/
drh7ed91f22010-04-29 22:34:07 +0000974static void walIteratorFree(WalIterator *p){
dan7c246102010-04-12 19:00:29 +0000975 sqlite3_free(p);
976}
977
978/*
979** Checkpoint the contents of the log file.
980*/
drh7ed91f22010-04-29 22:34:07 +0000981static int walCheckpoint(
982 Wal *pWal, /* Wal connection */
danc5118782010-04-17 17:34:41 +0000983 int sync_flags, /* Flags for OsSync() (or 0) */
danb6e099a2010-05-04 14:47:39 +0000984 int nBuf, /* Size of zBuf in bytes */
dan7c246102010-04-12 19:00:29 +0000985 u8 *zBuf /* Temporary buffer to use */
986){
987 int rc; /* Return code */
drh7ed91f22010-04-29 22:34:07 +0000988 int pgsz = pWal->hdr.pgsz; /* Database page-size */
989 WalIterator *pIter = 0; /* Wal iterator context */
dan7c246102010-04-12 19:00:29 +0000990 u32 iDbpage = 0; /* Next database page to write */
drh7ed91f22010-04-29 22:34:07 +0000991 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
dan7c246102010-04-12 19:00:29 +0000992
993 /* Allocate the iterator */
dan8f6097c2010-05-06 07:43:58 +0000994 rc = walIteratorInit(pWal, &pIter);
drh027a1282010-05-19 01:53:53 +0000995 if( rc!=SQLITE_OK || pWal->hdr.mxFrame==0 ){
danb6e099a2010-05-04 14:47:39 +0000996 goto out;
997 }
998
999 if( pWal->hdr.pgsz!=nBuf ){
1000 rc = SQLITE_CORRUPT_BKPT;
1001 goto out;
1002 }
1003
dan7c246102010-04-12 19:00:29 +00001004 /* Sync the log file to disk */
danc5118782010-04-17 17:34:41 +00001005 if( sync_flags ){
drhd9e5c4f2010-05-12 18:01:39 +00001006 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
danc5118782010-04-17 17:34:41 +00001007 if( rc!=SQLITE_OK ) goto out;
1008 }
dan7c246102010-04-12 19:00:29 +00001009
1010 /* Iterate through the contents of the log, copying data to the db file. */
drh7ed91f22010-04-29 22:34:07 +00001011 while( 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
drhd9e5c4f2010-05-12 18:01:39 +00001012 rc = sqlite3OsRead(pWal->pWalFd, zBuf, pgsz,
drh7ed91f22010-04-29 22:34:07 +00001013 walFrameOffset(iFrame, pgsz) + WAL_FRAME_HDRSIZE
dan7c246102010-04-12 19:00:29 +00001014 );
1015 if( rc!=SQLITE_OK ) goto out;
drhd9e5c4f2010-05-12 18:01:39 +00001016 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, pgsz, (iDbpage-1)*pgsz);
dan7c246102010-04-12 19:00:29 +00001017 if( rc!=SQLITE_OK ) goto out;
1018 }
1019
1020 /* Truncate the database file */
drhd9e5c4f2010-05-12 18:01:39 +00001021 rc = sqlite3OsTruncate(pWal->pDbFd, ((i64)pWal->hdr.nPage*(i64)pgsz));
dan7c246102010-04-12 19:00:29 +00001022 if( rc!=SQLITE_OK ) goto out;
1023
drh7ed91f22010-04-29 22:34:07 +00001024 /* Sync the database file. If successful, update the wal-index. */
danc5118782010-04-17 17:34:41 +00001025 if( sync_flags ){
drhd9e5c4f2010-05-12 18:01:39 +00001026 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
danc5118782010-04-17 17:34:41 +00001027 if( rc!=SQLITE_OK ) goto out;
1028 }
drh027a1282010-05-19 01:53:53 +00001029 pWal->hdr.mxFrame = 0;
drh7ed91f22010-04-29 22:34:07 +00001030 pWal->hdr.iCheck1 = 2;
1031 pWal->hdr.iCheck2 = 3;
1032 walIndexWriteHdr(pWal, &pWal->hdr);
dan7c246102010-04-12 19:00:29 +00001033
1034 /* TODO: If a crash occurs and the current log is copied into the
1035 ** database there is no problem. However, if a crash occurs while
1036 ** writing the next transaction into the start of the log, such that:
1037 **
1038 ** * The first transaction currently in the log is left intact, but
1039 ** * The second (or subsequent) transaction is damaged,
1040 **
1041 ** then the database could become corrupt.
1042 **
1043 ** The easiest thing to do would be to write and sync a dummy header
1044 ** into the log at this point. Unfortunately, that turns out to be
1045 ** an unwelcome performance hit. Alternatives are...
1046 */
1047#if 0
drh7ed91f22010-04-29 22:34:07 +00001048 memset(zBuf, 0, WAL_FRAME_HDRSIZE);
drhd9e5c4f2010-05-12 18:01:39 +00001049 rc = sqlite3OsWrite(pWal->pWalFd, zBuf, WAL_FRAME_HDRSIZE, 0);
dan7c246102010-04-12 19:00:29 +00001050 if( rc!=SQLITE_OK ) goto out;
drhd9e5c4f2010-05-12 18:01:39 +00001051 rc = sqlite3OsSync(pWal->pWalFd, pWal->sync_flags);
dan7c246102010-04-12 19:00:29 +00001052#endif
1053
1054 out:
drh7ed91f22010-04-29 22:34:07 +00001055 walIteratorFree(pIter);
dan7c246102010-04-12 19:00:29 +00001056 return rc;
1057}
1058
1059/*
1060** Close a connection to a log file.
1061*/
drhc438efd2010-04-26 00:19:45 +00001062int sqlite3WalClose(
drh7ed91f22010-04-29 22:34:07 +00001063 Wal *pWal, /* Wal to close */
danc5118782010-04-17 17:34:41 +00001064 int sync_flags, /* Flags to pass to OsSync() (or 0) */
danb6e099a2010-05-04 14:47:39 +00001065 int nBuf,
1066 u8 *zBuf /* Buffer of at least nBuf bytes */
dan7c246102010-04-12 19:00:29 +00001067){
1068 int rc = SQLITE_OK;
drh7ed91f22010-04-29 22:34:07 +00001069 if( pWal ){
dan30c86292010-04-30 16:24:46 +00001070 int isDelete = 0; /* True to unlink wal and wal-index files */
1071
1072 /* If an EXCLUSIVE lock can be obtained on the database file (using the
1073 ** ordinary, rollback-mode locking methods, this guarantees that the
1074 ** connection associated with this log file is the only connection to
1075 ** the database. In this case checkpoint the database and unlink both
1076 ** the wal and wal-index files.
1077 **
1078 ** The EXCLUSIVE lock is not released before returning.
1079 */
drhd9e5c4f2010-05-12 18:01:39 +00001080 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
dan30c86292010-04-30 16:24:46 +00001081 if( rc==SQLITE_OK ){
drhd9e5c4f2010-05-12 18:01:39 +00001082 rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf, 0, 0);
dan30c86292010-04-30 16:24:46 +00001083 if( rc==SQLITE_OK ){
1084 isDelete = 1;
1085 }
1086 walIndexUnmap(pWal);
1087 }
1088
dan1018e902010-05-05 15:33:05 +00001089 walIndexClose(pWal, isDelete);
drhd9e5c4f2010-05-12 18:01:39 +00001090 sqlite3OsClose(pWal->pWalFd);
dan30c86292010-04-30 16:24:46 +00001091 if( isDelete ){
drhd9e5c4f2010-05-12 18:01:39 +00001092 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
dan30c86292010-04-30 16:24:46 +00001093 }
drh7ed91f22010-04-29 22:34:07 +00001094 sqlite3_free(pWal);
dan7c246102010-04-12 19:00:29 +00001095 }
1096 return rc;
1097}
1098
1099/*
drha2a42012010-05-18 18:01:08 +00001100** Try to read the wal-index header. Return 0 on success and 1 if
1101** there is a problem.
1102**
1103** The wal-index is in shared memory. Another thread or process might
1104** be writing the header at the same time this procedure is trying to
1105** read it, which might result in inconsistency. A dirty read is detected
1106** by verifying a checksum on the header.
1107**
1108** If and only if the read is consistent and the header is different from
1109** pWal->hdr, then pWal->hdr is updated to the content of the new header
1110** and *pChanged is set to 1.
danb9bf16b2010-04-14 11:23:30 +00001111**
dan84670502010-05-07 05:46:23 +00001112** If the checksum cannot be verified return non-zero. If the header
1113** is read successfully and the checksum verified, return zero.
danb9bf16b2010-04-14 11:23:30 +00001114*/
dan84670502010-05-07 05:46:23 +00001115int walIndexTryHdr(Wal *pWal, int *pChanged){
drha2a42012010-05-18 18:01:08 +00001116 int i;
1117 volatile u32 *aWiData;
danb9bf16b2010-04-14 11:23:30 +00001118 u32 aCksum[2] = {1, 1};
drh7ed91f22010-04-29 22:34:07 +00001119 u32 aHdr[WALINDEX_HDR_NFIELD+2];
danb9bf16b2010-04-14 11:23:30 +00001120
dan84670502010-05-07 05:46:23 +00001121 assert( pWal->pWiData );
drh79e6c782010-04-30 02:13:26 +00001122 if( pWal->szWIndex==0 ){
dan84670502010-05-07 05:46:23 +00001123 /* The wal-index is of size 0 bytes. This is handled in the same way
1124 ** as an invalid header. The caller will run recovery to construct
1125 ** a valid wal-index file before accessing the database.
1126 */
1127 return 1;
drh79e6c782010-04-30 02:13:26 +00001128 }
1129
dan84670502010-05-07 05:46:23 +00001130 /* Read the header. The caller may or may not have an exclusive
1131 ** (WRITE, PENDING, CHECKPOINT or RECOVER) lock on the wal-index
dancd11fb22010-04-26 10:40:52 +00001132 ** file, meaning it is possible that an inconsistent snapshot is read
dan84670502010-05-07 05:46:23 +00001133 ** from the file. If this happens, return non-zero.
danb9bf16b2010-04-14 11:23:30 +00001134 */
drha2a42012010-05-18 18:01:08 +00001135 aWiData = pWal->pWiData;
1136 for(i=0; i<WALINDEX_HDR_NFIELD+2; i++){
1137 aHdr[i] = aWiData[i];
1138 }
drh7ed91f22010-04-29 22:34:07 +00001139 walChecksumBytes((u8*)aHdr, sizeof(u32)*WALINDEX_HDR_NFIELD, aCksum);
1140 if( aCksum[0]!=aHdr[WALINDEX_HDR_NFIELD]
1141 || aCksum[1]!=aHdr[WALINDEX_HDR_NFIELD+1]
danb9bf16b2010-04-14 11:23:30 +00001142 ){
dan84670502010-05-07 05:46:23 +00001143 return 1;
danb9bf16b2010-04-14 11:23:30 +00001144 }
1145
drh7ed91f22010-04-29 22:34:07 +00001146 if( memcmp(&pWal->hdr, aHdr, sizeof(WalIndexHdr)) ){
dana8614692010-05-06 14:42:34 +00001147 *pChanged = 1;
drh7ed91f22010-04-29 22:34:07 +00001148 memcpy(&pWal->hdr, aHdr, sizeof(WalIndexHdr));
danb9bf16b2010-04-14 11:23:30 +00001149 }
dan84670502010-05-07 05:46:23 +00001150
1151 /* The header was successfully read. Return zero. */
1152 return 0;
danb9bf16b2010-04-14 11:23:30 +00001153}
1154
1155/*
drha2a42012010-05-18 18:01:08 +00001156** Read the wal-index header from the wal-index and into pWal->hdr.
1157** If the wal-header appears to be corrupt, try to recover the log
1158** before returning.
1159**
1160** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
1161** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
1162** to 0.
1163**
1164** This routine also maps the wal-index content into memory and assigns
1165** ownership of that mapping to the current thread. In some implementations,
1166** only one thread at a time can hold a mapping of the wal-index. Hence,
1167** the caller should strive to invoke walIndexUnmap() as soon as possible
1168** after this routine returns.
danb9bf16b2010-04-14 11:23:30 +00001169**
drh7ed91f22010-04-29 22:34:07 +00001170** If the wal-index header is successfully read, return SQLITE_OK.
danb9bf16b2010-04-14 11:23:30 +00001171** Otherwise an SQLite error code.
1172*/
drh7ed91f22010-04-29 22:34:07 +00001173static int walIndexReadHdr(Wal *pWal, int *pChanged){
dan84670502010-05-07 05:46:23 +00001174 int rc; /* Return code */
1175 int lockState; /* pWal->lockState before running recovery */
danb9bf16b2010-04-14 11:23:30 +00001176
dan4c97b532010-04-30 09:52:17 +00001177 assert( pWal->lockState>=SQLITE_SHM_READ );
dana8614692010-05-06 14:42:34 +00001178 assert( pChanged );
danc7991bd2010-05-05 19:04:59 +00001179 rc = walIndexMap(pWal, -1);
1180 if( rc!=SQLITE_OK ){
1181 return rc;
1182 }
drh7ed91f22010-04-29 22:34:07 +00001183
dan84670502010-05-07 05:46:23 +00001184 /* First attempt to read the wal-index header. This may fail for one
1185 ** of two reasons: (a) the wal-index does not yet exist or has been
1186 ** corrupted and needs to be constructed by running recovery, or (b)
1187 ** the caller is only holding a READ lock and made a dirty read of
1188 ** the wal-index header.
1189 **
1190 ** A dirty read of the wal-index header occurs if another thread or
1191 ** process happens to be writing to the wal-index header at roughly
1192 ** the same time as this thread is reading it. In this case it is
1193 ** possible that an inconsistent header is read (which is detected
1194 ** using the header checksum mechanism).
danb9bf16b2010-04-14 11:23:30 +00001195 */
dan84670502010-05-07 05:46:23 +00001196 if( walIndexTryHdr(pWal, pChanged)==0 ){
1197 return SQLITE_OK;
danb9bf16b2010-04-14 11:23:30 +00001198 }
1199
drh7ed91f22010-04-29 22:34:07 +00001200 /* If the first attempt to read the header failed, lock the wal-index
dan84670502010-05-07 05:46:23 +00001201 ** file with an exclusive lock and try again. If the header checksum
1202 ** verification fails again, we can be sure that it is not simply a
1203 ** dirty read, but that the wal-index really does need to be
1204 ** reconstructed by running log recovery.
1205 **
1206 ** In the paragraph above, an "exclusive lock" may be any of WRITE,
1207 ** PENDING, CHECKPOINT or RECOVER. If any of these are already held,
1208 ** no locking operations are required. If the caller currently holds
1209 ** a READ lock, then upgrade to a RECOVER lock before re-reading the
1210 ** wal-index header and revert to a READ lock before returning.
danb9bf16b2010-04-14 11:23:30 +00001211 */
dan5273f582010-05-06 18:27:19 +00001212 lockState = pWal->lockState;
dan65be0d82010-05-06 18:48:27 +00001213 if( lockState>SQLITE_SHM_READ
1214 || SQLITE_OK==(rc = walSetLock(pWal, SQLITE_SHM_RECOVER))
1215 ){
dan84670502010-05-07 05:46:23 +00001216 if( walIndexTryHdr(pWal, pChanged) ){
dana8614692010-05-06 14:42:34 +00001217 *pChanged = 1;
drh7ed91f22010-04-29 22:34:07 +00001218 rc = walIndexRecover(pWal);
danb9bf16b2010-04-14 11:23:30 +00001219 }
dan65be0d82010-05-06 18:48:27 +00001220 if( lockState==SQLITE_SHM_READ ){
1221 walSetLock(pWal, SQLITE_SHM_READ);
1222 }
danb9bf16b2010-04-14 11:23:30 +00001223 }
1224
1225 return rc;
1226}
1227
1228/*
drha2a42012010-05-18 18:01:08 +00001229** Take a snapshot of the state of the WAL and wal-index for the current
1230** instant in time. The current thread will continue to use this snapshot.
1231** Other threads might containing appending to the WAL and wal-index but
1232** the extra content appended will be ignored by the current thread.
1233**
1234** A snapshot is like a read transaction.
1235**
1236** No other threads are allowed to run a checkpoint while this thread is
1237** holding the snapshot since a checkpoint would remove data out from under
1238** this thread.
dan7c246102010-04-12 19:00:29 +00001239**
1240** If this call obtains a new read-lock and the database contents have been
drh7ed91f22010-04-29 22:34:07 +00001241** modified since the most recent call to WalCloseSnapshot() on this Wal
dan7c246102010-04-12 19:00:29 +00001242** connection, then *pChanged is set to 1 before returning. Otherwise, it
1243** is left unmodified. This is used by the pager layer to determine whether
1244** or not any cached pages may be safely reused.
1245*/
drh7ed91f22010-04-29 22:34:07 +00001246int sqlite3WalOpenSnapshot(Wal *pWal, int *pChanged){
dan8d6ad1c2010-05-04 10:36:20 +00001247 int rc; /* Return code */
dan64d039e2010-04-13 19:27:31 +00001248
drh7ed91f22010-04-29 22:34:07 +00001249 rc = walSetLock(pWal, SQLITE_SHM_READ);
dan8d6ad1c2010-05-04 10:36:20 +00001250 assert( rc!=SQLITE_OK || pWal->lockState==SQLITE_SHM_READ );
dan64d039e2010-04-13 19:27:31 +00001251
dan8d6ad1c2010-05-04 10:36:20 +00001252 if( rc==SQLITE_OK ){
drh7ed91f22010-04-29 22:34:07 +00001253 rc = walIndexReadHdr(pWal, pChanged);
dan64d039e2010-04-13 19:27:31 +00001254 if( rc!=SQLITE_OK ){
1255 /* An error occured while attempting log recovery. */
drh7ed91f22010-04-29 22:34:07 +00001256 sqlite3WalCloseSnapshot(pWal);
dan64d039e2010-04-13 19:27:31 +00001257 }
dan7c246102010-04-12 19:00:29 +00001258 }
danba515902010-04-30 09:32:06 +00001259
1260 walIndexUnmap(pWal);
dan7c246102010-04-12 19:00:29 +00001261 return rc;
1262}
1263
1264/*
1265** Unlock the current snapshot.
1266*/
drh7ed91f22010-04-29 22:34:07 +00001267void sqlite3WalCloseSnapshot(Wal *pWal){
dan8d6ad1c2010-05-04 10:36:20 +00001268 assert( pWal->lockState==SQLITE_SHM_READ
1269 || pWal->lockState==SQLITE_SHM_UNLOCK
1270 );
1271 walSetLock(pWal, SQLITE_SHM_UNLOCK);
dan7c246102010-04-12 19:00:29 +00001272}
1273
dan5e0ce872010-04-28 17:48:44 +00001274/*
dan7c246102010-04-12 19:00:29 +00001275** Read a page from the log, if it is present.
1276*/
danb6e099a2010-05-04 14:47:39 +00001277int sqlite3WalRead(
danbb23aff2010-05-10 14:46:09 +00001278 Wal *pWal, /* WAL handle */
1279 Pgno pgno, /* Database page number to read data for */
1280 int *pInWal, /* OUT: True if data is read from WAL */
1281 int nOut, /* Size of buffer pOut in bytes */
1282 u8 *pOut /* Buffer to write page data to */
danb6e099a2010-05-04 14:47:39 +00001283){
danc7991bd2010-05-05 19:04:59 +00001284 int rc; /* Return code */
danbb23aff2010-05-10 14:46:09 +00001285 u32 iRead = 0; /* If !=0, WAL frame to return data from */
drh027a1282010-05-19 01:53:53 +00001286 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
danbb23aff2010-05-10 14:46:09 +00001287 int iHash; /* Used to loop through N hash tables */
dan7c246102010-04-12 19:00:29 +00001288
danbb23aff2010-05-10 14:46:09 +00001289 /* If the "last page" field of the wal-index header snapshot is 0, then
1290 ** no data will be read from the wal under any circumstances. Return early
1291 ** in this case to avoid the walIndexMap/Unmap overhead.
1292 */
1293 if( iLast==0 ){
1294 *pInWal = 0;
1295 return SQLITE_OK;
1296 }
1297
1298 /* Ensure the wal-index is mapped. */
dan1bc61712010-04-30 10:24:54 +00001299 assert( pWal->lockState==SQLITE_SHM_READ||pWal->lockState==SQLITE_SHM_WRITE );
danbb23aff2010-05-10 14:46:09 +00001300 rc = walIndexMap(pWal, walMappingSize(iLast));
danc7991bd2010-05-05 19:04:59 +00001301 if( rc!=SQLITE_OK ){
1302 return rc;
1303 }
dancd11fb22010-04-26 10:40:52 +00001304
danbb23aff2010-05-10 14:46:09 +00001305 /* Search the hash table or tables for an entry matching page number
1306 ** pgno. Each iteration of the following for() loop searches one
1307 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
1308 **
1309 ** This code may run concurrently to the code in walIndexAppend()
1310 ** that adds entries to the wal-index (and possibly to this hash
1311 ** table). This means the non-zero value just read from the hash
1312 ** slot (aHash[iKey]) may have been added before or after the
1313 ** current read transaction was opened. Values added after the
1314 ** read transaction was opened may have been written incorrectly -
1315 ** i.e. these slots may contain garbage data. However, we assume
1316 ** that any slots written before the current read transaction was
1317 ** opened remain unmodified.
1318 **
1319 ** For the reasons above, the if(...) condition featured in the inner
1320 ** loop of the following block is more stringent that would be required
1321 ** if we had exclusive access to the hash-table:
1322 **
1323 ** (aPgno[iFrame]==pgno):
1324 ** This condition filters out normal hash-table collisions.
1325 **
1326 ** (iFrame<=iLast):
1327 ** This condition filters out entries that were added to the hash
1328 ** table after the current read-transaction had started.
1329 **
1330 ** (iFrame>iRead):
1331 ** This filters out a dangerous class of garbage data. The
1332 ** garbage hash slot may refer to a frame with the correct page
1333 ** number, but not the most recent version of the frame. For
1334 ** example, if at the start of the read-transaction the log
1335 ** contains three copies of the desired page in frames 2, 3 and 4,
1336 ** the hash table may contain the following:
1337 **
1338 ** { ..., 2, 3, 4, 0, 0, ..... }
1339 **
1340 ** The correct answer is to read data from frame 4. But a
1341 ** dirty-read may potentially cause the hash-table to appear as
1342 ** follows to the reader:
1343 **
1344 ** { ..., 2, 3, 4, 3, 0, ..... }
1345 **
1346 ** Without this part of the if(...) clause, the reader might
1347 ** incorrectly read data from frame 3 instead of 4. This would be
1348 ** an error.
1349 **
1350 ** It is not actually clear to the developers that such a dirty-read
1351 ** can occur. But if it does, it should not cause any problems.
dan7c246102010-04-12 19:00:29 +00001352 */
danbb23aff2010-05-10 14:46:09 +00001353 for(iHash=iLast; iHash>0 && iRead==0; iHash-=HASHTABLE_NPAGE){
drh5939f442010-05-18 13:27:12 +00001354 volatile HASHTABLE_DATATYPE *aHash; /* Pointer to hash table */
1355 volatile u32 *aPgno; /* Pointer to array of page numbers */
danbb23aff2010-05-10 14:46:09 +00001356 u32 iZero; /* Frame number corresponding to aPgno[0] */
1357 int iKey; /* Hash slot index */
drh29d4dbe2010-05-18 23:29:52 +00001358 int mxHash; /* upper bound on aHash[] values */
danbb23aff2010-05-10 14:46:09 +00001359
1360 walHashFind(pWal, iHash, &aHash, &aPgno, &iZero);
drh29d4dbe2010-05-18 23:29:52 +00001361 mxHash = iLast - iZero;
1362 if( mxHash > HASHTABLE_NPAGE ) mxHash = HASHTABLE_NPAGE;
1363 for(iKey=walHash(pgno); aHash[iKey]<=mxHash; iKey=walNextHash(iKey)){
danbb23aff2010-05-10 14:46:09 +00001364 u32 iFrame = aHash[iKey] + iZero;
drh29d4dbe2010-05-18 23:29:52 +00001365 if( ALWAYS(iFrame<=iLast) && aPgno[iFrame]==pgno && iFrame>iRead ){
danbb23aff2010-05-10 14:46:09 +00001366 iRead = iFrame;
1367 }
dan7c246102010-04-12 19:00:29 +00001368 }
1369 }
danbb23aff2010-05-10 14:46:09 +00001370 assert( iRead==0 || pWal->pWiData[walIndexEntry(iRead)]==pgno );
dan7c246102010-04-12 19:00:29 +00001371
danbb23aff2010-05-10 14:46:09 +00001372#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
1373 /* If expensive assert() statements are available, do a linear search
1374 ** of the wal-index file content. Make sure the results agree with the
1375 ** result obtained using the hash indexes above. */
1376 {
1377 u32 iRead2 = 0;
1378 u32 iTest;
1379 for(iTest=iLast; iTest>0; iTest--){
1380 if( pWal->pWiData[walIndexEntry(iTest)]==pgno ){
1381 iRead2 = iTest;
dan7c246102010-04-12 19:00:29 +00001382 break;
1383 }
dan7c246102010-04-12 19:00:29 +00001384 }
danbb23aff2010-05-10 14:46:09 +00001385 assert( iRead==iRead2 );
dan7c246102010-04-12 19:00:29 +00001386 }
danbb23aff2010-05-10 14:46:09 +00001387#endif
dancd11fb22010-04-26 10:40:52 +00001388
dan7c246102010-04-12 19:00:29 +00001389 /* If iRead is non-zero, then it is the log frame number that contains the
1390 ** required page. Read and return data from the log file.
1391 */
danbb23aff2010-05-10 14:46:09 +00001392 walIndexUnmap(pWal);
dan7c246102010-04-12 19:00:29 +00001393 if( iRead ){
drh7ed91f22010-04-29 22:34:07 +00001394 i64 iOffset = walFrameOffset(iRead, pWal->hdr.pgsz) + WAL_FRAME_HDRSIZE;
1395 *pInWal = 1;
drhd9e5c4f2010-05-12 18:01:39 +00001396 return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
dan7c246102010-04-12 19:00:29 +00001397 }
1398
drh7ed91f22010-04-29 22:34:07 +00001399 *pInWal = 0;
dan7c246102010-04-12 19:00:29 +00001400 return SQLITE_OK;
1401}
1402
1403
1404/*
1405** Set *pPgno to the size of the database file (or zero, if unknown).
1406*/
drh7ed91f22010-04-29 22:34:07 +00001407void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno){
1408 assert( pWal->lockState==SQLITE_SHM_READ
1409 || pWal->lockState==SQLITE_SHM_WRITE );
1410 *pPgno = pWal->hdr.nPage;
dan7c246102010-04-12 19:00:29 +00001411}
1412
1413/*
dan7c246102010-04-12 19:00:29 +00001414** This function returns SQLITE_OK if the caller may write to the database.
1415** Otherwise, if the caller is operating on a snapshot that has already
dan49320f82010-04-14 18:50:08 +00001416** been overwritten by another writer, SQLITE_BUSY is returned.
dan7c246102010-04-12 19:00:29 +00001417*/
drh7ed91f22010-04-29 22:34:07 +00001418int sqlite3WalWriteLock(Wal *pWal, int op){
drhe874d9e2010-05-07 20:02:23 +00001419 int rc = SQLITE_OK;
dan7c246102010-04-12 19:00:29 +00001420 if( op ){
daned360202010-05-12 06:54:31 +00001421 assert( pWal->lockState==SQLITE_SHM_READ );
drh7ed91f22010-04-29 22:34:07 +00001422 rc = walSetLock(pWal, SQLITE_SHM_WRITE);
dan30c86292010-04-30 16:24:46 +00001423
1424 /* If this connection is not reading the most recent database snapshot,
1425 ** it is not possible to write to the database. In this case release
1426 ** the write locks and return SQLITE_BUSY.
1427 */
1428 if( rc==SQLITE_OK ){
dan576bc322010-05-06 18:04:50 +00001429 rc = walIndexMap(pWal, sizeof(WalIndexHdr));
dan30c86292010-04-30 16:24:46 +00001430 if( rc==SQLITE_OK
drh5939f442010-05-18 13:27:12 +00001431 && memcmp(&pWal->hdr, (void*)pWal->pWiData, sizeof(WalIndexHdr))
dan30c86292010-04-30 16:24:46 +00001432 ){
1433 rc = SQLITE_BUSY;
1434 }
1435 walIndexUnmap(pWal);
1436 if( rc!=SQLITE_OK ){
1437 walSetLock(pWal, SQLITE_SHM_READ);
1438 }
1439 }
dan55437592010-05-11 12:19:26 +00001440 }else if( pWal->lockState==SQLITE_SHM_WRITE ){
drh7ed91f22010-04-29 22:34:07 +00001441 rc = walSetLock(pWal, SQLITE_SHM_READ);
dan7c246102010-04-12 19:00:29 +00001442 }
drh7ed91f22010-04-29 22:34:07 +00001443 return rc;
dan7c246102010-04-12 19:00:29 +00001444}
1445
dan74d6cd82010-04-24 18:44:05 +00001446/*
dan74d6cd82010-04-24 18:44:05 +00001447** If any data has been written (but not committed) to the log file, this
1448** function moves the write-pointer back to the start of the transaction.
1449**
1450** Additionally, the callback function is invoked for each frame written
1451** to the log since the start of the transaction. If the callback returns
1452** other than SQLITE_OK, it is not invoked again and the error code is
1453** returned to the caller.
1454**
1455** Otherwise, if the callback function does not return an error, this
1456** function returns SQLITE_OK.
1457*/
drh7ed91f22010-04-29 22:34:07 +00001458int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
dan55437592010-05-11 12:19:26 +00001459 int rc = SQLITE_OK;
1460 if( pWal->lockState==SQLITE_SHM_WRITE ){
1461 int unused;
drh027a1282010-05-19 01:53:53 +00001462 Pgno iMax = pWal->hdr.mxFrame;
dan55437592010-05-11 12:19:26 +00001463 Pgno iFrame;
1464
1465 assert( pWal->pWiData==0 );
1466 rc = walIndexReadHdr(pWal, &unused);
drh027a1282010-05-19 01:53:53 +00001467 for(iFrame=pWal->hdr.mxFrame+1; rc==SQLITE_OK && iFrame<=iMax; iFrame++){
dan55437592010-05-11 12:19:26 +00001468 assert( pWal->lockState==SQLITE_SHM_WRITE );
1469 rc = xUndo(pUndoCtx, pWal->pWiData[walIndexEntry(iFrame)]);
1470 }
1471 walIndexUnmap(pWal);
dan74d6cd82010-04-24 18:44:05 +00001472 }
1473 return rc;
1474}
1475
drh7ed91f22010-04-29 22:34:07 +00001476/* Return an integer that records the current (uncommitted) write
1477** position in the WAL
1478*/
1479u32 sqlite3WalSavepoint(Wal *pWal){
1480 assert( pWal->lockState==SQLITE_SHM_WRITE );
drh027a1282010-05-19 01:53:53 +00001481 return pWal->hdr.mxFrame;
dan4cd78b42010-04-26 16:57:10 +00001482}
1483
drh7ed91f22010-04-29 22:34:07 +00001484/* Move the write position of the WAL back to iFrame. Called in
1485** response to a ROLLBACK TO command.
1486*/
1487int sqlite3WalSavepointUndo(Wal *pWal, u32 iFrame){
dan4cd78b42010-04-26 16:57:10 +00001488 int rc = SQLITE_OK;
1489 u8 aCksum[8];
drh7ed91f22010-04-29 22:34:07 +00001490 assert( pWal->lockState==SQLITE_SHM_WRITE );
dan4cd78b42010-04-26 16:57:10 +00001491
drh027a1282010-05-19 01:53:53 +00001492 pWal->hdr.mxFrame = iFrame;
dan4cd78b42010-04-26 16:57:10 +00001493 if( iFrame>0 ){
drh7ed91f22010-04-29 22:34:07 +00001494 i64 iOffset = walFrameOffset(iFrame, pWal->hdr.pgsz) + sizeof(u32)*2;
drhd9e5c4f2010-05-12 18:01:39 +00001495 rc = sqlite3OsRead(pWal->pWalFd, aCksum, sizeof(aCksum), iOffset);
drh7ed91f22010-04-29 22:34:07 +00001496 pWal->hdr.iCheck1 = sqlite3Get4byte(&aCksum[0]);
1497 pWal->hdr.iCheck2 = sqlite3Get4byte(&aCksum[4]);
dan4cd78b42010-04-26 16:57:10 +00001498 }
1499
1500 return rc;
1501}
1502
dan7c246102010-04-12 19:00:29 +00001503/*
dan4cd78b42010-04-26 16:57:10 +00001504** Write a set of frames to the log. The caller must hold the write-lock
1505** on the log file (obtained using sqlite3WalWriteLock()).
dan7c246102010-04-12 19:00:29 +00001506*/
drhc438efd2010-04-26 00:19:45 +00001507int sqlite3WalFrames(
drh7ed91f22010-04-29 22:34:07 +00001508 Wal *pWal, /* Wal handle to write to */
dan7c246102010-04-12 19:00:29 +00001509 int nPgsz, /* Database page-size in bytes */
1510 PgHdr *pList, /* List of dirty pages to write */
1511 Pgno nTruncate, /* Database size after this commit */
1512 int isCommit, /* True if this is a commit */
danc5118782010-04-17 17:34:41 +00001513 int sync_flags /* Flags to pass to OsSync() (or 0) */
dan7c246102010-04-12 19:00:29 +00001514){
dan7c246102010-04-12 19:00:29 +00001515 int rc; /* Used to catch return codes */
1516 u32 iFrame; /* Next frame address */
drh7ed91f22010-04-29 22:34:07 +00001517 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
dan7c246102010-04-12 19:00:29 +00001518 PgHdr *p; /* Iterator to run through pList with. */
dan97a31352010-04-16 13:59:31 +00001519 u32 aCksum[2]; /* Checksums */
drhe874d9e2010-05-07 20:02:23 +00001520 PgHdr *pLast = 0; /* Last frame in list */
dan7c246102010-04-12 19:00:29 +00001521 int nLast = 0; /* Number of extra copies of last page */
1522
drh7ed91f22010-04-29 22:34:07 +00001523 assert( WAL_FRAME_HDRSIZE==(4 * 2 + 2*sizeof(u32)) );
dan7c246102010-04-12 19:00:29 +00001524 assert( pList );
drh7ed91f22010-04-29 22:34:07 +00001525 assert( pWal->lockState==SQLITE_SHM_WRITE );
danba515902010-04-30 09:32:06 +00001526 assert( pWal->pWiData==0 );
dan7c246102010-04-12 19:00:29 +00001527
drha2a42012010-05-18 18:01:08 +00001528 /* If this is the first frame written into the log, write the WAL
1529 ** header to the start of the WAL file. See comments at the top of
1530 ** this source file for a description of the WAL header format.
dan97a31352010-04-16 13:59:31 +00001531 */
drh7ed91f22010-04-29 22:34:07 +00001532 assert( WAL_FRAME_HDRSIZE>=WAL_HDRSIZE );
drh027a1282010-05-19 01:53:53 +00001533 iFrame = pWal->hdr.mxFrame;
dan97a31352010-04-16 13:59:31 +00001534 if( iFrame==0 ){
1535 sqlite3Put4byte(aFrame, nPgsz);
1536 sqlite3_randomness(8, &aFrame[4]);
drh7ed91f22010-04-29 22:34:07 +00001537 pWal->hdr.iCheck1 = sqlite3Get4byte(&aFrame[4]);
1538 pWal->hdr.iCheck2 = sqlite3Get4byte(&aFrame[8]);
drhd9e5c4f2010-05-12 18:01:39 +00001539 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, WAL_HDRSIZE, 0);
dan97a31352010-04-16 13:59:31 +00001540 if( rc!=SQLITE_OK ){
1541 return rc;
1542 }
1543 }
1544
drh7ed91f22010-04-29 22:34:07 +00001545 aCksum[0] = pWal->hdr.iCheck1;
1546 aCksum[1] = pWal->hdr.iCheck2;
dan7c246102010-04-12 19:00:29 +00001547
1548 /* Write the log file. */
dan7c246102010-04-12 19:00:29 +00001549 for(p=pList; p; p=p->pDirty){
1550 u32 nDbsize; /* Db-size field for frame header */
1551 i64 iOffset; /* Write offset in log file */
1552
drh7ed91f22010-04-29 22:34:07 +00001553 iOffset = walFrameOffset(++iFrame, nPgsz);
dan7c246102010-04-12 19:00:29 +00001554
1555 /* Populate and write the frame header */
1556 nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
drh7ed91f22010-04-29 22:34:07 +00001557 walEncodeFrame(aCksum, p->pgno, nDbsize, nPgsz, p->pData, aFrame);
drhd9e5c4f2010-05-12 18:01:39 +00001558 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
dan7c246102010-04-12 19:00:29 +00001559 if( rc!=SQLITE_OK ){
1560 return rc;
1561 }
1562
1563 /* Write the page data */
drha2a42012010-05-18 18:01:08 +00001564 rc = sqlite3OsWrite(pWal->pWalFd, p->pData, nPgsz, iOffset+sizeof(aFrame));
dan7c246102010-04-12 19:00:29 +00001565 if( rc!=SQLITE_OK ){
1566 return rc;
1567 }
1568 pLast = p;
1569 }
1570
1571 /* Sync the log file if the 'isSync' flag was specified. */
danc5118782010-04-17 17:34:41 +00001572 if( sync_flags ){
drhd9e5c4f2010-05-12 18:01:39 +00001573 i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
drh7ed91f22010-04-29 22:34:07 +00001574 i64 iOffset = walFrameOffset(iFrame+1, nPgsz);
dan67032392010-04-17 15:42:43 +00001575
1576 assert( isCommit );
drh69c46962010-05-17 20:16:50 +00001577 assert( iSegment>0 );
dan7c246102010-04-12 19:00:29 +00001578
dan7c246102010-04-12 19:00:29 +00001579 iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
1580 while( iOffset<iSegment ){
drh7ed91f22010-04-29 22:34:07 +00001581 walEncodeFrame(aCksum,pLast->pgno,nTruncate,nPgsz,pLast->pData,aFrame);
drhd9e5c4f2010-05-12 18:01:39 +00001582 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
dan7c246102010-04-12 19:00:29 +00001583 if( rc!=SQLITE_OK ){
1584 return rc;
1585 }
1586
drh7ed91f22010-04-29 22:34:07 +00001587 iOffset += WAL_FRAME_HDRSIZE;
drhd9e5c4f2010-05-12 18:01:39 +00001588 rc = sqlite3OsWrite(pWal->pWalFd, pLast->pData, nPgsz, iOffset);
dan7c246102010-04-12 19:00:29 +00001589 if( rc!=SQLITE_OK ){
1590 return rc;
1591 }
1592 nLast++;
1593 iOffset += nPgsz;
1594 }
dan7c246102010-04-12 19:00:29 +00001595
drhd9e5c4f2010-05-12 18:01:39 +00001596 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
dan7c246102010-04-12 19:00:29 +00001597 }
danba515902010-04-30 09:32:06 +00001598 assert( pWal->pWiData==0 );
dan7c246102010-04-12 19:00:29 +00001599
drhe730fec2010-05-18 12:56:50 +00001600 /* Append data to the wal-index. It is not necessary to lock the
drha2a42012010-05-18 18:01:08 +00001601 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
dan7c246102010-04-12 19:00:29 +00001602 ** guarantees that there are no other writers, and no data that may
1603 ** be in use by existing readers is being overwritten.
1604 */
drh027a1282010-05-19 01:53:53 +00001605 iFrame = pWal->hdr.mxFrame;
danc7991bd2010-05-05 19:04:59 +00001606 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
dan7c246102010-04-12 19:00:29 +00001607 iFrame++;
danc7991bd2010-05-05 19:04:59 +00001608 rc = walIndexAppend(pWal, iFrame, p->pgno);
dan7c246102010-04-12 19:00:29 +00001609 }
danc7991bd2010-05-05 19:04:59 +00001610 while( nLast>0 && rc==SQLITE_OK ){
dan7c246102010-04-12 19:00:29 +00001611 iFrame++;
1612 nLast--;
danc7991bd2010-05-05 19:04:59 +00001613 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
dan7c246102010-04-12 19:00:29 +00001614 }
1615
danc7991bd2010-05-05 19:04:59 +00001616 if( rc==SQLITE_OK ){
1617 /* Update the private copy of the header. */
1618 pWal->hdr.pgsz = nPgsz;
drh027a1282010-05-19 01:53:53 +00001619 pWal->hdr.mxFrame = iFrame;
danc7991bd2010-05-05 19:04:59 +00001620 if( isCommit ){
1621 pWal->hdr.iChange++;
1622 pWal->hdr.nPage = nTruncate;
1623 }
1624 pWal->hdr.iCheck1 = aCksum[0];
1625 pWal->hdr.iCheck2 = aCksum[1];
dan7c246102010-04-12 19:00:29 +00001626
danc7991bd2010-05-05 19:04:59 +00001627 /* If this is a commit, update the wal-index header too. */
1628 if( isCommit ){
1629 walIndexWriteHdr(pWal, &pWal->hdr);
1630 pWal->iCallback = iFrame;
1631 }
dan7c246102010-04-12 19:00:29 +00001632 }
danc7991bd2010-05-05 19:04:59 +00001633
drh7ed91f22010-04-29 22:34:07 +00001634 walIndexUnmap(pWal);
dan8d22a172010-04-19 18:03:51 +00001635 return rc;
dan7c246102010-04-12 19:00:29 +00001636}
1637
1638/*
danb9bf16b2010-04-14 11:23:30 +00001639** Checkpoint the database:
1640**
drh7ed91f22010-04-29 22:34:07 +00001641** 1. Acquire a CHECKPOINT lock
1642** 2. Copy the contents of the log into the database file.
1643** 3. Zero the wal-index header (so new readers will ignore the log).
1644** 4. Drop the CHECKPOINT lock.
dan7c246102010-04-12 19:00:29 +00001645*/
drhc438efd2010-04-26 00:19:45 +00001646int sqlite3WalCheckpoint(
drh7ed91f22010-04-29 22:34:07 +00001647 Wal *pWal, /* Wal connection */
danc5118782010-04-17 17:34:41 +00001648 int sync_flags, /* Flags to sync db file with (or 0) */
danb6e099a2010-05-04 14:47:39 +00001649 int nBuf, /* Size of temporary buffer */
dan64d039e2010-04-13 19:27:31 +00001650 u8 *zBuf, /* Temporary buffer to use */
1651 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
1652 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
dan7c246102010-04-12 19:00:29 +00001653){
danb9bf16b2010-04-14 11:23:30 +00001654 int rc; /* Return code */
dan31c03902010-04-29 14:51:33 +00001655 int isChanged = 0; /* True if a new wal-index header is loaded */
dan7c246102010-04-12 19:00:29 +00001656
dan5cf53532010-05-01 16:40:20 +00001657 assert( pWal->pWiData==0 );
dan39c79f52010-04-15 10:58:51 +00001658
daned360202010-05-12 06:54:31 +00001659 /* Get the CHECKPOINT lock.
1660 **
1661 ** Normally, the connection will be in UNLOCK state at this point. But
1662 ** if the connection is in exclusive-mode it may still be in READ state
1663 ** even though the upper layer has no active read-transaction (because
1664 ** WalCloseSnapshot() is not called in exclusive mode). The state will
1665 ** be set to UNLOCK when this function returns. This is Ok.
1666 */
1667 assert( (pWal->lockState==SQLITE_SHM_UNLOCK)
drh5cccc942010-05-13 15:44:00 +00001668 || (pWal->lockState==SQLITE_SHM_READ) );
1669 walSetLock(pWal, SQLITE_SHM_UNLOCK);
dan64d039e2010-04-13 19:27:31 +00001670 do {
drh7ed91f22010-04-29 22:34:07 +00001671 rc = walSetLock(pWal, SQLITE_SHM_CHECKPOINT);
dan64d039e2010-04-13 19:27:31 +00001672 }while( rc==SQLITE_BUSY && xBusyHandler(pBusyHandlerArg) );
danb9bf16b2010-04-14 11:23:30 +00001673 if( rc!=SQLITE_OK ){
drh7ed91f22010-04-29 22:34:07 +00001674 walSetLock(pWal, SQLITE_SHM_UNLOCK);
danb9bf16b2010-04-14 11:23:30 +00001675 return rc;
1676 }
dan64d039e2010-04-13 19:27:31 +00001677
danb9bf16b2010-04-14 11:23:30 +00001678 /* Copy data from the log to the database file. */
drh7ed91f22010-04-29 22:34:07 +00001679 rc = walIndexReadHdr(pWal, &isChanged);
danb9bf16b2010-04-14 11:23:30 +00001680 if( rc==SQLITE_OK ){
drhd9e5c4f2010-05-12 18:01:39 +00001681 rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
danb9bf16b2010-04-14 11:23:30 +00001682 }
dan31c03902010-04-29 14:51:33 +00001683 if( isChanged ){
1684 /* If a new wal-index header was loaded before the checkpoint was
drha2a42012010-05-18 18:01:08 +00001685 ** performed, then the pager-cache associated with pWal is now
dan31c03902010-04-29 14:51:33 +00001686 ** out of date. So zero the cached wal-index header to ensure that
1687 ** next time the pager opens a snapshot on this database it knows that
1688 ** the cache needs to be reset.
1689 */
drh7ed91f22010-04-29 22:34:07 +00001690 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
dan31c03902010-04-29 14:51:33 +00001691 }
danb9bf16b2010-04-14 11:23:30 +00001692
1693 /* Release the locks. */
dan87bfb512010-04-30 11:43:28 +00001694 walIndexUnmap(pWal);
drh7ed91f22010-04-29 22:34:07 +00001695 walSetLock(pWal, SQLITE_SHM_UNLOCK);
dan64d039e2010-04-13 19:27:31 +00001696 return rc;
dan7c246102010-04-12 19:00:29 +00001697}
1698
drh7ed91f22010-04-29 22:34:07 +00001699/* Return the value to pass to a sqlite3_wal_hook callback, the
1700** number of frames in the WAL at the point of the last commit since
1701** sqlite3WalCallback() was called. If no commits have occurred since
1702** the last call, then return 0.
1703*/
1704int sqlite3WalCallback(Wal *pWal){
dan8d22a172010-04-19 18:03:51 +00001705 u32 ret = 0;
drh7ed91f22010-04-29 22:34:07 +00001706 if( pWal ){
1707 ret = pWal->iCallback;
1708 pWal->iCallback = 0;
dan8d22a172010-04-19 18:03:51 +00001709 }
1710 return (int)ret;
1711}
dan55437592010-05-11 12:19:26 +00001712
1713/*
1714** This function is called to set or query the exclusive-mode flag
1715** associated with the WAL connection passed as the first argument. The
1716** exclusive-mode flag should be set to indicate that the caller is
1717** holding an EXCLUSIVE lock on the database file (it does this in
1718** locking_mode=exclusive mode). If the EXCLUSIVE lock is to be dropped,
1719** the flag set by this function should be cleared before doing so.
1720**
1721** The value of the exclusive-mode flag may only be modified when
1722** the WAL connection is in READ state.
1723**
1724** When the flag is set, this module does not call the VFS xShmLock()
1725** method to obtain any locks on the wal-index (as it assumes it
1726** has exclusive access to the wal and wal-index files anyhow). It
1727** continues to hold (and does not drop) the existing READ lock on
1728** the wal-index.
1729**
1730** To set or clear the flag, the "op" parameter is passed 1 or 0,
1731** respectively. To query the flag, pass -1. In all cases, the value
1732** returned is the value of the exclusive-mode flag (after its value
1733** has been modified, if applicable).
1734*/
1735int sqlite3WalExclusiveMode(Wal *pWal, int op){
1736 if( op>=0 ){
1737 assert( pWal->lockState==SQLITE_SHM_READ );
1738 pWal->exclusiveMode = (u8)op;
1739 }
1740 return pWal->exclusiveMode;
1741}
1742
dan5cf53532010-05-01 16:40:20 +00001743#endif /* #ifndef SQLITE_OMIT_WAL */