blob: dbac31ae3507e8dfe5e6334f4edac8303f44c448 [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/*
drhc74c3332010-05-31 12:15:19 +0000227** Trace output macros
228*/
drhc74c3332010-05-31 12:15:19 +0000229#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh15d68092010-05-31 16:56:14 +0000230int sqlite3WalTrace = 0;
drhc74c3332010-05-31 12:15:19 +0000231# define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
232#else
233# define WALTRACE(X)
234#endif
235
236
237/*
drh73b64e42010-05-30 19:55:15 +0000238** Indices of various locking bytes. WAL_NREADER is the number
239** of available reader locks and should be at least 3.
240*/
241#define WAL_WRITE_LOCK 0
242#define WAL_ALL_BUT_WRITE 1
243#define WAL_CKPT_LOCK 1
244#define WAL_RECOVER_LOCK 2
245#define WAL_READ_LOCK(I) (3+(I))
246#define WAL_NREADER (SQLITE_SHM_NLOCK-3)
247
dan97a31352010-04-16 13:59:31 +0000248
drh7ed91f22010-04-29 22:34:07 +0000249/* Object declarations */
250typedef struct WalIndexHdr WalIndexHdr;
251typedef struct WalIterator WalIterator;
drh73b64e42010-05-30 19:55:15 +0000252typedef struct WalCkptInfo WalCkptInfo;
dan7c246102010-04-12 19:00:29 +0000253
254
255/*
drh286a2882010-05-20 23:51:06 +0000256** The following object holds a copy of the wal-index header content.
257**
258** The actual header in the wal-index consists of two copies of this
259** object.
dan7c246102010-04-12 19:00:29 +0000260*/
drh7ed91f22010-04-29 22:34:07 +0000261struct WalIndexHdr {
dan71d89912010-05-24 13:57:42 +0000262 u32 iChange; /* Counter incremented each transaction */
drh4b82c382010-05-31 18:24:19 +0000263 u8 isInit; /* 1 when initialized */
264 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
dan71d89912010-05-24 13:57:42 +0000265 u16 szPage; /* Database page size in bytes */
dand0aa3422010-05-31 16:41:53 +0000266 u32 mxFrame; /* Index of last valid frame in the WAL */
dan71d89912010-05-24 13:57:42 +0000267 u32 nPage; /* Size of database in pages */
268 u32 aFrameCksum[2]; /* Checksum of last frame in log */
269 u32 aSalt[2]; /* Two salt values copied from WAL header */
270 u32 aCksum[2]; /* Checksum over all prior fields */
dan7c246102010-04-12 19:00:29 +0000271};
272
drh73b64e42010-05-30 19:55:15 +0000273/*
274** A copy of the following object occurs in the wal-index immediately
275** following the second copy of the WalIndexHdr. This object stores
276** information used by checkpoint.
277**
278** nBackfill is the number of frames in the WAL that have been written
279** back into the database. (We call the act of moving content from WAL to
280** database "backfilling".) The nBackfill number is never greater than
281** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
282** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
283** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
284** mxFrame back to zero when the WAL is reset.
285**
286** There is one entry in aReadMark[] for each reader lock. If a reader
287** holds read-lock K, then the value in aReadMark[K] is no greater than
288** the mxFrame for that reader. aReadMark[0] is a special case. It
289** always holds zero. Readers holding WAL_READ_LOCK(0) always ignore
290** the entire WAL and read all content directly from the database.
291**
292** The value of aReadMark[K] may only be changed by a thread that
293** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
294** aReadMark[K] cannot changed while there is a reader is using that mark
295** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
296**
297** The checkpointer may only transfer frames from WAL to database where
298** the frame numbers are less than or equal to every aReadMark[] that is
299** in use (that is, every aReadMark[j] for which there is a corresponding
300** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
301** largest value and will increase an unused aReadMark[] to mxFrame if there
302** is not already an aReadMark[] equal to mxFrame. The exception to the
303** previous sentence is when nBackfill equals mxFrame (meaning that everything
304** in the WAL has been backfilled into the database) then new readers
305** will choose aReadMark[0] which has value 0 and hence such reader will
306** get all their all content directly from the database file and ignore
307** the WAL.
308**
309** Writers normally append new frames to the end of the WAL. However,
310** if nBackfill equals mxFrame (meaning that all WAL content has been
311** written back into the database) and if no readers are using the WAL
312** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
313** the writer will first "reset" the WAL back to the beginning and start
314** writing new content beginning at frame 1.
315**
316** We assume that 32-bit loads are atomic and so no locks are needed in
317** order to read from any aReadMark[] entries.
318*/
319struct WalCkptInfo {
320 u32 nBackfill; /* Number of WAL frames backfilled into DB */
321 u32 aReadMark[WAL_NREADER]; /* Reader marks */
322};
323
324
drh7e263722010-05-20 21:21:09 +0000325/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
326** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
327** only support mandatory file-locks, we do not read or write data
328** from the region of the file on which locks are applied.
danff207012010-04-24 04:49:15 +0000329*/
drh73b64e42010-05-30 19:55:15 +0000330#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
331#define WALINDEX_LOCK_RESERVED 16
drh026ac282010-05-26 15:06:38 +0000332#define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
dan7c246102010-04-12 19:00:29 +0000333
drh7ed91f22010-04-29 22:34:07 +0000334/* Size of header before each frame in wal */
drh23ea97b2010-05-20 16:45:58 +0000335#define WAL_FRAME_HDRSIZE 24
danff207012010-04-24 04:49:15 +0000336
drh7ed91f22010-04-29 22:34:07 +0000337/* Size of write ahead log header */
drh23ea97b2010-05-20 16:45:58 +0000338#define WAL_HDRSIZE 24
dan97a31352010-04-16 13:59:31 +0000339
danb8fd6c22010-05-24 10:39:36 +0000340/* WAL magic value. Either this value, or the same value with the least
341** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
342** big-endian format in the first 4 bytes of a WAL file.
343**
344** If the LSB is set, then the checksums for each frame within the WAL
345** file are calculated by treating all data as an array of 32-bit
346** big-endian words. Otherwise, they are calculated by interpreting
347** all data as 32-bit little-endian words.
348*/
349#define WAL_MAGIC 0x377f0682
350
dan97a31352010-04-16 13:59:31 +0000351/*
drh7ed91f22010-04-29 22:34:07 +0000352** Return the offset of frame iFrame in the write-ahead log file,
drh6e810962010-05-19 17:49:50 +0000353** assuming a database page size of szPage bytes. The offset returned
drh7ed91f22010-04-29 22:34:07 +0000354** is to the start of the write-ahead log frame-header.
dan97a31352010-04-16 13:59:31 +0000355*/
drh6e810962010-05-19 17:49:50 +0000356#define walFrameOffset(iFrame, szPage) ( \
357 WAL_HDRSIZE + ((iFrame)-1)*((szPage)+WAL_FRAME_HDRSIZE) \
dan97a31352010-04-16 13:59:31 +0000358)
dan7c246102010-04-12 19:00:29 +0000359
360/*
drh7ed91f22010-04-29 22:34:07 +0000361** An open write-ahead log file is represented by an instance of the
362** following object.
dance4f05f2010-04-22 19:14:13 +0000363*/
drh7ed91f22010-04-29 22:34:07 +0000364struct Wal {
drh73b64e42010-05-30 19:55:15 +0000365 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
drhd9e5c4f2010-05-12 18:01:39 +0000366 sqlite3_file *pDbFd; /* File handle for the database file */
367 sqlite3_file *pWalFd; /* File handle for WAL file */
drh7ed91f22010-04-29 22:34:07 +0000368 u32 iCallback; /* Value to pass to log callback (or 0) */
drh5530b762010-04-30 14:39:50 +0000369 int szWIndex; /* Size of the wal-index that is mapped in mem */
drh5939f442010-05-18 13:27:12 +0000370 volatile u32 *pWiData; /* Pointer to wal-index content in memory */
drh73b64e42010-05-30 19:55:15 +0000371 u16 szPage; /* Database page size */
372 i16 readLock; /* Which read lock is being held. -1 for none */
dan55437592010-05-11 12:19:26 +0000373 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
drh73b64e42010-05-30 19:55:15 +0000374 u8 isWIndexOpen; /* True if ShmOpen() called on pDbFd */
375 u8 writeLock; /* True if in a write transaction */
376 u8 ckptLock; /* True if holding a checkpoint lock */
377 WalIndexHdr hdr; /* Wal-index header for current transaction */
drhd9e5c4f2010-05-12 18:01:39 +0000378 char *zWalName; /* Name of WAL file */
drh7e263722010-05-20 21:21:09 +0000379 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
dan7c246102010-04-12 19:00:29 +0000380};
381
drh73b64e42010-05-30 19:55:15 +0000382/*
383** Return a pointer to the WalCkptInfo structure in the wal-index.
384*/
385static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
386 assert( pWal->pWiData!=0 );
387 return (volatile WalCkptInfo*)&pWal->pWiData[sizeof(WalIndexHdr)/2];
388}
389
dan64d039e2010-04-13 19:27:31 +0000390
dan7c246102010-04-12 19:00:29 +0000391/*
drha2a42012010-05-18 18:01:08 +0000392** This structure is used to implement an iterator that loops through
393** all frames in the WAL in database page order. Where two or more frames
dan7c246102010-04-12 19:00:29 +0000394** correspond to the same database page, the iterator visits only the
drha2a42012010-05-18 18:01:08 +0000395** frame most recently written to the WAL (in other words, the frame with
396** the largest index).
dan7c246102010-04-12 19:00:29 +0000397**
398** The internals of this structure are only accessed by:
399**
drh7ed91f22010-04-29 22:34:07 +0000400** walIteratorInit() - Create a new iterator,
401** walIteratorNext() - Step an iterator,
402** walIteratorFree() - Free an iterator.
dan7c246102010-04-12 19:00:29 +0000403**
drh7ed91f22010-04-29 22:34:07 +0000404** This functionality is used by the checkpoint code (see walCheckpoint()).
dan7c246102010-04-12 19:00:29 +0000405*/
drh7ed91f22010-04-29 22:34:07 +0000406struct WalIterator {
drha2a42012010-05-18 18:01:08 +0000407 int iPrior; /* Last result returned from the iterator */
408 int nSegment; /* Size of the aSegment[] array */
409 int nFinal; /* Elements in aSegment[nSegment-1] */
drh7ed91f22010-04-29 22:34:07 +0000410 struct WalSegment {
drha2a42012010-05-18 18:01:08 +0000411 int iNext; /* Next slot in aIndex[] not previously returned */
412 u8 *aIndex; /* i0, i1, i2... such that aPgno[iN] ascending */
413 u32 *aPgno; /* 256 page numbers. Pointer to Wal.pWiData */
414 } aSegment[1]; /* One for every 256 entries in the WAL */
dan7c246102010-04-12 19:00:29 +0000415};
416
danb8fd6c22010-05-24 10:39:36 +0000417/*
418** The argument to this macro must be of type u32. On a little-endian
419** architecture, it returns the u32 value that results from interpreting
420** the 4 bytes as a big-endian value. On a big-endian architecture, it
421** returns the value that would be produced by intepreting the 4 bytes
422** of the input value as a little-endian integer.
423*/
424#define BYTESWAP32(x) ( \
425 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
426 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
427)
dan64d039e2010-04-13 19:27:31 +0000428
dan7c246102010-04-12 19:00:29 +0000429/*
drh7e263722010-05-20 21:21:09 +0000430** Generate or extend an 8 byte checksum based on the data in
431** array aByte[] and the initial values of aIn[0] and aIn[1] (or
432** initial values of 0 and 0 if aIn==NULL).
433**
434** The checksum is written back into aOut[] before returning.
435**
436** nByte must be a positive multiple of 8.
dan7c246102010-04-12 19:00:29 +0000437*/
drh7e263722010-05-20 21:21:09 +0000438static void walChecksumBytes(
danb8fd6c22010-05-24 10:39:36 +0000439 int nativeCksum, /* True for native byte-order, false for non-native */
drh7e263722010-05-20 21:21:09 +0000440 u8 *a, /* Content to be checksummed */
441 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
442 const u32 *aIn, /* Initial checksum value input */
443 u32 *aOut /* OUT: Final checksum value output */
444){
445 u32 s1, s2;
danb8fd6c22010-05-24 10:39:36 +0000446 u32 *aData = (u32 *)a;
447 u32 *aEnd = (u32 *)&a[nByte];
448
drh7e263722010-05-20 21:21:09 +0000449 if( aIn ){
450 s1 = aIn[0];
451 s2 = aIn[1];
452 }else{
453 s1 = s2 = 0;
454 }
dan7c246102010-04-12 19:00:29 +0000455
drh584c7542010-05-19 18:08:10 +0000456 assert( nByte>=8 );
danb8fd6c22010-05-24 10:39:36 +0000457 assert( (nByte&0x00000007)==0 );
dan7c246102010-04-12 19:00:29 +0000458
danb8fd6c22010-05-24 10:39:36 +0000459 if( nativeCksum ){
460 do {
461 s1 += *aData++ + s2;
462 s2 += *aData++ + s1;
463 }while( aData<aEnd );
464 }else{
465 do {
466 s1 += BYTESWAP32(aData[0]) + s2;
467 s2 += BYTESWAP32(aData[1]) + s1;
468 aData += 2;
469 }while( aData<aEnd );
470 }
471
drh7e263722010-05-20 21:21:09 +0000472 aOut[0] = s1;
473 aOut[1] = s2;
dan7c246102010-04-12 19:00:29 +0000474}
475
476/*
drh7e263722010-05-20 21:21:09 +0000477** Write the header information in pWal->hdr into the wal-index.
478**
479** The checksum on pWal->hdr is updated before it is written.
drh7ed91f22010-04-29 22:34:07 +0000480*/
drh7e263722010-05-20 21:21:09 +0000481static void walIndexWriteHdr(Wal *pWal){
drh286a2882010-05-20 23:51:06 +0000482 WalIndexHdr *aHdr;
drh73b64e42010-05-30 19:55:15 +0000483
484 assert( pWal->writeLock );
drh4b82c382010-05-31 18:24:19 +0000485 pWal->hdr.isInit = 1;
drh73b64e42010-05-30 19:55:15 +0000486 walChecksumBytes(1, (u8*)&pWal->hdr, offsetof(WalIndexHdr, aCksum),
drh7e263722010-05-20 21:21:09 +0000487 0, pWal->hdr.aCksum);
drh286a2882010-05-20 23:51:06 +0000488 aHdr = (WalIndexHdr*)pWal->pWiData;
drh73b64e42010-05-30 19:55:15 +0000489 memcpy(&aHdr[1], &pWal->hdr, sizeof(WalIndexHdr));
drh286a2882010-05-20 23:51:06 +0000490 sqlite3OsShmBarrier(pWal->pDbFd);
drh73b64e42010-05-30 19:55:15 +0000491 memcpy(&aHdr[0], &pWal->hdr, sizeof(WalIndexHdr));
dan7c246102010-04-12 19:00:29 +0000492}
493
494/*
495** This function encodes a single frame header and writes it to a buffer
drh7ed91f22010-04-29 22:34:07 +0000496** supplied by the caller. A frame-header is made up of a series of
dan7c246102010-04-12 19:00:29 +0000497** 4-byte big-endian integers, as follows:
498**
drh23ea97b2010-05-20 16:45:58 +0000499** 0: Page number.
500** 4: For commit records, the size of the database image in pages
501** after the commit. For all other records, zero.
drh7e263722010-05-20 21:21:09 +0000502** 8: Salt-1 (copied from the wal-header)
503** 12: Salt-2 (copied from the wal-header)
drh23ea97b2010-05-20 16:45:58 +0000504** 16: Checksum-1.
505** 20: Checksum-2.
dan7c246102010-04-12 19:00:29 +0000506*/
drh7ed91f22010-04-29 22:34:07 +0000507static void walEncodeFrame(
drh23ea97b2010-05-20 16:45:58 +0000508 Wal *pWal, /* The write-ahead log */
dan7c246102010-04-12 19:00:29 +0000509 u32 iPage, /* Database page number for frame */
510 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
drh7e263722010-05-20 21:21:09 +0000511 u8 *aData, /* Pointer to page data */
dan7c246102010-04-12 19:00:29 +0000512 u8 *aFrame /* OUT: Write encoded frame here */
513){
danb8fd6c22010-05-24 10:39:36 +0000514 int nativeCksum; /* True for native byte-order checksums */
dan71d89912010-05-24 13:57:42 +0000515 u32 *aCksum = pWal->hdr.aFrameCksum;
drh23ea97b2010-05-20 16:45:58 +0000516 assert( WAL_FRAME_HDRSIZE==24 );
dan97a31352010-04-16 13:59:31 +0000517 sqlite3Put4byte(&aFrame[0], iPage);
518 sqlite3Put4byte(&aFrame[4], nTruncate);
drh7e263722010-05-20 21:21:09 +0000519 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
dan7c246102010-04-12 19:00:29 +0000520
danb8fd6c22010-05-24 10:39:36 +0000521 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
dan71d89912010-05-24 13:57:42 +0000522 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
danb8fd6c22010-05-24 10:39:36 +0000523 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
dan7c246102010-04-12 19:00:29 +0000524
drh23ea97b2010-05-20 16:45:58 +0000525 sqlite3Put4byte(&aFrame[16], aCksum[0]);
526 sqlite3Put4byte(&aFrame[20], aCksum[1]);
dan7c246102010-04-12 19:00:29 +0000527}
528
529/*
drh7e263722010-05-20 21:21:09 +0000530** Check to see if the frame with header in aFrame[] and content
531** in aData[] is valid. If it is a valid frame, fill *piPage and
532** *pnTruncate and return true. Return if the frame is not valid.
dan7c246102010-04-12 19:00:29 +0000533*/
drh7ed91f22010-04-29 22:34:07 +0000534static int walDecodeFrame(
drh23ea97b2010-05-20 16:45:58 +0000535 Wal *pWal, /* The write-ahead log */
dan7c246102010-04-12 19:00:29 +0000536 u32 *piPage, /* OUT: Database page number for frame */
537 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
dan7c246102010-04-12 19:00:29 +0000538 u8 *aData, /* Pointer to page data (for checksum) */
539 u8 *aFrame /* Frame data */
540){
danb8fd6c22010-05-24 10:39:36 +0000541 int nativeCksum; /* True for native byte-order checksums */
dan71d89912010-05-24 13:57:42 +0000542 u32 *aCksum = pWal->hdr.aFrameCksum;
drhc8179152010-05-24 13:28:36 +0000543 u32 pgno; /* Page number of the frame */
drh23ea97b2010-05-20 16:45:58 +0000544 assert( WAL_FRAME_HDRSIZE==24 );
545
drh7e263722010-05-20 21:21:09 +0000546 /* A frame is only valid if the salt values in the frame-header
547 ** match the salt values in the wal-header.
548 */
549 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
drh23ea97b2010-05-20 16:45:58 +0000550 return 0;
551 }
dan4a4b01d2010-04-16 11:30:18 +0000552
drhc8179152010-05-24 13:28:36 +0000553 /* A frame is only valid if the page number is creater than zero.
554 */
555 pgno = sqlite3Get4byte(&aFrame[0]);
556 if( pgno==0 ){
557 return 0;
558 }
559
drh7e263722010-05-20 21:21:09 +0000560 /* A frame is only valid if a checksum of the first 16 bytes
561 ** of the frame-header, and the frame-data matches
562 ** the checksum in the last 8 bytes of the frame-header.
563 */
danb8fd6c22010-05-24 10:39:36 +0000564 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
dan71d89912010-05-24 13:57:42 +0000565 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
danb8fd6c22010-05-24 10:39:36 +0000566 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
drh23ea97b2010-05-20 16:45:58 +0000567 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
568 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
dan7c246102010-04-12 19:00:29 +0000569 ){
570 /* Checksum failed. */
571 return 0;
572 }
573
drh7e263722010-05-20 21:21:09 +0000574 /* If we reach this point, the frame is valid. Return the page number
575 ** and the new database size.
576 */
drhc8179152010-05-24 13:28:36 +0000577 *piPage = pgno;
dan97a31352010-04-16 13:59:31 +0000578 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
dan7c246102010-04-12 19:00:29 +0000579 return 1;
580}
581
danbb23aff2010-05-10 14:46:09 +0000582/*
drh29d4dbe2010-05-18 23:29:52 +0000583** Define the parameters of the hash tables in the wal-index file. There
danbb23aff2010-05-10 14:46:09 +0000584** is a hash-table following every HASHTABLE_NPAGE page numbers in the
585** wal-index.
drh29d4dbe2010-05-18 23:29:52 +0000586**
587** Changing any of these constants will alter the wal-index format and
588** create incompatibilities.
danbb23aff2010-05-10 14:46:09 +0000589*/
drh29d4dbe2010-05-18 23:29:52 +0000590#define HASHTABLE_NPAGE 4096 /* Must be power of 2 and multiple of 256 */
danbb23aff2010-05-10 14:46:09 +0000591#define HASHTABLE_DATATYPE u16
drh29d4dbe2010-05-18 23:29:52 +0000592#define HASHTABLE_HASH_1 383 /* Should be prime */
593#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
594#define HASHTABLE_NBYTE (sizeof(HASHTABLE_DATATYPE)*HASHTABLE_NSLOT)
dan7c246102010-04-12 19:00:29 +0000595
drhc74c3332010-05-31 12:15:19 +0000596#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
597/*
drh181e0912010-06-01 01:08:08 +0000598** Names of locks. This routine is used to provide debugging output and is not
599** a part of an ordinary build.
drhc74c3332010-05-31 12:15:19 +0000600*/
601static const char *walLockName(int lockIdx){
602 if( lockIdx==WAL_WRITE_LOCK ){
603 return "WRITE-LOCK";
604 }else if( lockIdx==WAL_CKPT_LOCK ){
605 return "CKPT-LOCK";
606 }else if( lockIdx==WAL_RECOVER_LOCK ){
607 return "RECOVER-LOCK";
608 }else{
609 static char zName[15];
610 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
611 lockIdx-WAL_READ_LOCK(0));
612 return zName;
613 }
614}
615#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
616
617
dan7c246102010-04-12 19:00:29 +0000618/*
drh181e0912010-06-01 01:08:08 +0000619** Set or release locks on the WAL. Locks are either shared or exclusive.
620** A lock cannot be moved directly between shared and exclusive - it must go
621** through the unlocked state first.
drh73b64e42010-05-30 19:55:15 +0000622**
623** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
624*/
625static int walLockShared(Wal *pWal, int lockIdx){
drhc74c3332010-05-31 12:15:19 +0000626 int rc;
drh73b64e42010-05-30 19:55:15 +0000627 if( pWal->exclusiveMode ) return SQLITE_OK;
drhc74c3332010-05-31 12:15:19 +0000628 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
629 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
630 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
631 walLockName(lockIdx), rc ? "failed" : "ok"));
632 return rc;
drh73b64e42010-05-30 19:55:15 +0000633}
634static void walUnlockShared(Wal *pWal, int lockIdx){
635 if( pWal->exclusiveMode ) return;
636 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
637 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
drhc74c3332010-05-31 12:15:19 +0000638 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
drh73b64e42010-05-30 19:55:15 +0000639}
640static int walLockExclusive(Wal *pWal, int lockIdx, int n){
drhc74c3332010-05-31 12:15:19 +0000641 int rc;
drh73b64e42010-05-30 19:55:15 +0000642 if( pWal->exclusiveMode ) return SQLITE_OK;
drhc74c3332010-05-31 12:15:19 +0000643 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
644 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
645 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
646 walLockName(lockIdx), n, rc ? "failed" : "ok"));
647 return rc;
drh73b64e42010-05-30 19:55:15 +0000648}
649static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
650 if( pWal->exclusiveMode ) return;
651 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
652 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
drhc74c3332010-05-31 12:15:19 +0000653 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
654 walLockName(lockIdx), n));
drh73b64e42010-05-30 19:55:15 +0000655}
656
657/*
drha2a42012010-05-18 18:01:08 +0000658** Return the index in the Wal.pWiData array that corresponds to
659** frame iFrame.
660**
661** Wal.pWiData is an array of u32 elements that is the wal-index.
662** The array begins with a header and is then followed by alternating
663** "map" and "hash-table" blocks. Each "map" block consists of
664** HASHTABLE_NPAGE u32 elements which are page numbers corresponding
665** to frames in the WAL file.
666**
667** This routine returns an index X such that Wal.pWiData[X] is part
668** of a "map" block that contains the page number of the iFrame-th
669** frame in the WAL file.
dan7c246102010-04-12 19:00:29 +0000670*/
drh7ed91f22010-04-29 22:34:07 +0000671static int walIndexEntry(u32 iFrame){
danff207012010-04-24 04:49:15 +0000672 return (
drh7ed91f22010-04-29 22:34:07 +0000673 (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)/sizeof(u32)
danbb23aff2010-05-10 14:46:09 +0000674 + (((iFrame-1)/HASHTABLE_NPAGE) * HASHTABLE_NBYTE)/sizeof(u32)
675 + (iFrame-1)
danff207012010-04-24 04:49:15 +0000676 );
dan7c246102010-04-12 19:00:29 +0000677}
678
drh7ed91f22010-04-29 22:34:07 +0000679/*
drh181e0912010-06-01 01:08:08 +0000680** Return the minimum size of the shared-memory, in bytes, that is needed
681** to support a wal-index containing frame iFrame. The value returned
682** includes the wal-index header and the complete "block" containing iFrame,
683** including the hash table segment that follows the block.
danb7d53f52010-05-06 17:28:08 +0000684*/
685static int walMappingSize(u32 iFrame){
danbb23aff2010-05-10 14:46:09 +0000686 const int nByte = (sizeof(u32)*HASHTABLE_NPAGE + HASHTABLE_NBYTE) ;
687 return ( WALINDEX_LOCK_OFFSET
688 + WALINDEX_LOCK_RESERVED
689 + nByte * ((iFrame + HASHTABLE_NPAGE - 1)/HASHTABLE_NPAGE)
danb7d53f52010-05-06 17:28:08 +0000690 );
691}
692
693/*
drh5530b762010-04-30 14:39:50 +0000694** Release our reference to the wal-index memory map, if we are holding
695** it.
drh7ed91f22010-04-29 22:34:07 +0000696*/
697static void walIndexUnmap(Wal *pWal){
698 if( pWal->pWiData ){
drhd9e5c4f2010-05-12 18:01:39 +0000699 sqlite3OsShmRelease(pWal->pDbFd);
drh7ed91f22010-04-29 22:34:07 +0000700 }
drh026ac282010-05-26 15:06:38 +0000701 pWal->pWiData = 0;
702 pWal->szWIndex = -1;
drh7ed91f22010-04-29 22:34:07 +0000703}
dan7c246102010-04-12 19:00:29 +0000704
705/*
drh5530b762010-04-30 14:39:50 +0000706** Map the wal-index file into memory if it isn't already.
707**
drh026ac282010-05-26 15:06:38 +0000708** The reqSize parameter is the requested size of the mapping. The
709** mapping will be at least this big if the underlying storage is
710** that big. But the mapping will never grow larger than the underlying
711** storage. Use the walIndexRemap() to enlarget the storage space.
drh7ed91f22010-04-29 22:34:07 +0000712*/
drh5530b762010-04-30 14:39:50 +0000713static int walIndexMap(Wal *pWal, int reqSize){
714 int rc = SQLITE_OK;
dan998ad212010-05-07 06:59:08 +0000715 if( pWal->pWiData==0 || reqSize>pWal->szWIndex ){
drh5500a1f2010-05-13 09:11:31 +0000716 walIndexUnmap(pWal);
drhd9e5c4f2010-05-12 18:01:39 +0000717 rc = sqlite3OsShmGet(pWal->pDbFd, reqSize, &pWal->szWIndex,
drh5939f442010-05-18 13:27:12 +0000718 (void volatile**)(char volatile*)&pWal->pWiData);
dan65f2ac52010-05-07 09:43:50 +0000719 if( rc!=SQLITE_OK ){
720 walIndexUnmap(pWal);
721 }
drh79e6c782010-04-30 02:13:26 +0000722 }
723 return rc;
724}
725
726/*
drh026ac282010-05-26 15:06:38 +0000727** Enlarge the wal-index to be at least enlargeTo bytes in size and
drh5530b762010-04-30 14:39:50 +0000728** Remap the wal-index so that the mapping covers the full size
729** of the underlying file.
730**
731** If enlargeTo is non-negative, then increase the size of the underlying
732** storage to be at least as big as enlargeTo before remapping.
drh79e6c782010-04-30 02:13:26 +0000733*/
drh5530b762010-04-30 14:39:50 +0000734static int walIndexRemap(Wal *pWal, int enlargeTo){
735 int rc;
736 int sz;
drh73b64e42010-05-30 19:55:15 +0000737 assert( pWal->writeLock );
drhd9e5c4f2010-05-12 18:01:39 +0000738 rc = sqlite3OsShmSize(pWal->pDbFd, enlargeTo, &sz);
drh5530b762010-04-30 14:39:50 +0000739 if( rc==SQLITE_OK && sz>pWal->szWIndex ){
740 walIndexUnmap(pWal);
741 rc = walIndexMap(pWal, sz);
742 }
drh026ac282010-05-26 15:06:38 +0000743 assert( pWal->szWIndex>=enlargeTo || rc!=SQLITE_OK );
drh7ed91f22010-04-29 22:34:07 +0000744 return rc;
745}
746
747/*
drh29d4dbe2010-05-18 23:29:52 +0000748** Compute a hash on a page number. The resulting hash value must land
drh181e0912010-06-01 01:08:08 +0000749** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
750** the hash to the next value in the event of a collision.
drh29d4dbe2010-05-18 23:29:52 +0000751*/
752static int walHash(u32 iPage){
753 assert( iPage>0 );
754 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
755 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
756}
757static int walNextHash(int iPriorHash){
758 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
danbb23aff2010-05-10 14:46:09 +0000759}
760
761
762/*
763** Find the hash table and (section of the) page number array used to
764** store data for WAL frame iFrame.
765**
766** Set output variable *paHash to point to the start of the hash table
767** in the wal-index file. Set *piZero to one less than the frame
768** number of the first frame indexed by this hash table. If a
769** slot in the hash table is set to N, it refers to frame number
770** (*piZero+N) in the log.
771**
772** Finally, set *paPgno such that for all frames F between (*piZero+1) and
773** (*piZero+HASHTABLE_NPAGE), (*paPgno)[F] is the database page number
774** associated with frame F.
775*/
776static void walHashFind(
777 Wal *pWal, /* WAL handle */
778 u32 iFrame, /* Find the hash table indexing this frame */
drh5939f442010-05-18 13:27:12 +0000779 volatile HASHTABLE_DATATYPE **paHash, /* OUT: Pointer to hash index */
780 volatile u32 **paPgno, /* OUT: Pointer to page number array */
danbb23aff2010-05-10 14:46:09 +0000781 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
782){
783 u32 iZero;
drh5939f442010-05-18 13:27:12 +0000784 volatile u32 *aPgno;
785 volatile HASHTABLE_DATATYPE *aHash;
danbb23aff2010-05-10 14:46:09 +0000786
787 iZero = ((iFrame-1)/HASHTABLE_NPAGE) * HASHTABLE_NPAGE;
788 aPgno = &pWal->pWiData[walIndexEntry(iZero+1)-iZero-1];
789 aHash = (HASHTABLE_DATATYPE *)&aPgno[iZero+HASHTABLE_NPAGE+1];
790
791 /* Assert that:
792 **
793 ** + the mapping is large enough for this hash-table, and
794 **
795 ** + that aPgno[iZero+1] really is the database page number associated
796 ** with the first frame indexed by this hash table.
797 */
798 assert( (u32*)(&aHash[HASHTABLE_NSLOT])<=&pWal->pWiData[pWal->szWIndex/4] );
799 assert( walIndexEntry(iZero+1)==(&aPgno[iZero+1] - pWal->pWiData) );
800
801 *paHash = aHash;
802 *paPgno = aPgno;
803 *piZero = iZero;
804}
805
danca6b5ba2010-05-25 10:50:56 +0000806/*
807** Remove entries from the hash table that point to WAL slots greater
808** than pWal->hdr.mxFrame.
809**
810** This function is called whenever pWal->hdr.mxFrame is decreased due
811** to a rollback or savepoint.
812**
drh181e0912010-06-01 01:08:08 +0000813** At most only the hash table containing pWal->hdr.mxFrame needs to be
814** updated. Any later hash tables will be automatically cleared when
815** pWal->hdr.mxFrame advances to the point where those hash tables are
816** actually needed.
danca6b5ba2010-05-25 10:50:56 +0000817*/
818static void walCleanupHash(Wal *pWal){
819 volatile HASHTABLE_DATATYPE *aHash; /* Pointer to hash table to clear */
820 volatile u32 *aPgno; /* Unused return from walHashFind() */
821 u32 iZero; /* frame == (aHash[x]+iZero) */
drhf77bbd92010-06-01 13:17:44 +0000822 int iLimit = 0; /* Zero values greater than this */
danca6b5ba2010-05-25 10:50:56 +0000823
drh73b64e42010-05-30 19:55:15 +0000824 assert( pWal->writeLock );
drh9c156472010-06-01 12:58:41 +0000825 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE-1 );
826 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE );
827 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE+1 );
828 if( (pWal->hdr.mxFrame % HASHTABLE_NPAGE)>0 ){
danca6b5ba2010-05-25 10:50:56 +0000829 int nByte; /* Number of bytes to zero in aPgno[] */
830 int i; /* Used to iterate through aHash[] */
drh9c156472010-06-01 12:58:41 +0000831
832 walHashFind(pWal, pWal->hdr.mxFrame+1, &aHash, &aPgno, &iZero);
833 iLimit = pWal->hdr.mxFrame - iZero;
834 assert( iLimit>0 );
danca6b5ba2010-05-25 10:50:56 +0000835 for(i=0; i<HASHTABLE_NSLOT; i++){
836 if( aHash[i]>iLimit ){
837 aHash[i] = 0;
838 }
839 }
840
841 /* Zero the entries in the aPgno array that correspond to frames with
842 ** frame numbers greater than pWal->hdr.mxFrame.
843 */
844 nByte = sizeof(u32) * (HASHTABLE_NPAGE-iLimit);
845 memset((void *)&aPgno[iZero+iLimit+1], 0, nByte);
846 assert( &((u8 *)&aPgno[iZero+iLimit+1])[nByte]==(u8 *)aHash );
847 }
848
849#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
850 /* Verify that the every entry in the mapping region is still reachable
851 ** via the hash table even after the cleanup.
852 */
drhf77bbd92010-06-01 13:17:44 +0000853 if( iLimit ){
danca6b5ba2010-05-25 10:50:56 +0000854 int i; /* Loop counter */
855 int iKey; /* Hash key */
856 for(i=1; i<=iLimit; i++){
857 for(iKey=walHash(aPgno[i+iZero]); aHash[iKey]; iKey=walNextHash(iKey)){
858 if( aHash[iKey]==i ) break;
859 }
860 assert( aHash[iKey]==i );
861 }
862 }
863#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
864}
865
danbb23aff2010-05-10 14:46:09 +0000866
drh7ed91f22010-04-29 22:34:07 +0000867/*
drh29d4dbe2010-05-18 23:29:52 +0000868** Set an entry in the wal-index that will map database page number
869** pPage into WAL frame iFrame.
dan7c246102010-04-12 19:00:29 +0000870*/
drh7ed91f22010-04-29 22:34:07 +0000871static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
danbb23aff2010-05-10 14:46:09 +0000872 int rc; /* Return code */
873 int nMapping; /* Required mapping size in bytes */
drh7ed91f22010-04-29 22:34:07 +0000874
danbb23aff2010-05-10 14:46:09 +0000875 /* Make sure the wal-index is mapped. Enlarge the mapping if required. */
876 nMapping = walMappingSize(iFrame);
drh026ac282010-05-26 15:06:38 +0000877 rc = walIndexMap(pWal, nMapping);
danbb23aff2010-05-10 14:46:09 +0000878 while( rc==SQLITE_OK && nMapping>pWal->szWIndex ){
drh026ac282010-05-26 15:06:38 +0000879 rc = walIndexRemap(pWal, nMapping);
dance4f05f2010-04-22 19:14:13 +0000880 }
881
danbb23aff2010-05-10 14:46:09 +0000882 /* Assuming the wal-index file was successfully mapped, find the hash
883 ** table and section of of the page number array that pertain to frame
884 ** iFrame of the WAL. Then populate the page number array and the hash
885 ** table entry.
dan7c246102010-04-12 19:00:29 +0000886 */
danbb23aff2010-05-10 14:46:09 +0000887 if( rc==SQLITE_OK ){
888 int iKey; /* Hash table key */
889 u32 iZero; /* One less than frame number of aPgno[1] */
drh5939f442010-05-18 13:27:12 +0000890 volatile u32 *aPgno; /* Page number array */
891 volatile HASHTABLE_DATATYPE *aHash; /* Hash table */
892 int idx; /* Value to write to hash-table slot */
drh29d4dbe2010-05-18 23:29:52 +0000893 TESTONLY( int nCollide = 0; /* Number of hash collisions */ )
dan7c246102010-04-12 19:00:29 +0000894
danbb23aff2010-05-10 14:46:09 +0000895 walHashFind(pWal, iFrame, &aHash, &aPgno, &iZero);
896 idx = iFrame - iZero;
danca6b5ba2010-05-25 10:50:56 +0000897 if( idx==1 ){
898 memset((void*)&aPgno[iZero+1], 0, HASHTABLE_NPAGE*sizeof(u32));
899 memset((void*)aHash, 0, HASHTABLE_NBYTE);
900 }
drh29d4dbe2010-05-18 23:29:52 +0000901 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
danca6b5ba2010-05-25 10:50:56 +0000902
903 if( aPgno[iFrame] ){
904 /* If the entry in aPgno[] is already set, then the previous writer
905 ** must have exited unexpectedly in the middle of a transaction (after
906 ** writing one or more dirty pages to the WAL to free up memory).
907 ** Remove the remnants of that writers uncommitted transaction from
908 ** the hash-table before writing any new entries.
909 */
910 walCleanupHash(pWal);
911 assert( !aPgno[iFrame] );
912 }
danbb23aff2010-05-10 14:46:09 +0000913 aPgno[iFrame] = iPage;
dan6f150142010-05-21 15:31:56 +0000914 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
drh29d4dbe2010-05-18 23:29:52 +0000915 assert( nCollide++ < idx );
916 }
danbb23aff2010-05-10 14:46:09 +0000917 aHash[iKey] = idx;
drh4fa95bf2010-05-22 00:55:39 +0000918
919#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
920 /* Verify that the number of entries in the hash table exactly equals
921 ** the number of entries in the mapping region.
922 */
923 {
924 int i; /* Loop counter */
925 int nEntry = 0; /* Number of entries in the hash table */
926 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
927 assert( nEntry==idx );
928 }
929
930 /* Verify that the every entry in the mapping region is reachable
931 ** via the hash table. This turns out to be a really, really expensive
932 ** thing to check, so only do this occasionally - not on every
933 ** iteration.
934 */
935 if( (idx&0x3ff)==0 ){
936 int i; /* Loop counter */
937 for(i=1; i<=idx; i++){
938 for(iKey=walHash(aPgno[i+iZero]); aHash[iKey]; iKey=walNextHash(iKey)){
939 if( aHash[iKey]==i ) break;
940 }
941 assert( aHash[iKey]==i );
942 }
943 }
944#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
dan7c246102010-04-12 19:00:29 +0000945 }
dan31f98fc2010-04-27 05:42:32 +0000946
drh4fa95bf2010-05-22 00:55:39 +0000947
danbb23aff2010-05-10 14:46:09 +0000948 return rc;
dan7c246102010-04-12 19:00:29 +0000949}
950
951
952/*
drh7ed91f22010-04-29 22:34:07 +0000953** Recover the wal-index by reading the write-ahead log file.
drh73b64e42010-05-30 19:55:15 +0000954**
955** This routine first tries to establish an exclusive lock on the
956** wal-index to prevent other threads/processes from doing anything
957** with the WAL or wal-index while recovery is running. The
958** WAL_RECOVER_LOCK is also held so that other threads will know
959** that this thread is running recovery. If unable to establish
960** the necessary locks, this routine returns SQLITE_BUSY.
dan7c246102010-04-12 19:00:29 +0000961*/
drh7ed91f22010-04-29 22:34:07 +0000962static int walIndexRecover(Wal *pWal){
dan7c246102010-04-12 19:00:29 +0000963 int rc; /* Return Code */
964 i64 nSize; /* Size of log file */
dan71d89912010-05-24 13:57:42 +0000965 u32 aFrameCksum[2] = {0, 0};
dand0aa3422010-05-31 16:41:53 +0000966 int iLock; /* Lock offset to lock for checkpoint */
967 int nLock; /* Number of locks to hold */
dan7c246102010-04-12 19:00:29 +0000968
dand0aa3422010-05-31 16:41:53 +0000969 /* Obtain an exclusive lock on all byte in the locking range not already
970 ** locked by the caller. The caller is guaranteed to have locked the
971 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
972 ** If successful, the same bytes that are locked here are unlocked before
973 ** this function returns.
974 */
975 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
976 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
977 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
978 assert( pWal->writeLock );
979 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
980 nLock = SQLITE_SHM_NLOCK - iLock;
981 rc = walLockExclusive(pWal, iLock, nLock);
drh73b64e42010-05-30 19:55:15 +0000982 if( rc ){
983 return rc;
984 }
drhc74c3332010-05-31 12:15:19 +0000985 WALTRACE(("WAL%p: recovery begin...\n", pWal));
drh73b64e42010-05-30 19:55:15 +0000986
dan71d89912010-05-24 13:57:42 +0000987 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
dan7c246102010-04-12 19:00:29 +0000988
drhd9e5c4f2010-05-12 18:01:39 +0000989 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
dan7c246102010-04-12 19:00:29 +0000990 if( rc!=SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +0000991 goto recovery_error;
dan7c246102010-04-12 19:00:29 +0000992 }
993
danb8fd6c22010-05-24 10:39:36 +0000994 if( nSize>WAL_HDRSIZE ){
995 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
dan7c246102010-04-12 19:00:29 +0000996 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
drh584c7542010-05-19 18:08:10 +0000997 int szFrame; /* Number of bytes in buffer aFrame[] */
dan7c246102010-04-12 19:00:29 +0000998 u8 *aData; /* Pointer to data part of aFrame buffer */
999 int iFrame; /* Index of last frame read */
1000 i64 iOffset; /* Next offset to read from log file */
drh6e810962010-05-19 17:49:50 +00001001 int szPage; /* Page size according to the log */
danb8fd6c22010-05-24 10:39:36 +00001002 u32 magic; /* Magic value read from WAL header */
dan7c246102010-04-12 19:00:29 +00001003
danb8fd6c22010-05-24 10:39:36 +00001004 /* Read in the WAL header. */
drhd9e5c4f2010-05-12 18:01:39 +00001005 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
dan7c246102010-04-12 19:00:29 +00001006 if( rc!=SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00001007 goto recovery_error;
dan7c246102010-04-12 19:00:29 +00001008 }
1009
1010 /* If the database page size is not a power of two, or is greater than
danb8fd6c22010-05-24 10:39:36 +00001011 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
1012 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
1013 ** WAL file.
dan7c246102010-04-12 19:00:29 +00001014 */
danb8fd6c22010-05-24 10:39:36 +00001015 magic = sqlite3Get4byte(&aBuf[0]);
drh23ea97b2010-05-20 16:45:58 +00001016 szPage = sqlite3Get4byte(&aBuf[8]);
danb8fd6c22010-05-24 10:39:36 +00001017 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
1018 || szPage&(szPage-1)
1019 || szPage>SQLITE_MAX_PAGE_SIZE
1020 || szPage<512
1021 ){
dan7c246102010-04-12 19:00:29 +00001022 goto finished;
1023 }
dan71d89912010-05-24 13:57:42 +00001024 pWal->hdr.bigEndCksum = (magic&0x00000001);
drh7e263722010-05-20 21:21:09 +00001025 pWal->szPage = szPage;
drh23ea97b2010-05-20 16:45:58 +00001026 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
drh7e263722010-05-20 21:21:09 +00001027 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
dan71d89912010-05-24 13:57:42 +00001028 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
1029 aBuf, WAL_HDRSIZE, 0, pWal->hdr.aFrameCksum
1030 );
dan7c246102010-04-12 19:00:29 +00001031
1032 /* Malloc a buffer to read frames into. */
drh584c7542010-05-19 18:08:10 +00001033 szFrame = szPage + WAL_FRAME_HDRSIZE;
1034 aFrame = (u8 *)sqlite3_malloc(szFrame);
dan7c246102010-04-12 19:00:29 +00001035 if( !aFrame ){
drh73b64e42010-05-30 19:55:15 +00001036 rc = SQLITE_NOMEM;
1037 goto recovery_error;
dan7c246102010-04-12 19:00:29 +00001038 }
drh7ed91f22010-04-29 22:34:07 +00001039 aData = &aFrame[WAL_FRAME_HDRSIZE];
dan7c246102010-04-12 19:00:29 +00001040
1041 /* Read all frames from the log file. */
1042 iFrame = 0;
drh584c7542010-05-19 18:08:10 +00001043 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
dan7c246102010-04-12 19:00:29 +00001044 u32 pgno; /* Database page number for frame */
1045 u32 nTruncate; /* dbsize field from frame header */
1046 int isValid; /* True if this frame is valid */
1047
1048 /* Read and decode the next log frame. */
drh584c7542010-05-19 18:08:10 +00001049 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
dan7c246102010-04-12 19:00:29 +00001050 if( rc!=SQLITE_OK ) break;
drh7e263722010-05-20 21:21:09 +00001051 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
dan7c246102010-04-12 19:00:29 +00001052 if( !isValid ) break;
danc7991bd2010-05-05 19:04:59 +00001053 rc = walIndexAppend(pWal, ++iFrame, pgno);
1054 if( rc!=SQLITE_OK ) break;
dan7c246102010-04-12 19:00:29 +00001055
1056 /* If nTruncate is non-zero, this is a commit record. */
1057 if( nTruncate ){
dan71d89912010-05-24 13:57:42 +00001058 pWal->hdr.mxFrame = iFrame;
1059 pWal->hdr.nPage = nTruncate;
1060 pWal->hdr.szPage = szPage;
1061 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
1062 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
dan7c246102010-04-12 19:00:29 +00001063 }
1064 }
1065
1066 sqlite3_free(aFrame);
dan7c246102010-04-12 19:00:29 +00001067 }
1068
1069finished:
dan71d89912010-05-24 13:57:42 +00001070 if( rc==SQLITE_OK && pWal->hdr.mxFrame==0 ){
drh026ac282010-05-26 15:06:38 +00001071 rc = walIndexRemap(pWal, walMappingSize(1));
dan576bc322010-05-06 18:04:50 +00001072 }
1073 if( rc==SQLITE_OK ){
dan71d89912010-05-24 13:57:42 +00001074 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
1075 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
drh7e263722010-05-20 21:21:09 +00001076 walIndexWriteHdr(pWal);
dan3dee6da2010-05-31 16:17:54 +00001077
1078 /* Zero the checkpoint-header. This is safe because this thread is
1079 ** currently holding locks that exclude all other readers, writers and
1080 ** checkpointers.
1081 */
1082 memset((void *)walCkptInfo(pWal), 0, sizeof(WalCkptInfo));
dan576bc322010-05-06 18:04:50 +00001083 }
drh73b64e42010-05-30 19:55:15 +00001084
1085recovery_error:
drhc74c3332010-05-31 12:15:19 +00001086 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
dand0aa3422010-05-31 16:41:53 +00001087 walUnlockExclusive(pWal, iLock, nLock);
dan7c246102010-04-12 19:00:29 +00001088 return rc;
1089}
1090
drha8e654e2010-05-04 17:38:42 +00001091/*
dan1018e902010-05-05 15:33:05 +00001092** Close an open wal-index.
drha8e654e2010-05-04 17:38:42 +00001093*/
dan1018e902010-05-05 15:33:05 +00001094static void walIndexClose(Wal *pWal, int isDelete){
drh73b64e42010-05-30 19:55:15 +00001095 if( pWal->isWIndexOpen ){
drhd9e5c4f2010-05-12 18:01:39 +00001096 sqlite3OsShmClose(pWal->pDbFd, isDelete);
drh73b64e42010-05-30 19:55:15 +00001097 pWal->isWIndexOpen = 0;
drha8e654e2010-05-04 17:38:42 +00001098 }
1099}
1100
dan7c246102010-04-12 19:00:29 +00001101/*
drh181e0912010-06-01 01:08:08 +00001102** Open a connection to the WAL file associated with database zDbName.
1103** The database file must already be opened on connection pDbFd.
dan3de777f2010-04-17 12:31:37 +00001104**
1105** A SHARED lock should be held on the database file when this function
1106** is called. The purpose of this SHARED lock is to prevent any other
drh181e0912010-06-01 01:08:08 +00001107** client from unlinking the WAL or wal-index file. If another process
dan3de777f2010-04-17 12:31:37 +00001108** were to do this just after this client opened one of these files, the
1109** system would be badly broken.
danef378022010-05-04 11:06:03 +00001110**
1111** If the log file is successfully opened, SQLITE_OK is returned and
1112** *ppWal is set to point to a new WAL handle. If an error occurs,
1113** an SQLite error code is returned and *ppWal is left unmodified.
dan7c246102010-04-12 19:00:29 +00001114*/
drhc438efd2010-04-26 00:19:45 +00001115int sqlite3WalOpen(
drh7ed91f22010-04-29 22:34:07 +00001116 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
drhd9e5c4f2010-05-12 18:01:39 +00001117 sqlite3_file *pDbFd, /* The open database file */
1118 const char *zDbName, /* Name of the database file */
drh7ed91f22010-04-29 22:34:07 +00001119 Wal **ppWal /* OUT: Allocated Wal handle */
dan7c246102010-04-12 19:00:29 +00001120){
danef378022010-05-04 11:06:03 +00001121 int rc; /* Return Code */
drh7ed91f22010-04-29 22:34:07 +00001122 Wal *pRet; /* Object to allocate and return */
dan7c246102010-04-12 19:00:29 +00001123 int flags; /* Flags passed to OsOpen() */
drhd9e5c4f2010-05-12 18:01:39 +00001124 char *zWal; /* Name of write-ahead log file */
dan7c246102010-04-12 19:00:29 +00001125 int nWal; /* Length of zWal in bytes */
1126
drhd9e5c4f2010-05-12 18:01:39 +00001127 assert( zDbName && zDbName[0] );
1128 assert( pDbFd );
dan7c246102010-04-12 19:00:29 +00001129
drh1b78eaf2010-05-25 13:40:03 +00001130 /* In the amalgamation, the os_unix.c and os_win.c source files come before
1131 ** this source file. Verify that the #defines of the locking byte offsets
1132 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
1133 */
1134#ifdef WIN_SHM_BASE
1135 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
1136#endif
1137#ifdef UNIX_SHM_BASE
1138 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
1139#endif
1140
1141
drh7ed91f22010-04-29 22:34:07 +00001142 /* Allocate an instance of struct Wal to return. */
1143 *ppWal = 0;
drh686138f2010-05-12 18:10:52 +00001144 nWal = sqlite3Strlen30(zDbName) + 5;
drhd9e5c4f2010-05-12 18:01:39 +00001145 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile + nWal);
dan76ed3bc2010-05-03 17:18:24 +00001146 if( !pRet ){
1147 return SQLITE_NOMEM;
1148 }
1149
dan7c246102010-04-12 19:00:29 +00001150 pRet->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00001151 pRet->pWalFd = (sqlite3_file *)&pRet[1];
1152 pRet->pDbFd = pDbFd;
drh026ac282010-05-26 15:06:38 +00001153 pRet->szWIndex = -1;
drh73b64e42010-05-30 19:55:15 +00001154 pRet->readLock = -1;
drh7e263722010-05-20 21:21:09 +00001155 sqlite3_randomness(8, &pRet->hdr.aSalt);
drhd9e5c4f2010-05-12 18:01:39 +00001156 pRet->zWalName = zWal = pVfs->szOsFile + (char*)pRet->pWalFd;
1157 sqlite3_snprintf(nWal, zWal, "%s-wal", zDbName);
1158 rc = sqlite3OsShmOpen(pDbFd);
dan7c246102010-04-12 19:00:29 +00001159
drh7ed91f22010-04-29 22:34:07 +00001160 /* Open file handle on the write-ahead log file. */
dan76ed3bc2010-05-03 17:18:24 +00001161 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00001162 pRet->isWIndexOpen = 1;
dan76ed3bc2010-05-03 17:18:24 +00001163 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_JOURNAL);
drhd9e5c4f2010-05-12 18:01:39 +00001164 rc = sqlite3OsOpen(pVfs, zWal, pRet->pWalFd, flags, &flags);
dan76ed3bc2010-05-03 17:18:24 +00001165 }
dan7c246102010-04-12 19:00:29 +00001166
dan7c246102010-04-12 19:00:29 +00001167 if( rc!=SQLITE_OK ){
dan1018e902010-05-05 15:33:05 +00001168 walIndexClose(pRet, 0);
drhd9e5c4f2010-05-12 18:01:39 +00001169 sqlite3OsClose(pRet->pWalFd);
danef378022010-05-04 11:06:03 +00001170 sqlite3_free(pRet);
1171 }else{
1172 *ppWal = pRet;
drhc74c3332010-05-31 12:15:19 +00001173 WALTRACE(("WAL%d: opened\n", pRet));
dan7c246102010-04-12 19:00:29 +00001174 }
dan7c246102010-04-12 19:00:29 +00001175 return rc;
1176}
1177
drha2a42012010-05-18 18:01:08 +00001178/*
1179** Find the smallest page number out of all pages held in the WAL that
1180** has not been returned by any prior invocation of this method on the
1181** same WalIterator object. Write into *piFrame the frame index where
1182** that page was last written into the WAL. Write into *piPage the page
1183** number.
1184**
1185** Return 0 on success. If there are no pages in the WAL with a page
1186** number larger than *piPage, then return 1.
1187*/
drh7ed91f22010-04-29 22:34:07 +00001188static int walIteratorNext(
1189 WalIterator *p, /* Iterator */
drha2a42012010-05-18 18:01:08 +00001190 u32 *piPage, /* OUT: The page number of the next page */
1191 u32 *piFrame /* OUT: Wal frame index of next page */
dan7c246102010-04-12 19:00:29 +00001192){
drha2a42012010-05-18 18:01:08 +00001193 u32 iMin; /* Result pgno must be greater than iMin */
1194 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
1195 int i; /* For looping through segments */
1196 int nBlock = p->nFinal; /* Number of entries in current segment */
dan7c246102010-04-12 19:00:29 +00001197
drha2a42012010-05-18 18:01:08 +00001198 iMin = p->iPrior;
1199 assert( iMin<0xffffffff );
dan7c246102010-04-12 19:00:29 +00001200 for(i=p->nSegment-1; i>=0; i--){
drh7ed91f22010-04-29 22:34:07 +00001201 struct WalSegment *pSegment = &p->aSegment[i];
dan7c246102010-04-12 19:00:29 +00001202 while( pSegment->iNext<nBlock ){
drha2a42012010-05-18 18:01:08 +00001203 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
dan7c246102010-04-12 19:00:29 +00001204 if( iPg>iMin ){
1205 if( iPg<iRet ){
1206 iRet = iPg;
1207 *piFrame = i*256 + 1 + pSegment->aIndex[pSegment->iNext];
1208 }
1209 break;
1210 }
1211 pSegment->iNext++;
1212 }
dan7c246102010-04-12 19:00:29 +00001213 nBlock = 256;
1214 }
1215
drha2a42012010-05-18 18:01:08 +00001216 *piPage = p->iPrior = iRet;
dan7c246102010-04-12 19:00:29 +00001217 return (iRet==0xFFFFFFFF);
1218}
1219
dan7c246102010-04-12 19:00:29 +00001220
drha2a42012010-05-18 18:01:08 +00001221static void walMergesort8(
1222 Pgno *aContent, /* Pages in wal */
1223 u8 *aBuffer, /* Buffer of at least *pnList items to use */
1224 u8 *aList, /* IN/OUT: List to sort */
1225 int *pnList /* IN/OUT: Number of elements in aList[] */
1226){
1227 int nList = *pnList;
1228 if( nList>1 ){
1229 int nLeft = nList / 2; /* Elements in left list */
1230 int nRight = nList - nLeft; /* Elements in right list */
1231 u8 *aLeft = aList; /* Left list */
1232 u8 *aRight = &aList[nLeft]; /* Right list */
1233 int iLeft = 0; /* Current index in aLeft */
1234 int iRight = 0; /* Current index in aright */
1235 int iOut = 0; /* Current index in output buffer */
1236
1237 /* TODO: Change to non-recursive version. */
1238 walMergesort8(aContent, aBuffer, aLeft, &nLeft);
1239 walMergesort8(aContent, aBuffer, aRight, &nRight);
1240
1241 while( iRight<nRight || iLeft<nLeft ){
1242 u8 logpage;
1243 Pgno dbpage;
1244
1245 if( (iLeft<nLeft)
1246 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
1247 ){
1248 logpage = aLeft[iLeft++];
1249 }else{
1250 logpage = aRight[iRight++];
1251 }
1252 dbpage = aContent[logpage];
1253
1254 aBuffer[iOut++] = logpage;
1255 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
1256
1257 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
1258 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
1259 }
1260 memcpy(aList, aBuffer, sizeof(aList[0])*iOut);
1261 *pnList = iOut;
1262 }
1263
1264#ifdef SQLITE_DEBUG
1265 {
1266 int i;
1267 for(i=1; i<*pnList; i++){
1268 assert( aContent[aList[i]] > aContent[aList[i-1]] );
1269 }
1270 }
1271#endif
1272}
1273
1274/*
1275** Map the wal-index into memory owned by this thread, if it is not
1276** mapped already. Then construct a WalInterator object that can be
1277** used to loop over all pages in the WAL in ascending order.
1278**
1279** On success, make *pp point to the newly allocated WalInterator object
1280** return SQLITE_OK. Otherwise, leave *pp unchanged and return an error
1281** code.
1282**
1283** The calling routine should invoke walIteratorFree() to destroy the
1284** WalIterator object when it has finished with it. The caller must
1285** also unmap the wal-index. But the wal-index must not be unmapped
1286** prior to the WalIterator object being destroyed.
1287*/
1288static int walIteratorInit(Wal *pWal, WalIterator **pp){
1289 u32 *aData; /* Content of the wal-index file */
1290 WalIterator *p; /* Return value */
1291 int nSegment; /* Number of segments to merge */
1292 u32 iLast; /* Last frame in log */
1293 int nByte; /* Number of bytes to allocate */
1294 int i; /* Iterator variable */
1295 int nFinal; /* Number of unindexed entries */
1296 u8 *aTmp; /* Temp space used by merge-sort */
1297 int rc; /* Return code of walIndexMap() */
1298 u8 *aSpace; /* Surplus space on the end of the allocation */
1299
1300 /* Make sure the wal-index is mapped into local memory */
drh027a1282010-05-19 01:53:53 +00001301 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
dan8f6097c2010-05-06 07:43:58 +00001302 if( rc!=SQLITE_OK ){
1303 return rc;
1304 }
drha2a42012010-05-18 18:01:08 +00001305
1306 /* This routine only runs while holding SQLITE_SHM_CHECKPOINT. No other
1307 ** thread is able to write to shared memory while this routine is
1308 ** running (or, indeed, while the WalIterator object exists). Hence,
1309 ** we can cast off the volatile qualifacation from shared memory
1310 */
dan1beb9392010-05-31 12:02:30 +00001311 assert( pWal->ckptLock );
drh5939f442010-05-18 13:27:12 +00001312 aData = (u32*)pWal->pWiData;
drha2a42012010-05-18 18:01:08 +00001313
1314 /* Allocate space for the WalIterator object */
drh027a1282010-05-19 01:53:53 +00001315 iLast = pWal->hdr.mxFrame;
dan7c246102010-04-12 19:00:29 +00001316 nSegment = (iLast >> 8) + 1;
1317 nFinal = (iLast & 0x000000FF);
danbb23aff2010-05-10 14:46:09 +00001318 nByte = sizeof(WalIterator) + (nSegment+1)*(sizeof(struct WalSegment)+256);
drh7ed91f22010-04-29 22:34:07 +00001319 p = (WalIterator *)sqlite3_malloc(nByte);
dan8f6097c2010-05-06 07:43:58 +00001320 if( !p ){
drha2a42012010-05-18 18:01:08 +00001321 return SQLITE_NOMEM;
1322 }
1323 memset(p, 0, nByte);
dan76ed3bc2010-05-03 17:18:24 +00001324
drha2a42012010-05-18 18:01:08 +00001325 /* Initialize the WalIterator object. Each 256-entry segment is
1326 ** presorted in order to make iterating through all entries much
1327 ** faster.
1328 */
1329 p->nSegment = nSegment;
1330 aSpace = (u8 *)&p->aSegment[nSegment];
1331 aTmp = &aSpace[nSegment*256];
1332 for(i=0; i<nSegment; i++){
1333 int j;
1334 int nIndex = (i==nSegment-1) ? nFinal : 256;
1335 p->aSegment[i].aPgno = &aData[walIndexEntry(i*256+1)];
1336 p->aSegment[i].aIndex = aSpace;
1337 for(j=0; j<nIndex; j++){
1338 aSpace[j] = j;
dan76ed3bc2010-05-03 17:18:24 +00001339 }
drha2a42012010-05-18 18:01:08 +00001340 walMergesort8(p->aSegment[i].aPgno, aTmp, aSpace, &nIndex);
1341 memset(&aSpace[nIndex], aSpace[nIndex-1], 256-nIndex);
1342 aSpace += 256;
1343 p->nFinal = nIndex;
dan7c246102010-04-12 19:00:29 +00001344 }
1345
drha2a42012010-05-18 18:01:08 +00001346 /* Return the fully initializd WalIterator object */
dan8f6097c2010-05-06 07:43:58 +00001347 *pp = p;
drha2a42012010-05-18 18:01:08 +00001348 return SQLITE_OK ;
dan7c246102010-04-12 19:00:29 +00001349}
1350
1351/*
drha2a42012010-05-18 18:01:08 +00001352** Free an iterator allocated by walIteratorInit().
dan7c246102010-04-12 19:00:29 +00001353*/
drh7ed91f22010-04-29 22:34:07 +00001354static void walIteratorFree(WalIterator *p){
dan7c246102010-04-12 19:00:29 +00001355 sqlite3_free(p);
1356}
1357
drh73b64e42010-05-30 19:55:15 +00001358
dan7c246102010-04-12 19:00:29 +00001359/*
drh73b64e42010-05-30 19:55:15 +00001360** Copy as much content as we can from the WAL back into the database file
1361** in response to an sqlite3_wal_checkpoint() request or the equivalent.
1362**
1363** The amount of information copies from WAL to database might be limited
1364** by active readers. This routine will never overwrite a database page
1365** that a concurrent reader might be using.
1366**
1367** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
1368** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
1369** checkpoints are always run by a background thread or background
1370** process, foreground threads will never block on a lengthy fsync call.
1371**
1372** Fsync is called on the WAL before writing content out of the WAL and
1373** into the database. This ensures that if the new content is persistent
1374** in the WAL and can be recovered following a power-loss or hard reset.
1375**
1376** Fsync is also called on the database file if (and only if) the entire
1377** WAL content is copied into the database file. This second fsync makes
1378** it safe to delete the WAL since the new content will persist in the
1379** database file.
1380**
1381** This routine uses and updates the nBackfill field of the wal-index header.
1382** This is the only routine tha will increase the value of nBackfill.
1383** (A WAL reset or recovery will revert nBackfill to zero, but not increase
1384** its value.)
1385**
1386** The caller must be holding sufficient locks to ensure that no other
1387** checkpoint is running (in any other thread or process) at the same
1388** time.
dan7c246102010-04-12 19:00:29 +00001389*/
drh7ed91f22010-04-29 22:34:07 +00001390static int walCheckpoint(
1391 Wal *pWal, /* Wal connection */
danc5118782010-04-17 17:34:41 +00001392 int sync_flags, /* Flags for OsSync() (or 0) */
danb6e099a2010-05-04 14:47:39 +00001393 int nBuf, /* Size of zBuf in bytes */
dan7c246102010-04-12 19:00:29 +00001394 u8 *zBuf /* Temporary buffer to use */
1395){
1396 int rc; /* Return code */
drh6e810962010-05-19 17:49:50 +00001397 int szPage = pWal->hdr.szPage; /* Database page-size */
drh7ed91f22010-04-29 22:34:07 +00001398 WalIterator *pIter = 0; /* Wal iterator context */
dan7c246102010-04-12 19:00:29 +00001399 u32 iDbpage = 0; /* Next database page to write */
drh7ed91f22010-04-29 22:34:07 +00001400 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
drh73b64e42010-05-30 19:55:15 +00001401 u32 mxSafeFrame; /* Max frame that can be backfilled */
1402 int i; /* Loop counter */
1403 volatile WalIndexHdr *pHdr; /* The actual wal-index header in SHM */
1404 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
dan7c246102010-04-12 19:00:29 +00001405
1406 /* Allocate the iterator */
dan8f6097c2010-05-06 07:43:58 +00001407 rc = walIteratorInit(pWal, &pIter);
drh027a1282010-05-19 01:53:53 +00001408 if( rc!=SQLITE_OK || pWal->hdr.mxFrame==0 ){
drh73b64e42010-05-30 19:55:15 +00001409 walIteratorFree(pIter);
1410 return rc;
danb6e099a2010-05-04 14:47:39 +00001411 }
1412
drh73b64e42010-05-30 19:55:15 +00001413 /*** TODO: Move this test out to the caller. Make it an assert() here ***/
drh6e810962010-05-19 17:49:50 +00001414 if( pWal->hdr.szPage!=nBuf ){
drh73b64e42010-05-30 19:55:15 +00001415 walIteratorFree(pIter);
1416 return SQLITE_CORRUPT_BKPT;
danb6e099a2010-05-04 14:47:39 +00001417 }
1418
drh73b64e42010-05-30 19:55:15 +00001419 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
1420 ** safe to write into the database. Frames beyond mxSafeFrame might
1421 ** overwrite database pages that are in use by active readers and thus
1422 ** cannot be backfilled from the WAL.
1423 */
dand54ff602010-05-31 11:16:30 +00001424 mxSafeFrame = pWal->hdr.mxFrame;
drh73b64e42010-05-30 19:55:15 +00001425 pHdr = (volatile WalIndexHdr*)pWal->pWiData;
1426 pInfo = (volatile WalCkptInfo*)&pHdr[2];
1427 assert( pInfo==walCkptInfo(pWal) );
1428 for(i=1; i<WAL_NREADER; i++){
1429 u32 y = pInfo->aReadMark[i];
dand54ff602010-05-31 11:16:30 +00001430 if( y>0 && (mxSafeFrame==0 || mxSafeFrame>=y) ){
dan0cc5b2b2010-05-31 11:39:53 +00001431 if( y<=pWal->hdr.mxFrame
dane8772962010-06-01 10:44:28 +00001432 && walLockExclusive(pWal, WAL_READ_LOCK(i), 1)==SQLITE_OK
drh73b64e42010-05-30 19:55:15 +00001433 ){
1434 pInfo->aReadMark[i] = 0;
1435 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
1436 }else{
dand54ff602010-05-31 11:16:30 +00001437 mxSafeFrame = y-1;
drh73b64e42010-05-30 19:55:15 +00001438 }
1439 }
danc5118782010-04-17 17:34:41 +00001440 }
dan7c246102010-04-12 19:00:29 +00001441
drh73b64e42010-05-30 19:55:15 +00001442 if( pInfo->nBackfill<mxSafeFrame
1443 && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
1444 ){
1445 u32 nBackfill = pInfo->nBackfill;
1446
1447 /* Sync the WAL to disk */
1448 if( sync_flags ){
1449 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
1450 }
1451
1452 /* Iterate through the contents of the WAL, copying data to the db file. */
1453 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
1454 if( iFrame<=nBackfill || iFrame>mxSafeFrame ) continue;
1455 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage,
1456 walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE
1457 );
1458 if( rc!=SQLITE_OK ) break;
1459 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, (iDbpage-1)*szPage);
1460 if( rc!=SQLITE_OK ) break;
1461 }
1462
1463 /* If work was actually accomplished... */
1464 if( rc==SQLITE_OK && pInfo->nBackfill<mxSafeFrame ){
1465 pInfo->nBackfill = mxSafeFrame;
1466 if( mxSafeFrame==pHdr[0].mxFrame && sync_flags ){
1467 rc = sqlite3OsTruncate(pWal->pDbFd, ((i64)pWal->hdr.nPage*(i64)szPage));
1468 if( rc==SQLITE_OK && sync_flags ){
1469 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
1470 }
1471 }
1472 }
1473
1474 /* Release the reader lock held while backfilling */
1475 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
drh34116ea2010-05-31 12:30:52 +00001476 }else{
1477 /* Reset the return code so as not to report a checkpoint failure
1478 ** just because active readers prevent any backfill.
1479 */
1480 rc = SQLITE_OK;
dan7c246102010-04-12 19:00:29 +00001481 }
1482
drh7ed91f22010-04-29 22:34:07 +00001483 walIteratorFree(pIter);
dan7c246102010-04-12 19:00:29 +00001484 return rc;
1485}
1486
1487/*
1488** Close a connection to a log file.
1489*/
drhc438efd2010-04-26 00:19:45 +00001490int sqlite3WalClose(
drh7ed91f22010-04-29 22:34:07 +00001491 Wal *pWal, /* Wal to close */
danc5118782010-04-17 17:34:41 +00001492 int sync_flags, /* Flags to pass to OsSync() (or 0) */
danb6e099a2010-05-04 14:47:39 +00001493 int nBuf,
1494 u8 *zBuf /* Buffer of at least nBuf bytes */
dan7c246102010-04-12 19:00:29 +00001495){
1496 int rc = SQLITE_OK;
drh7ed91f22010-04-29 22:34:07 +00001497 if( pWal ){
dan30c86292010-04-30 16:24:46 +00001498 int isDelete = 0; /* True to unlink wal and wal-index files */
1499
1500 /* If an EXCLUSIVE lock can be obtained on the database file (using the
1501 ** ordinary, rollback-mode locking methods, this guarantees that the
1502 ** connection associated with this log file is the only connection to
1503 ** the database. In this case checkpoint the database and unlink both
1504 ** the wal and wal-index files.
1505 **
1506 ** The EXCLUSIVE lock is not released before returning.
1507 */
drhd9e5c4f2010-05-12 18:01:39 +00001508 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
dan30c86292010-04-30 16:24:46 +00001509 if( rc==SQLITE_OK ){
drh73b64e42010-05-30 19:55:15 +00001510 pWal->exclusiveMode = 1;
dan1beb9392010-05-31 12:02:30 +00001511 rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
dan30c86292010-04-30 16:24:46 +00001512 if( rc==SQLITE_OK ){
1513 isDelete = 1;
1514 }
1515 walIndexUnmap(pWal);
1516 }
1517
dan1018e902010-05-05 15:33:05 +00001518 walIndexClose(pWal, isDelete);
drhd9e5c4f2010-05-12 18:01:39 +00001519 sqlite3OsClose(pWal->pWalFd);
dan30c86292010-04-30 16:24:46 +00001520 if( isDelete ){
drhd9e5c4f2010-05-12 18:01:39 +00001521 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
dan30c86292010-04-30 16:24:46 +00001522 }
drhc74c3332010-05-31 12:15:19 +00001523 WALTRACE(("WAL%p: closed\n", pWal));
drh7ed91f22010-04-29 22:34:07 +00001524 sqlite3_free(pWal);
dan7c246102010-04-12 19:00:29 +00001525 }
1526 return rc;
1527}
1528
1529/*
drha2a42012010-05-18 18:01:08 +00001530** Try to read the wal-index header. Return 0 on success and 1 if
1531** there is a problem.
1532**
1533** The wal-index is in shared memory. Another thread or process might
1534** be writing the header at the same time this procedure is trying to
1535** read it, which might result in inconsistency. A dirty read is detected
drh73b64e42010-05-30 19:55:15 +00001536** by verifying that both copies of the header are the same and also by
1537** a checksum on the header.
drha2a42012010-05-18 18:01:08 +00001538**
1539** If and only if the read is consistent and the header is different from
1540** pWal->hdr, then pWal->hdr is updated to the content of the new header
1541** and *pChanged is set to 1.
danb9bf16b2010-04-14 11:23:30 +00001542**
dan84670502010-05-07 05:46:23 +00001543** If the checksum cannot be verified return non-zero. If the header
1544** is read successfully and the checksum verified, return zero.
danb9bf16b2010-04-14 11:23:30 +00001545*/
dan84670502010-05-07 05:46:23 +00001546int walIndexTryHdr(Wal *pWal, int *pChanged){
drh286a2882010-05-20 23:51:06 +00001547 u32 aCksum[2]; /* Checksum on the header content */
drhf0b20f82010-05-21 13:16:18 +00001548 WalIndexHdr h1, h2; /* Two copies of the header content */
drh286a2882010-05-20 23:51:06 +00001549 WalIndexHdr *aHdr; /* Header in shared memory */
danb9bf16b2010-04-14 11:23:30 +00001550
drh026ac282010-05-26 15:06:38 +00001551 if( pWal->szWIndex < WALINDEX_HDR_SIZE ){
1552 /* The wal-index is not large enough to hold the header, then assume
1553 ** header is invalid. */
dan84670502010-05-07 05:46:23 +00001554 return 1;
drh79e6c782010-04-30 02:13:26 +00001555 }
drh026ac282010-05-26 15:06:38 +00001556 assert( pWal->pWiData );
drh79e6c782010-04-30 02:13:26 +00001557
drh73b64e42010-05-30 19:55:15 +00001558 /* Read the header. This might happen currently with a write to the
1559 ** same area of shared memory on a different CPU in a SMP,
1560 ** meaning it is possible that an inconsistent snapshot is read
dan84670502010-05-07 05:46:23 +00001561 ** from the file. If this happens, return non-zero.
drhf0b20f82010-05-21 13:16:18 +00001562 **
1563 ** There are two copies of the header at the beginning of the wal-index.
1564 ** When reading, read [0] first then [1]. Writes are in the reverse order.
1565 ** Memory barriers are used to prevent the compiler or the hardware from
1566 ** reordering the reads and writes.
danb9bf16b2010-04-14 11:23:30 +00001567 */
drh286a2882010-05-20 23:51:06 +00001568 aHdr = (WalIndexHdr*)pWal->pWiData;
drhf0b20f82010-05-21 13:16:18 +00001569 memcpy(&h1, &aHdr[0], sizeof(h1));
drh286a2882010-05-20 23:51:06 +00001570 sqlite3OsShmBarrier(pWal->pDbFd);
drhf0b20f82010-05-21 13:16:18 +00001571 memcpy(&h2, &aHdr[1], sizeof(h2));
drh286a2882010-05-20 23:51:06 +00001572
drhf0b20f82010-05-21 13:16:18 +00001573 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
1574 return 1; /* Dirty read */
drh286a2882010-05-20 23:51:06 +00001575 }
drh4b82c382010-05-31 18:24:19 +00001576 if( h1.isInit==0 ){
drhf0b20f82010-05-21 13:16:18 +00001577 return 1; /* Malformed header - probably all zeros */
1578 }
danb8fd6c22010-05-24 10:39:36 +00001579 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
drhf0b20f82010-05-21 13:16:18 +00001580 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
1581 return 1; /* Checksum does not match */
danb9bf16b2010-04-14 11:23:30 +00001582 }
1583
drhf0b20f82010-05-21 13:16:18 +00001584 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
dana8614692010-05-06 14:42:34 +00001585 *pChanged = 1;
drhf0b20f82010-05-21 13:16:18 +00001586 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
drh7e263722010-05-20 21:21:09 +00001587 pWal->szPage = pWal->hdr.szPage;
danb9bf16b2010-04-14 11:23:30 +00001588 }
dan84670502010-05-07 05:46:23 +00001589
1590 /* The header was successfully read. Return zero. */
1591 return 0;
danb9bf16b2010-04-14 11:23:30 +00001592}
1593
1594/*
drha2a42012010-05-18 18:01:08 +00001595** Read the wal-index header from the wal-index and into pWal->hdr.
1596** If the wal-header appears to be corrupt, try to recover the log
1597** before returning.
1598**
1599** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
1600** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
1601** to 0.
1602**
1603** This routine also maps the wal-index content into memory and assigns
1604** ownership of that mapping to the current thread. In some implementations,
1605** only one thread at a time can hold a mapping of the wal-index. Hence,
1606** the caller should strive to invoke walIndexUnmap() as soon as possible
1607** after this routine returns.
danb9bf16b2010-04-14 11:23:30 +00001608**
drh7ed91f22010-04-29 22:34:07 +00001609** If the wal-index header is successfully read, return SQLITE_OK.
danb9bf16b2010-04-14 11:23:30 +00001610** Otherwise an SQLite error code.
1611*/
drh7ed91f22010-04-29 22:34:07 +00001612static int walIndexReadHdr(Wal *pWal, int *pChanged){
dan84670502010-05-07 05:46:23 +00001613 int rc; /* Return code */
drh73b64e42010-05-30 19:55:15 +00001614 int badHdr; /* True if a header read failed */
danb9bf16b2010-04-14 11:23:30 +00001615
dana8614692010-05-06 14:42:34 +00001616 assert( pChanged );
drh026ac282010-05-26 15:06:38 +00001617 rc = walIndexMap(pWal, walMappingSize(1));
danc7991bd2010-05-05 19:04:59 +00001618 if( rc!=SQLITE_OK ){
1619 return rc;
1620 }
drh7ed91f22010-04-29 22:34:07 +00001621
drh73b64e42010-05-30 19:55:15 +00001622 /* Try once to read the header straight out. This works most of the
1623 ** time.
danb9bf16b2010-04-14 11:23:30 +00001624 */
drh73b64e42010-05-30 19:55:15 +00001625 badHdr = walIndexTryHdr(pWal, pChanged);
drhbab7b912010-05-26 17:31:58 +00001626
drh73b64e42010-05-30 19:55:15 +00001627 /* If the first attempt failed, it might have been due to a race
1628 ** with a writer. So get a WRITE lock and try again.
1629 */
dand54ff602010-05-31 11:16:30 +00001630 assert( badHdr==0 || pWal->writeLock==0 );
drh73b64e42010-05-30 19:55:15 +00001631 if( badHdr ){
1632 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
1633 if( rc==SQLITE_OK ){
1634 pWal->writeLock = 1;
1635 badHdr = walIndexTryHdr(pWal, pChanged);
1636 if( badHdr ){
1637 /* If the wal-index header is still malformed even while holding
1638 ** a WRITE lock, it can only mean that the header is corrupted and
1639 ** needs to be reconstructed. So run recovery to do exactly that.
1640 */
drhbab7b912010-05-26 17:31:58 +00001641 rc = walIndexRecover(pWal);
dan3dee6da2010-05-31 16:17:54 +00001642 *pChanged = 1;
drhbab7b912010-05-26 17:31:58 +00001643 }
drh73b64e42010-05-30 19:55:15 +00001644 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
1645 pWal->writeLock = 0;
1646 }else if( rc!=SQLITE_BUSY ){
1647 return rc;
drhbab7b912010-05-26 17:31:58 +00001648 }
danb9bf16b2010-04-14 11:23:30 +00001649 }
1650
drhbab7b912010-05-26 17:31:58 +00001651 /* Make sure the mapping is large enough to cover the entire wal-index */
1652 if( rc==SQLITE_OK ){
1653 int szWanted = walMappingSize(pWal->hdr.mxFrame);
1654 if( pWal->szWIndex<szWanted ){
1655 rc = walIndexMap(pWal, szWanted);
dan65be0d82010-05-06 18:48:27 +00001656 }
danb9bf16b2010-04-14 11:23:30 +00001657 }
1658
1659 return rc;
1660}
1661
1662/*
drh73b64e42010-05-30 19:55:15 +00001663** This is the value that walTryBeginRead returns when it needs to
1664** be retried.
dan7c246102010-04-12 19:00:29 +00001665*/
drh73b64e42010-05-30 19:55:15 +00001666#define WAL_RETRY (-1)
dan64d039e2010-04-13 19:27:31 +00001667
drh73b64e42010-05-30 19:55:15 +00001668/*
1669** Attempt to start a read transaction. This might fail due to a race or
1670** other transient condition. When that happens, it returns WAL_RETRY to
1671** indicate to the caller that it is safe to retry immediately.
1672**
1673** On success return SQLITE_OK. On a permantent failure (such an
1674** I/O error or an SQLITE_BUSY because another process is running
1675** recovery) return a positive error code.
1676**
1677** On success, this routine obtains a read lock on
1678** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
1679** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
1680** that means the Wal does not hold any read lock. The reader must not
1681** access any database page that is modified by a WAL frame up to and
1682** including frame number aReadMark[pWal->readLock]. The reader will
1683** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
1684** Or if pWal->readLock==0, then the reader will ignore the WAL
1685** completely and get all content directly from the database file.
1686** When the read transaction is completed, the caller must release the
1687** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
1688**
1689** This routine uses the nBackfill and aReadMark[] fields of the header
1690** to select a particular WAL_READ_LOCK() that strives to let the
1691** checkpoint process do as much work as possible. This routine might
1692** update values of the aReadMark[] array in the header, but if it does
1693** so it takes care to hold an exclusive lock on the corresponding
1694** WAL_READ_LOCK() while changing values.
1695*/
1696static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal){
1697 volatile WalIndexHdr *pHdr; /* Header of the wal-index */
1698 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
1699 u32 mxReadMark; /* Largest aReadMark[] value */
1700 int mxI; /* Index of largest aReadMark[] value */
1701 int i; /* Loop counter */
1702 int rc; /* Return code */
dan64d039e2010-04-13 19:27:31 +00001703
drh61e4ace2010-05-31 20:28:37 +00001704 assert( pWal->readLock<0 ); /* Not currently locked */
drh73b64e42010-05-30 19:55:15 +00001705
1706 if( !useWal ){
drh7ed91f22010-04-29 22:34:07 +00001707 rc = walIndexReadHdr(pWal, pChanged);
drh73b64e42010-05-30 19:55:15 +00001708 if( rc==SQLITE_BUSY ){
1709 /* If there is not a recovery running in another thread or process
1710 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
1711 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
1712 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
1713 ** would be technically correct. But the race is benign since with
1714 ** WAL_RETRY this routine will be called again and will probably be
1715 ** right on the second iteration.
1716 */
1717 rc = walLockShared(pWal, WAL_RECOVER_LOCK);
1718 if( rc==SQLITE_OK ){
1719 walUnlockShared(pWal, WAL_RECOVER_LOCK);
1720 rc = WAL_RETRY;
1721 }else if( rc==SQLITE_BUSY ){
1722 rc = SQLITE_BUSY_RECOVERY;
1723 }
1724 }
1725 }else{
drh18b7f602010-05-31 14:39:31 +00001726 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
drh73b64e42010-05-30 19:55:15 +00001727 }
1728 if( rc!=SQLITE_OK ){
1729 return rc;
1730 }
1731
1732 pHdr = (volatile WalIndexHdr*)pWal->pWiData;
1733 pInfo = (volatile WalCkptInfo*)&pHdr[2];
1734 assert( pInfo==walCkptInfo(pWal) );
1735 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
1736 /* The WAL has been completely backfilled (or it is empty).
1737 ** and can be safely ignored.
1738 */
1739 rc = walLockShared(pWal, WAL_READ_LOCK(0));
1740 if( rc==SQLITE_OK ){
1741 if( pHdr->mxFrame!=pWal->hdr.mxFrame ){
1742 walUnlockShared(pWal, WAL_READ_LOCK(0));
1743 return WAL_RETRY;
1744 }
1745 pWal->readLock = 0;
1746 return SQLITE_OK;
1747 }else if( rc!=SQLITE_BUSY ){
1748 return rc;
dan64d039e2010-04-13 19:27:31 +00001749 }
dan7c246102010-04-12 19:00:29 +00001750 }
danba515902010-04-30 09:32:06 +00001751
drh73b64e42010-05-30 19:55:15 +00001752 /* If we get this far, it means that the reader will want to use
1753 ** the WAL to get at content from recent commits. The job now is
1754 ** to select one of the aReadMark[] entries that is closest to
1755 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
1756 */
1757 mxReadMark = 0;
1758 mxI = 0;
1759 for(i=1; i<WAL_NREADER; i++){
1760 u32 thisMark = pInfo->aReadMark[i];
1761 if( mxReadMark<thisMark ){
1762 mxReadMark = thisMark;
1763 mxI = i;
1764 }
1765 }
1766 if( mxI==0 ){
1767 /* If we get here, it means that all of the aReadMark[] entries between
1768 ** 1 and WAL_NREADER-1 are zero. Try to initialize aReadMark[1] to
1769 ** be mxFrame, then retry.
1770 */
1771 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
1772 if( rc==SQLITE_OK ){
dand54ff602010-05-31 11:16:30 +00001773 pInfo->aReadMark[1] = pWal->hdr.mxFrame+1;
drh73b64e42010-05-30 19:55:15 +00001774 walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
1775 }
1776 return WAL_RETRY;
1777 }else{
1778 if( mxReadMark < pWal->hdr.mxFrame ){
dand54ff602010-05-31 11:16:30 +00001779 for(i=1; i<WAL_NREADER; i++){
drh73b64e42010-05-30 19:55:15 +00001780 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
1781 if( rc==SQLITE_OK ){
dan3dee6da2010-05-31 16:17:54 +00001782 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame+1;
drh73b64e42010-05-30 19:55:15 +00001783 mxI = i;
1784 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
1785 break;
1786 }
1787 }
1788 }
1789
1790 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
1791 if( rc ){
1792 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
1793 }
1794 if( pInfo->aReadMark[mxI]!=mxReadMark
1795 || pHdr[0].mxFrame!=pWal->hdr.mxFrame
1796 || (sqlite3OsShmBarrier(pWal->pDbFd), pHdr[1].mxFrame!=pWal->hdr.mxFrame)
1797 ){
1798 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
1799 return WAL_RETRY;
1800 }else{
1801 pWal->readLock = mxI;
1802 }
1803 }
1804 return rc;
1805}
1806
1807/*
1808** Begin a read transaction on the database.
1809**
1810** This routine used to be called sqlite3OpenSnapshot() and with good reason:
1811** it takes a snapshot of the state of the WAL and wal-index for the current
1812** instant in time. The current thread will continue to use this snapshot.
1813** Other threads might append new content to the WAL and wal-index but
1814** that extra content is ignored by the current thread.
1815**
1816** If the database contents have changes since the previous read
1817** transaction, then *pChanged is set to 1 before returning. The
1818** Pager layer will use this to know that is cache is stale and
1819** needs to be flushed.
1820*/
1821int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
1822 int rc; /* Return code */
1823
1824 do{
1825 rc = walTryBeginRead(pWal, pChanged, 0);
1826 }while( rc==WAL_RETRY );
danba515902010-04-30 09:32:06 +00001827 walIndexUnmap(pWal);
dan7c246102010-04-12 19:00:29 +00001828 return rc;
1829}
1830
1831/*
drh73b64e42010-05-30 19:55:15 +00001832** Finish with a read transaction. All this does is release the
1833** read-lock.
dan7c246102010-04-12 19:00:29 +00001834*/
drh73b64e42010-05-30 19:55:15 +00001835void sqlite3WalEndReadTransaction(Wal *pWal){
1836 if( pWal->readLock>=0 ){
1837 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
1838 pWal->readLock = -1;
1839 }
dan7c246102010-04-12 19:00:29 +00001840}
1841
dan5e0ce872010-04-28 17:48:44 +00001842/*
drh73b64e42010-05-30 19:55:15 +00001843** Read a page from the WAL, if it is present in the WAL and if the
1844** current read transaction is configured to use the WAL.
1845**
1846** The *pInWal is set to 1 if the requested page is in the WAL and
1847** has been loaded. Or *pInWal is set to 0 if the page was not in
1848** the WAL and needs to be read out of the database.
dan7c246102010-04-12 19:00:29 +00001849*/
danb6e099a2010-05-04 14:47:39 +00001850int sqlite3WalRead(
danbb23aff2010-05-10 14:46:09 +00001851 Wal *pWal, /* WAL handle */
1852 Pgno pgno, /* Database page number to read data for */
1853 int *pInWal, /* OUT: True if data is read from WAL */
1854 int nOut, /* Size of buffer pOut in bytes */
1855 u8 *pOut /* Buffer to write page data to */
danb6e099a2010-05-04 14:47:39 +00001856){
danc7991bd2010-05-05 19:04:59 +00001857 int rc; /* Return code */
danbb23aff2010-05-10 14:46:09 +00001858 u32 iRead = 0; /* If !=0, WAL frame to return data from */
drh027a1282010-05-19 01:53:53 +00001859 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
danbb23aff2010-05-10 14:46:09 +00001860 int iHash; /* Used to loop through N hash tables */
dan7c246102010-04-12 19:00:29 +00001861
drh73b64e42010-05-30 19:55:15 +00001862 /* This routine is only called from within a read transaction */
1863 assert( pWal->readLock>=0 );
1864
danbb23aff2010-05-10 14:46:09 +00001865 /* If the "last page" field of the wal-index header snapshot is 0, then
1866 ** no data will be read from the wal under any circumstances. Return early
drh73b64e42010-05-30 19:55:15 +00001867 ** in this case to avoid the walIndexMap/Unmap overhead. Likewise, if
1868 ** pWal->readLock==0, then the WAL is ignored by the reader so
1869 ** return early, as if the WAL were empty.
danbb23aff2010-05-10 14:46:09 +00001870 */
drh73b64e42010-05-30 19:55:15 +00001871 if( iLast==0 || pWal->readLock==0 ){
danbb23aff2010-05-10 14:46:09 +00001872 *pInWal = 0;
1873 return SQLITE_OK;
1874 }
1875
1876 /* Ensure the wal-index is mapped. */
danbb23aff2010-05-10 14:46:09 +00001877 rc = walIndexMap(pWal, walMappingSize(iLast));
danc7991bd2010-05-05 19:04:59 +00001878 if( rc!=SQLITE_OK ){
1879 return rc;
1880 }
dancd11fb22010-04-26 10:40:52 +00001881
danbb23aff2010-05-10 14:46:09 +00001882 /* Search the hash table or tables for an entry matching page number
1883 ** pgno. Each iteration of the following for() loop searches one
1884 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
1885 **
1886 ** This code may run concurrently to the code in walIndexAppend()
1887 ** that adds entries to the wal-index (and possibly to this hash
drh6e810962010-05-19 17:49:50 +00001888 ** table). This means the value just read from the hash
danbb23aff2010-05-10 14:46:09 +00001889 ** slot (aHash[iKey]) may have been added before or after the
1890 ** current read transaction was opened. Values added after the
1891 ** read transaction was opened may have been written incorrectly -
1892 ** i.e. these slots may contain garbage data. However, we assume
1893 ** that any slots written before the current read transaction was
1894 ** opened remain unmodified.
1895 **
1896 ** For the reasons above, the if(...) condition featured in the inner
1897 ** loop of the following block is more stringent that would be required
1898 ** if we had exclusive access to the hash-table:
1899 **
1900 ** (aPgno[iFrame]==pgno):
1901 ** This condition filters out normal hash-table collisions.
1902 **
1903 ** (iFrame<=iLast):
1904 ** This condition filters out entries that were added to the hash
1905 ** table after the current read-transaction had started.
1906 **
1907 ** (iFrame>iRead):
1908 ** This filters out a dangerous class of garbage data. The
1909 ** garbage hash slot may refer to a frame with the correct page
1910 ** number, but not the most recent version of the frame. For
drh6e810962010-05-19 17:49:50 +00001911 ** example, if at the start of the read-transaction the WAL
danbb23aff2010-05-10 14:46:09 +00001912 ** contains three copies of the desired page in frames 2, 3 and 4,
1913 ** the hash table may contain the following:
1914 **
drh6e810962010-05-19 17:49:50 +00001915 ** { ..., 2, 3, 4, 99, 99, ..... }
danbb23aff2010-05-10 14:46:09 +00001916 **
1917 ** The correct answer is to read data from frame 4. But a
1918 ** dirty-read may potentially cause the hash-table to appear as
1919 ** follows to the reader:
1920 **
drh6e810962010-05-19 17:49:50 +00001921 ** { ..., 2, 3, 4, 3, 99, ..... }
danbb23aff2010-05-10 14:46:09 +00001922 **
1923 ** Without this part of the if(...) clause, the reader might
1924 ** incorrectly read data from frame 3 instead of 4. This would be
1925 ** an error.
1926 **
1927 ** It is not actually clear to the developers that such a dirty-read
1928 ** can occur. But if it does, it should not cause any problems.
dan7c246102010-04-12 19:00:29 +00001929 */
danbb23aff2010-05-10 14:46:09 +00001930 for(iHash=iLast; iHash>0 && iRead==0; iHash-=HASHTABLE_NPAGE){
drh5939f442010-05-18 13:27:12 +00001931 volatile HASHTABLE_DATATYPE *aHash; /* Pointer to hash table */
1932 volatile u32 *aPgno; /* Pointer to array of page numbers */
danbb23aff2010-05-10 14:46:09 +00001933 u32 iZero; /* Frame number corresponding to aPgno[0] */
1934 int iKey; /* Hash slot index */
drh29d4dbe2010-05-18 23:29:52 +00001935 int mxHash; /* upper bound on aHash[] values */
danbb23aff2010-05-10 14:46:09 +00001936
1937 walHashFind(pWal, iHash, &aHash, &aPgno, &iZero);
drh29d4dbe2010-05-18 23:29:52 +00001938 mxHash = iLast - iZero;
1939 if( mxHash > HASHTABLE_NPAGE ) mxHash = HASHTABLE_NPAGE;
dan6f150142010-05-21 15:31:56 +00001940 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
danbb23aff2010-05-10 14:46:09 +00001941 u32 iFrame = aHash[iKey] + iZero;
dan6f150142010-05-21 15:31:56 +00001942 if( iFrame<=iLast && aPgno[iFrame]==pgno && iFrame>iRead ){
danbb23aff2010-05-10 14:46:09 +00001943 iRead = iFrame;
1944 }
dan7c246102010-04-12 19:00:29 +00001945 }
1946 }
danbb23aff2010-05-10 14:46:09 +00001947 assert( iRead==0 || pWal->pWiData[walIndexEntry(iRead)]==pgno );
dan7c246102010-04-12 19:00:29 +00001948
danbb23aff2010-05-10 14:46:09 +00001949#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
1950 /* If expensive assert() statements are available, do a linear search
1951 ** of the wal-index file content. Make sure the results agree with the
1952 ** result obtained using the hash indexes above. */
1953 {
1954 u32 iRead2 = 0;
1955 u32 iTest;
1956 for(iTest=iLast; iTest>0; iTest--){
1957 if( pWal->pWiData[walIndexEntry(iTest)]==pgno ){
1958 iRead2 = iTest;
dan7c246102010-04-12 19:00:29 +00001959 break;
1960 }
dan7c246102010-04-12 19:00:29 +00001961 }
danbb23aff2010-05-10 14:46:09 +00001962 assert( iRead==iRead2 );
dan7c246102010-04-12 19:00:29 +00001963 }
danbb23aff2010-05-10 14:46:09 +00001964#endif
dancd11fb22010-04-26 10:40:52 +00001965
dan7c246102010-04-12 19:00:29 +00001966 /* If iRead is non-zero, then it is the log frame number that contains the
1967 ** required page. Read and return data from the log file.
1968 */
danbb23aff2010-05-10 14:46:09 +00001969 walIndexUnmap(pWal);
dan7c246102010-04-12 19:00:29 +00001970 if( iRead ){
drh6e810962010-05-19 17:49:50 +00001971 i64 iOffset = walFrameOffset(iRead, pWal->hdr.szPage) + WAL_FRAME_HDRSIZE;
drh7ed91f22010-04-29 22:34:07 +00001972 *pInWal = 1;
drhd9e5c4f2010-05-12 18:01:39 +00001973 return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
dan7c246102010-04-12 19:00:29 +00001974 }
1975
drh7ed91f22010-04-29 22:34:07 +00001976 *pInWal = 0;
dan7c246102010-04-12 19:00:29 +00001977 return SQLITE_OK;
1978}
1979
1980
1981/*
1982** Set *pPgno to the size of the database file (or zero, if unknown).
1983*/
drh7ed91f22010-04-29 22:34:07 +00001984void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno){
drh73b64e42010-05-30 19:55:15 +00001985 assert( pWal->readLock>=0 );
drh7ed91f22010-04-29 22:34:07 +00001986 *pPgno = pWal->hdr.nPage;
dan7c246102010-04-12 19:00:29 +00001987}
1988
dan30c86292010-04-30 16:24:46 +00001989
drh73b64e42010-05-30 19:55:15 +00001990/*
1991** This function starts a write transaction on the WAL.
1992**
1993** A read transaction must have already been started by a prior call
1994** to sqlite3WalBeginReadTransaction().
1995**
1996** If another thread or process has written into the database since
1997** the read transaction was started, then it is not possible for this
1998** thread to write as doing so would cause a fork. So this routine
1999** returns SQLITE_BUSY in that case and no write transaction is started.
2000**
2001** There can only be a single writer active at a time.
2002*/
2003int sqlite3WalBeginWriteTransaction(Wal *pWal){
2004 int rc;
2005 volatile WalCkptInfo *pInfo;
2006
2007 /* Cannot start a write transaction without first holding a read
2008 ** transaction. */
2009 assert( pWal->readLock>=0 );
2010
2011 /* Only one writer allowed at a time. Get the write lock. Return
2012 ** SQLITE_BUSY if unable.
2013 */
2014 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
2015 if( rc ){
2016 return rc;
2017 }
drhc99597c2010-05-31 01:41:15 +00002018 pWal->writeLock = 1;
drh73b64e42010-05-30 19:55:15 +00002019
2020 /* If another connection has written to the database file since the
2021 ** time the read transaction on this connection was started, then
2022 ** the write is disallowed.
2023 */
drh18b7f602010-05-31 14:39:31 +00002024 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
drh73b64e42010-05-30 19:55:15 +00002025 if( rc ){
2026 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
drhc99597c2010-05-31 01:41:15 +00002027 pWal->writeLock = 0;
drh73b64e42010-05-30 19:55:15 +00002028 return rc;
2029 }
2030 if( memcmp(&pWal->hdr, (void*)pWal->pWiData, sizeof(WalIndexHdr))!=0 ){
2031 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
drhc99597c2010-05-31 01:41:15 +00002032 pWal->writeLock = 0;
drh73b64e42010-05-30 19:55:15 +00002033 walIndexUnmap(pWal);
2034 return SQLITE_BUSY;
2035 }
2036
2037 pInfo = walCkptInfo(pWal);
dand54ff602010-05-31 11:16:30 +00002038 if( pWal->readLock==0 ){
2039 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
2040 if( pInfo->nBackfill>0 ){
2041 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
2042 if( rc==SQLITE_OK ){
2043 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
2044 ** readers are currently using the WAL) */
2045 pWal->nCkpt++;
2046 pWal->hdr.mxFrame = 0;
2047 sqlite3Put4byte((u8*)pWal->hdr.aSalt,
2048 1 + sqlite3Get4byte((u8*)pWal->hdr.aSalt));
2049 sqlite3_randomness(4, &pWal->hdr.aSalt[1]);
2050 walIndexWriteHdr(pWal);
2051 pInfo->nBackfill = 0;
drh20e1f082010-05-31 16:10:12 +00002052 memset((void*)&pInfo->aReadMark[1], 0,
2053 sizeof(pInfo->aReadMark)-sizeof(u32));
dand54ff602010-05-31 11:16:30 +00002054 rc = sqlite3OsTruncate(pWal->pDbFd,
2055 ((i64)pWal->hdr.nPage*(i64)pWal->szPage));
2056 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
2057 }
dan30c86292010-04-30 16:24:46 +00002058 }
drh73b64e42010-05-30 19:55:15 +00002059 walUnlockShared(pWal, WAL_READ_LOCK(0));
drhc99597c2010-05-31 01:41:15 +00002060 pWal->readLock = -1;
drh73b64e42010-05-30 19:55:15 +00002061 do{
2062 int notUsed;
2063 rc = walTryBeginRead(pWal, &notUsed, 1);
2064 }while( rc==WAL_RETRY );
dan7c246102010-04-12 19:00:29 +00002065 }
dand54ff602010-05-31 11:16:30 +00002066 walIndexUnmap(pWal);
drh7ed91f22010-04-29 22:34:07 +00002067 return rc;
dan7c246102010-04-12 19:00:29 +00002068}
2069
dan74d6cd82010-04-24 18:44:05 +00002070/*
drh73b64e42010-05-30 19:55:15 +00002071** End a write transaction. The commit has already been done. This
2072** routine merely releases the lock.
2073*/
2074int sqlite3WalEndWriteTransaction(Wal *pWal){
2075 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
dand54ff602010-05-31 11:16:30 +00002076 pWal->writeLock = 0;
drh73b64e42010-05-30 19:55:15 +00002077 return SQLITE_OK;
2078}
2079
2080/*
dan74d6cd82010-04-24 18:44:05 +00002081** If any data has been written (but not committed) to the log file, this
2082** function moves the write-pointer back to the start of the transaction.
2083**
2084** Additionally, the callback function is invoked for each frame written
drh73b64e42010-05-30 19:55:15 +00002085** to the WAL since the start of the transaction. If the callback returns
dan74d6cd82010-04-24 18:44:05 +00002086** other than SQLITE_OK, it is not invoked again and the error code is
2087** returned to the caller.
2088**
2089** Otherwise, if the callback function does not return an error, this
2090** function returns SQLITE_OK.
2091*/
drh7ed91f22010-04-29 22:34:07 +00002092int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
dan55437592010-05-11 12:19:26 +00002093 int rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00002094 if( pWal->writeLock ){
dan55437592010-05-11 12:19:26 +00002095 int unused;
drh027a1282010-05-19 01:53:53 +00002096 Pgno iMax = pWal->hdr.mxFrame;
dan55437592010-05-11 12:19:26 +00002097 Pgno iFrame;
2098
2099 assert( pWal->pWiData==0 );
2100 rc = walIndexReadHdr(pWal, &unused);
dan6f150142010-05-21 15:31:56 +00002101 if( rc==SQLITE_OK ){
drhbab7b912010-05-26 17:31:58 +00002102 rc = walIndexMap(pWal, walMappingSize(iMax));
2103 }
2104 if( rc==SQLITE_OK ){
drh4fa95bf2010-05-22 00:55:39 +00002105 for(iFrame=pWal->hdr.mxFrame+1; rc==SQLITE_OK && iFrame<=iMax; iFrame++){
drh73b64e42010-05-30 19:55:15 +00002106 assert( pWal->writeLock );
drh4fa95bf2010-05-22 00:55:39 +00002107 rc = xUndo(pUndoCtx, pWal->pWiData[walIndexEntry(iFrame)]);
2108 }
danca6b5ba2010-05-25 10:50:56 +00002109 walCleanupHash(pWal);
dan6f150142010-05-21 15:31:56 +00002110 }
dan55437592010-05-11 12:19:26 +00002111 walIndexUnmap(pWal);
dan74d6cd82010-04-24 18:44:05 +00002112 }
2113 return rc;
2114}
2115
dan71d89912010-05-24 13:57:42 +00002116/*
2117** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
2118** values. This function populates the array with values required to
2119** "rollback" the write position of the WAL handle back to the current
2120** point in the event of a savepoint rollback (via WalSavepointUndo()).
drh7ed91f22010-04-29 22:34:07 +00002121*/
dan71d89912010-05-24 13:57:42 +00002122void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
drh73b64e42010-05-30 19:55:15 +00002123 assert( pWal->writeLock );
dan71d89912010-05-24 13:57:42 +00002124 aWalData[0] = pWal->hdr.mxFrame;
2125 aWalData[1] = pWal->hdr.aFrameCksum[0];
2126 aWalData[2] = pWal->hdr.aFrameCksum[1];
dan4cd78b42010-04-26 16:57:10 +00002127}
2128
dan71d89912010-05-24 13:57:42 +00002129/*
2130** Move the write position of the WAL back to the point identified by
2131** the values in the aWalData[] array. aWalData must point to an array
2132** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
2133** by a call to WalSavepoint().
drh7ed91f22010-04-29 22:34:07 +00002134*/
dan71d89912010-05-24 13:57:42 +00002135int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
dan4cd78b42010-04-26 16:57:10 +00002136 int rc = SQLITE_OK;
drh73b64e42010-05-30 19:55:15 +00002137 assert( pWal->writeLock );
dan4cd78b42010-04-26 16:57:10 +00002138
dan71d89912010-05-24 13:57:42 +00002139 assert( aWalData[0]<=pWal->hdr.mxFrame );
2140 if( aWalData[0]<pWal->hdr.mxFrame ){
drh4fa95bf2010-05-22 00:55:39 +00002141 rc = walIndexMap(pWal, walMappingSize(pWal->hdr.mxFrame));
dan71d89912010-05-24 13:57:42 +00002142 pWal->hdr.mxFrame = aWalData[0];
2143 pWal->hdr.aFrameCksum[0] = aWalData[1];
2144 pWal->hdr.aFrameCksum[1] = aWalData[2];
drh4fa95bf2010-05-22 00:55:39 +00002145 if( rc==SQLITE_OK ){
2146 walCleanupHash(pWal);
2147 walIndexUnmap(pWal);
2148 }
dan6f150142010-05-21 15:31:56 +00002149 }
dan4cd78b42010-04-26 16:57:10 +00002150 return rc;
2151}
2152
dan7c246102010-04-12 19:00:29 +00002153/*
dan4cd78b42010-04-26 16:57:10 +00002154** Write a set of frames to the log. The caller must hold the write-lock
2155** on the log file (obtained using sqlite3WalWriteLock()).
dan7c246102010-04-12 19:00:29 +00002156*/
drhc438efd2010-04-26 00:19:45 +00002157int sqlite3WalFrames(
drh7ed91f22010-04-29 22:34:07 +00002158 Wal *pWal, /* Wal handle to write to */
drh6e810962010-05-19 17:49:50 +00002159 int szPage, /* Database page-size in bytes */
dan7c246102010-04-12 19:00:29 +00002160 PgHdr *pList, /* List of dirty pages to write */
2161 Pgno nTruncate, /* Database size after this commit */
2162 int isCommit, /* True if this is a commit */
danc5118782010-04-17 17:34:41 +00002163 int sync_flags /* Flags to pass to OsSync() (or 0) */
dan7c246102010-04-12 19:00:29 +00002164){
dan7c246102010-04-12 19:00:29 +00002165 int rc; /* Used to catch return codes */
2166 u32 iFrame; /* Next frame address */
drh7ed91f22010-04-29 22:34:07 +00002167 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
dan7c246102010-04-12 19:00:29 +00002168 PgHdr *p; /* Iterator to run through pList with. */
drhe874d9e2010-05-07 20:02:23 +00002169 PgHdr *pLast = 0; /* Last frame in list */
dan7c246102010-04-12 19:00:29 +00002170 int nLast = 0; /* Number of extra copies of last page */
2171
dan7c246102010-04-12 19:00:29 +00002172 assert( pList );
drh73b64e42010-05-30 19:55:15 +00002173 assert( pWal->writeLock );
danba515902010-04-30 09:32:06 +00002174 assert( pWal->pWiData==0 );
dan7c246102010-04-12 19:00:29 +00002175
drhc74c3332010-05-31 12:15:19 +00002176#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
2177 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
2178 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
2179 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
2180 }
2181#endif
2182
drha2a42012010-05-18 18:01:08 +00002183 /* If this is the first frame written into the log, write the WAL
2184 ** header to the start of the WAL file. See comments at the top of
2185 ** this source file for a description of the WAL header format.
dan97a31352010-04-16 13:59:31 +00002186 */
drh027a1282010-05-19 01:53:53 +00002187 iFrame = pWal->hdr.mxFrame;
dan97a31352010-04-16 13:59:31 +00002188 if( iFrame==0 ){
drh23ea97b2010-05-20 16:45:58 +00002189 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assembly wal-header in */
danb8fd6c22010-05-24 10:39:36 +00002190 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
drh23ea97b2010-05-20 16:45:58 +00002191 sqlite3Put4byte(&aWalHdr[4], 3007000);
2192 sqlite3Put4byte(&aWalHdr[8], szPage);
drh7e263722010-05-20 21:21:09 +00002193 pWal->szPage = szPage;
danb8fd6c22010-05-24 10:39:36 +00002194 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
drh23ea97b2010-05-20 16:45:58 +00002195 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
drh7e263722010-05-20 21:21:09 +00002196 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
drh23ea97b2010-05-20 16:45:58 +00002197 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
drhc74c3332010-05-31 12:15:19 +00002198 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
dan97a31352010-04-16 13:59:31 +00002199 if( rc!=SQLITE_OK ){
2200 return rc;
2201 }
dan71d89912010-05-24 13:57:42 +00002202 walChecksumBytes(1, aWalHdr, sizeof(aWalHdr), 0, pWal->hdr.aFrameCksum);
dan97a31352010-04-16 13:59:31 +00002203 }
drh7e263722010-05-20 21:21:09 +00002204 assert( pWal->szPage==szPage );
dan97a31352010-04-16 13:59:31 +00002205
drh7e263722010-05-20 21:21:09 +00002206 /* Write the log file. */
dan7c246102010-04-12 19:00:29 +00002207 for(p=pList; p; p=p->pDirty){
2208 u32 nDbsize; /* Db-size field for frame header */
2209 i64 iOffset; /* Write offset in log file */
2210
drh6e810962010-05-19 17:49:50 +00002211 iOffset = walFrameOffset(++iFrame, szPage);
dan7c246102010-04-12 19:00:29 +00002212
2213 /* Populate and write the frame header */
2214 nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
drh7e263722010-05-20 21:21:09 +00002215 walEncodeFrame(pWal, p->pgno, nDbsize, p->pData, aFrame);
drhd9e5c4f2010-05-12 18:01:39 +00002216 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
dan7c246102010-04-12 19:00:29 +00002217 if( rc!=SQLITE_OK ){
2218 return rc;
2219 }
2220
2221 /* Write the page data */
drh6e810962010-05-19 17:49:50 +00002222 rc = sqlite3OsWrite(pWal->pWalFd, p->pData, szPage, iOffset+sizeof(aFrame));
dan7c246102010-04-12 19:00:29 +00002223 if( rc!=SQLITE_OK ){
2224 return rc;
2225 }
2226 pLast = p;
2227 }
2228
2229 /* Sync the log file if the 'isSync' flag was specified. */
danc5118782010-04-17 17:34:41 +00002230 if( sync_flags ){
drhd9e5c4f2010-05-12 18:01:39 +00002231 i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
drh6e810962010-05-19 17:49:50 +00002232 i64 iOffset = walFrameOffset(iFrame+1, szPage);
dan67032392010-04-17 15:42:43 +00002233
2234 assert( isCommit );
drh69c46962010-05-17 20:16:50 +00002235 assert( iSegment>0 );
dan7c246102010-04-12 19:00:29 +00002236
dan7c246102010-04-12 19:00:29 +00002237 iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
2238 while( iOffset<iSegment ){
drh7e263722010-05-20 21:21:09 +00002239 walEncodeFrame(pWal, pLast->pgno, nTruncate, pLast->pData, aFrame);
drhd9e5c4f2010-05-12 18:01:39 +00002240 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
dan7c246102010-04-12 19:00:29 +00002241 if( rc!=SQLITE_OK ){
2242 return rc;
2243 }
2244
drh7ed91f22010-04-29 22:34:07 +00002245 iOffset += WAL_FRAME_HDRSIZE;
drh6e810962010-05-19 17:49:50 +00002246 rc = sqlite3OsWrite(pWal->pWalFd, pLast->pData, szPage, iOffset);
dan7c246102010-04-12 19:00:29 +00002247 if( rc!=SQLITE_OK ){
2248 return rc;
2249 }
2250 nLast++;
drh6e810962010-05-19 17:49:50 +00002251 iOffset += szPage;
dan7c246102010-04-12 19:00:29 +00002252 }
dan7c246102010-04-12 19:00:29 +00002253
drhd9e5c4f2010-05-12 18:01:39 +00002254 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
dan7c246102010-04-12 19:00:29 +00002255 }
danba515902010-04-30 09:32:06 +00002256 assert( pWal->pWiData==0 );
dan7c246102010-04-12 19:00:29 +00002257
drhe730fec2010-05-18 12:56:50 +00002258 /* Append data to the wal-index. It is not necessary to lock the
drha2a42012010-05-18 18:01:08 +00002259 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
dan7c246102010-04-12 19:00:29 +00002260 ** guarantees that there are no other writers, and no data that may
2261 ** be in use by existing readers is being overwritten.
2262 */
drh027a1282010-05-19 01:53:53 +00002263 iFrame = pWal->hdr.mxFrame;
danc7991bd2010-05-05 19:04:59 +00002264 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
dan7c246102010-04-12 19:00:29 +00002265 iFrame++;
danc7991bd2010-05-05 19:04:59 +00002266 rc = walIndexAppend(pWal, iFrame, p->pgno);
dan7c246102010-04-12 19:00:29 +00002267 }
danc7991bd2010-05-05 19:04:59 +00002268 while( nLast>0 && rc==SQLITE_OK ){
dan7c246102010-04-12 19:00:29 +00002269 iFrame++;
2270 nLast--;
danc7991bd2010-05-05 19:04:59 +00002271 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
dan7c246102010-04-12 19:00:29 +00002272 }
2273
danc7991bd2010-05-05 19:04:59 +00002274 if( rc==SQLITE_OK ){
2275 /* Update the private copy of the header. */
drh6e810962010-05-19 17:49:50 +00002276 pWal->hdr.szPage = szPage;
drh027a1282010-05-19 01:53:53 +00002277 pWal->hdr.mxFrame = iFrame;
danc7991bd2010-05-05 19:04:59 +00002278 if( isCommit ){
2279 pWal->hdr.iChange++;
2280 pWal->hdr.nPage = nTruncate;
2281 }
danc7991bd2010-05-05 19:04:59 +00002282 /* If this is a commit, update the wal-index header too. */
2283 if( isCommit ){
drh7e263722010-05-20 21:21:09 +00002284 walIndexWriteHdr(pWal);
danc7991bd2010-05-05 19:04:59 +00002285 pWal->iCallback = iFrame;
2286 }
dan7c246102010-04-12 19:00:29 +00002287 }
danc7991bd2010-05-05 19:04:59 +00002288
drh7ed91f22010-04-29 22:34:07 +00002289 walIndexUnmap(pWal);
drhc74c3332010-05-31 12:15:19 +00002290 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
dan8d22a172010-04-19 18:03:51 +00002291 return rc;
dan7c246102010-04-12 19:00:29 +00002292}
2293
2294/*
drh73b64e42010-05-30 19:55:15 +00002295** This routine is called to implement sqlite3_wal_checkpoint() and
2296** related interfaces.
danb9bf16b2010-04-14 11:23:30 +00002297**
drh73b64e42010-05-30 19:55:15 +00002298** Obtain a CHECKPOINT lock and then backfill as much information as
2299** we can from WAL into the database.
dan7c246102010-04-12 19:00:29 +00002300*/
drhc438efd2010-04-26 00:19:45 +00002301int sqlite3WalCheckpoint(
drh7ed91f22010-04-29 22:34:07 +00002302 Wal *pWal, /* Wal connection */
danc5118782010-04-17 17:34:41 +00002303 int sync_flags, /* Flags to sync db file with (or 0) */
danb6e099a2010-05-04 14:47:39 +00002304 int nBuf, /* Size of temporary buffer */
drh73b64e42010-05-30 19:55:15 +00002305 u8 *zBuf /* Temporary buffer to use */
dan7c246102010-04-12 19:00:29 +00002306){
danb9bf16b2010-04-14 11:23:30 +00002307 int rc; /* Return code */
dan31c03902010-04-29 14:51:33 +00002308 int isChanged = 0; /* True if a new wal-index header is loaded */
dan7c246102010-04-12 19:00:29 +00002309
dan5cf53532010-05-01 16:40:20 +00002310 assert( pWal->pWiData==0 );
dand54ff602010-05-31 11:16:30 +00002311 assert( pWal->ckptLock==0 );
dan39c79f52010-04-15 10:58:51 +00002312
drhc74c3332010-05-31 12:15:19 +00002313 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
drh73b64e42010-05-30 19:55:15 +00002314 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
2315 if( rc ){
2316 /* Usually this is SQLITE_BUSY meaning that another thread or process
2317 ** is already running a checkpoint, or maybe a recovery. But it might
2318 ** also be SQLITE_IOERR. */
danb9bf16b2010-04-14 11:23:30 +00002319 return rc;
2320 }
dand54ff602010-05-31 11:16:30 +00002321 pWal->ckptLock = 1;
dan64d039e2010-04-13 19:27:31 +00002322
danb9bf16b2010-04-14 11:23:30 +00002323 /* Copy data from the log to the database file. */
drh7ed91f22010-04-29 22:34:07 +00002324 rc = walIndexReadHdr(pWal, &isChanged);
danb9bf16b2010-04-14 11:23:30 +00002325 if( rc==SQLITE_OK ){
drhd9e5c4f2010-05-12 18:01:39 +00002326 rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
danb9bf16b2010-04-14 11:23:30 +00002327 }
dan31c03902010-04-29 14:51:33 +00002328 if( isChanged ){
2329 /* If a new wal-index header was loaded before the checkpoint was
drha2a42012010-05-18 18:01:08 +00002330 ** performed, then the pager-cache associated with pWal is now
dan31c03902010-04-29 14:51:33 +00002331 ** out of date. So zero the cached wal-index header to ensure that
2332 ** next time the pager opens a snapshot on this database it knows that
2333 ** the cache needs to be reset.
2334 */
drh7ed91f22010-04-29 22:34:07 +00002335 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
dan31c03902010-04-29 14:51:33 +00002336 }
danb9bf16b2010-04-14 11:23:30 +00002337
2338 /* Release the locks. */
dan87bfb512010-04-30 11:43:28 +00002339 walIndexUnmap(pWal);
drh73b64e42010-05-30 19:55:15 +00002340 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
dand54ff602010-05-31 11:16:30 +00002341 pWal->ckptLock = 0;
drhc74c3332010-05-31 12:15:19 +00002342 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
dan64d039e2010-04-13 19:27:31 +00002343 return rc;
dan7c246102010-04-12 19:00:29 +00002344}
2345
drh7ed91f22010-04-29 22:34:07 +00002346/* Return the value to pass to a sqlite3_wal_hook callback, the
2347** number of frames in the WAL at the point of the last commit since
2348** sqlite3WalCallback() was called. If no commits have occurred since
2349** the last call, then return 0.
2350*/
2351int sqlite3WalCallback(Wal *pWal){
dan8d22a172010-04-19 18:03:51 +00002352 u32 ret = 0;
drh7ed91f22010-04-29 22:34:07 +00002353 if( pWal ){
2354 ret = pWal->iCallback;
2355 pWal->iCallback = 0;
dan8d22a172010-04-19 18:03:51 +00002356 }
2357 return (int)ret;
2358}
dan55437592010-05-11 12:19:26 +00002359
2360/*
drh61e4ace2010-05-31 20:28:37 +00002361** This function is called to change the WAL subsystem into or out
2362** of locking_mode=EXCLUSIVE.
dan55437592010-05-11 12:19:26 +00002363**
drh61e4ace2010-05-31 20:28:37 +00002364** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
2365** into locking_mode=NORMAL. This means that we must acquire a lock
2366** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
2367** or if the acquisition of the lock fails, then return 0. If the
2368** transition out of exclusive-mode is successful, return 1. This
2369** operation must occur while the pager is still holding the exclusive
2370** lock on the main database file.
dan55437592010-05-11 12:19:26 +00002371**
drh61e4ace2010-05-31 20:28:37 +00002372** If op is one, then change from locking_mode=NORMAL into
2373** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
2374** be released. Return 1 if the transition is made and 0 if the
2375** WAL is already in exclusive-locking mode - meaning that this
2376** routine is a no-op. The pager must already hold the exclusive lock
2377** on the main database file before invoking this operation.
2378**
2379** If op is negative, then do a dry-run of the op==1 case but do
2380** not actually change anything. The pager uses this to see if it
2381** should acquire the database exclusive lock prior to invoking
2382** the op==1 case.
dan55437592010-05-11 12:19:26 +00002383*/
2384int sqlite3WalExclusiveMode(Wal *pWal, int op){
drh61e4ace2010-05-31 20:28:37 +00002385 int rc;
2386 assert( pWal->writeLock==0 && pWal->readLock>=0 );
2387 if( op==0 ){
2388 if( pWal->exclusiveMode ){
2389 pWal->exclusiveMode = 0;
2390 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
2391 pWal->exclusiveMode = 1;
2392 }
2393 rc = pWal->exclusiveMode==0;
2394 }else{
2395 /* No changes. Either already in locking_mode=NORMAL or else the
2396 ** acquisition of the read-lock failed. The pager must continue to
2397 ** hold the database exclusive lock. */
2398 rc = 0;
2399 }
2400 }else if( op>0 ){
2401 assert( pWal->exclusiveMode==0 );
2402 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
2403 pWal->exclusiveMode = 1;
2404 rc = 1;
2405 }else{
2406 rc = pWal->exclusiveMode==0;
dan55437592010-05-11 12:19:26 +00002407 }
drh61e4ace2010-05-31 20:28:37 +00002408 return rc;
dan55437592010-05-11 12:19:26 +00002409}
2410
dan5cf53532010-05-01 16:40:20 +00002411#endif /* #ifndef SQLITE_OMIT_WAL */